//我的代码如下: (有点土,高手莫笑,呵呵)
//计算机一开始就会猜一个数字,所以,在运行程序前,先想一个数字,呵呵
//------------------------------------------------
nit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit
//写入位置正确的有几个
Label1: TLabel;
Label2: TLabel;
Edit2: TEdit
//写入数字正确,但是位置不对的有几个
Edit3: TEdit;
Label3: TLabel;
Button2: TButton;
Memo1: TMemo
//用来列出所有可能的数字
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
MYNUMBER:Integer;//猜的数字数量
RightP:Integer;//位置正确的数量
RightN:Integer;//个数正确的数量
NumListO:TStringList;//原始列表
NumListT:TStringList;//临时列表
{ Private declarations }
public
procedure InitNumbers(n:Integer)
//初始化数字,n=3,4,5,6
function PushNumber:String
//猜数字
procedure CheckNumber(n:Integer)
//根据人工填入的数字进行判断
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
Procedure TForm1.CheckNumber(n:Integer);
var
LastGuess:String;
i,j,k:Integer;
PGuess,NGuess:Integer;
begin
NumListT.Clear;
PGuess:=0;
NGuess:=0;
RightP:=StrToInt(Edit1.Text);
RightN:=StrToInt(Edit2.Text);
LastGuess:=Edit3.Text;
for i:=0 to NumListO.Count-1 do
begin
for j:=1 to n do
begin
if NumListO.Strings[j]=LastGuess[j] then
Inc(PGuess);
for k:=1 to n do
if (NumListO.Strings[j]=LastGuess[k]) and (j<>k) then
inc(NGuess);
end;
if (NGuess=RightN) and (PGuess=RightP) then
begin
NumListT.Add(NumListO.Strings);
end;
NGuess:=0;
PGuess:=0;
end;
Form1.Caption:=IntToStr(NumListT.Count)
//看看总计有多少种可能性
NumListO.Clear;
NumListO.Assign(NumListT);
end;
function TForm1.PushNumber:String;
var
numcount:Integer;
begin
numcount:=NumListO.Count;
if numcount>0 then
begin
Randomize;
Result:=NumListO.Strings[Random(NumCount-1)];
end;
//
end;
procedure TForm1.InitNumbers(n:Integer);
var
i,j,k,l,m,o:Integer;
begin
NumListO.Clear;
for i:=0 to 9 do
for j:=0 to 9 do
if j<>i then
for k:=0 to 9 do
if (k<>j) and (k<>i) then
if n=3 then
NumListO.Add(IntToStr(i)+IntToStr(j)+IntToStr(k))
else
for l:=0 to 9 do
if (l<>i) and (l<>j) and (l<>k) then
begin
if n=4 then
NumListO.Add(IntToStr(i)+IntToStr(j)+IntToStr(k)+IntToStr(l))
else
for m:=0 to 9 do
if (m<>i) and (m<>j) and (m<>k) and (m<>l) then
if n=5 then
NumListO.Add(IntToStr(i)+IntToStr(j)+IntToStr(k)+IntToStr(l)+IntToStr(m))
else
for o:=0 to 9 do
if (o<>i) and (o<>j) and (o<>k) and (o<>l) and (o<>m) then
NumListO.Add(IntToStr(i)+IntToStr(j)+IntToStr(k)+IntToStr(l)+IntToStr(m)+IntToStr(o));
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
CheckNumber(MYNUMBER);
Edit3.Text:=PushNumber;
Memo1.Lines.Clear;
Memo1.Lines.Assign(NumListO);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
NumListO:=TStringList.Create;
NumListT:=TStringList.Create;
MYNUMBER:=6;
initNumbers(MYNUMBER);
Edit3.Text:=PushNumber;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
initnumbers(MYNUMBER);
Edit1.Text:='';
Edit2.Text:='';
Edit3.Text:=PushNumber;
end;
end.