【delphi开源代码栏目提醒】:本文主要为网学会员提供moves.pas,希望对需要moves.pas网友有所帮助,学习一下!
unit moves;
interface
Const bdEmptySlot=0;
Type TBoard = Array[0..8] of Integer;
TMove=Class
private
Pred: TMove;
Public
Board: TBoard;
Tiefe: Integer;
Constructor Create(b: TBoard);
Destructor Destroy;override;
Function IsSolve: Boolean;
Function NextCount: Integer;
Function EmptySlot: Integer;
Function GetNext(index: Integer): TMove;
Function GetID: LongInt;
Function Distance: Integer;
Property Predecessor: TMove read Pred;
End;
implementation
Constructor TMove.Create(b: TBoard);
Begin
Move(b,Board,SizeOf(TBoard));
Pred:=Nil;
End;
Destructor TMove.Destroy;
Begin
inherited Destroy;
End;
Function TMove.IsSolve: Boolean;
Var i: Integer;
Begin
Result:=True;
For i:=0 to 7 Do
If Board[i]<>(i+1) Then
Begin
Result:=False;
Break;
End;
End;
Function TMove.NextCount: Integer;
var
tmp: Integer;
Begin
tmp:=EmptySlot;
if(tmp=4) then
Result:=4
else
if odd(tmp) Then
Result:=3
else
Result:=2;
End;
Function TMove.EmptySlot: Integer;
var
slot: Integer;
Begin
slot:=0;
while(slot<9) Do If Board[slot]=0 Then Break Else Inc(slot);
Result:=slot;
End;
Function TMove.GetNext(index: Integer): TMove;
var tmpCount, tmpSlot: Integer;
var tmpMove: TMove;
Begin
if Index>=NextCount Then
Begin
Result:=nil;
exit;
End;
tmpCount:=0;
tmpSlot:=EmptySlot;
If(EmptySlot>2) Then
Begin
Inc(tmpCount);
If(tmpCount=(index+1)) Then
Begin
tmpMove:=TMove.Create(Board);
tmpMove.Board[tmpSlot]:=tmpMove.Board[tmpSlot-3];
tmpMove.Board[tmpSlot-3]:=0;
tmpMove.Pred:=Self;
tmpMove.Tiefe:=Self.Tiefe+1;
Result:=tmpMove;
exit;
End;
End;
If(EmptySlot Mod 3>0) Then
Begin
Inc(tmpCount);
If(tmpCount=(index+1)) Then
Begin
tmpMove:=TMove.Create(Board);
tmpMove.Board[tmpSlot]:=tmpMove.Board[tmpSlot-1];
tmpMove.Board[tmpSlot-1]:=0;
tmpMove.Pred:=Self;
tmpMove.Tiefe:=Self.Tiefe+1;
Result:=tmpMove;
exit;
End;
End;
If(EmptySlot Mod 3<2) Then
Begin
Inc(tmpCount);
If(tmpCount=(index+1)) Then
Begin
tmpMove:=TMove.Create(Board);
tmpMove.Board[tmpSlot]:=tmpMove.Board[tmpSlot+1];
tmpMove.Board[tmpSlot+1]:=0;
tmpMove.Pred:=Self;
tmpMove.Tiefe:=Self.Tiefe+1;
Result:=tmpMove;
exit;
End;
End;
If(EmptySlot<6) Then
Begin
Inc(tmpCount);
If(tmpCount=(index+1)) Then
Begin
tmpMove:=TMove.Create(Board);
tmpMove.Board[tmpSlot]:=tmpMove.Board[tmpSlot+3];
tmpMove.Board[tmpSlot+3]:=0;
tmpMove.Pred:=Self;
tmpMove.Tiefe:=Self.Tiefe+1;
Result:=tmpMove;
exit;
End;
End;
Result:=nil;
End;
Function TMove.GetID: LongInt;
Var
tmp: LongInt;
I: Integer;
Begin
tmp:=0;
For i:=0 To 8 Do
tmp:=tmp*10+Board[i];
Result:=tmp;
End;
Function TMove.Distance: Integer;
var
i, sx,sy,g,gx,gy, tmp: Integer;
const
dx=3;
dy=3;
Begin
i:= -1;
tmp:=0;
for sy:= 0 to dy-1 Do
for sx:= 0 to dx-1 Do
Begin
Inc(i);
g:= Board[i]-1;
if (g = -1) Then continue;
gx:= g Mod dx;
gy:= g Div dx;
tmp:=tmp+abs(gy - sy) +abs(gx - sx);
End;
Result:=tmp;
End;
end.