Delphi 实现刘谦春晚魔术
试试看
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes;
var
list, removeElement: TStringList;
i, NameCount, insertIndex, directCount, sexCount: Integer;
tmp, element, hiddenEle1, hiddenEle2: String;
procedure Fun1(NameCount: Integer);
begin
if NameCount < list.Count then
begin
for i := 0 to NameCount - 1 do
begin
element := list[0]; // 获取第0个元素
list.Delete(0); // 移除第0个元素
list.Add(element); // 将第0个元素添加到最后
end;
end;
end;
procedure Fun2(forCount: Integer);
begin
// 被删除掉的三张牌
removeElement := TStringList.Create;
for i := 0 to forCount - 1 do
begin
removeElement.Add(list[0]);
list.Delete(0);
end;
Writeln(Format('被删除掉的%D张牌:%s', [forCount, removeElement.CommaText]));
Writeln('删除之后:' + list.CommaText);
// 把拿到的三张牌插到中间
Randomize;
insertIndex := Random(list.Count - 1) + 1; // 生成一个介于第一个和倒数第二个位置之间的随机插入位置
Writeln('插入位置:' + insertIndex.ToString);
for i := removeElement.Count - 1 downto 0 do
begin
list.Insert(insertIndex, removeElement[i]);
end;
end;
procedure Fun3();
begin
// 藏起来第一张牌
hiddenEle1 := list.Strings[0];
list.Delete(0);
end;
procedure Fun4(Count: Integer);
begin
for i := 0 to Count - 1 do
begin
list.Delete(0);
end
end;
procedure Fun5();
begin
for i := 0 to 6 do
begin
element := list[0];
list.Delete(0);
list.Add(element);
end;
end;
function Fun6(sexCount: Integer): string;
var
forCount: Integer;
begin
forCount := 0;
if sexCount = 1 then
forCount := 5 // 男生要5次
else
forCount := 4;
for i := 0 to forCount - 1 do
begin
// 把第一张牌放到数组最后面 (好运留下来)
element := list[0];
list.Delete(0);
list.Add(element);
// 烦恼丢出去
list.Delete(0);
end;
result := list[0];
end;
begin
try
try
list := TStringList.Create;
list.CommaText := 'A,B,C,D,A,B,C,D';
Writeln('初始牌组:' + list.CommaText);
Writeln('请输入你的名字有几个字:');
ReadLn(tmp);
NameCount := tmp.ToInteger;
Fun1(NameCount);
Writeln('变化之后:' + list.CommaText);
Fun2(3);
Writeln('插入三张牌后:' + list.CommaText);
Fun3();
Writeln('藏起来第一张牌后:' + list.CommaText);
Writeln('北方-1 南方-2 不南不北-3,请输入对应数字:');
ReadLn(tmp);
directCount := tmp.ToInteger;
Fun2(directCount);
Writeln('南北方人后:' + list.CommaText);
Writeln('男-1 女-2,请输入对应数字:');
ReadLn(tmp);
sexCount := tmp.ToInteger;
Fun4(sexCount);
Writeln('男女生后:' + list.CommaText);
Fun5();
Writeln('见证奇迹后:' + list.CommaText);
Writeln('开始好运留下了 烦恼丢出去');
hiddenEle2 := Fun6(sexCount);
Writeln(Format('牌1:%s 牌2:%s', [hiddenEle1, hiddenEle2]));
ReadLn;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
finally
removeElement.Free;
list.Free;
end;
end.