Now this should be easy but for some reason I’m having a lot of trouble with it.
I didn’t want to simply download a source code and implement it, I wanted to try and work it out, but Im not having much luck.
type
Matrix = array[1..3,1..3] of char;
Coordinate =
record
x,y:integer;
end;
....
function FindBestMove(nMat:matrix; c:char):Coordinate;
var bestMove:coordinate;
newCoord:coordinate;
found:boolean;
j:Integer;
k:Integer;
begin
found := false;
if GetPossibleMoves(nMat) = 1 then //If only one find the last square (even though its inefficient as of now, but thats just temporary)
begin
while not found do
begin
newCoord.x:=Random(3)+1;
newCoord.y:=Random(3)+1;
found:=nMat[newCoord.x,newCoord.y]=' ';
end;
FindBestMove := newCoord;
Exit;
end;
bestMove.x := 0; bestMove.y := 0;
//Check for a winning square, if theres more than one empty
for j := 1 to 3 do
begin
for k := 1 to 3 do
begin
newCoord.x:=j; newCoord.y:=k;
if (nMat[newCoord.x,newCoord.y]=' ') then
begin
nMat[newCoord.x,newCoord.y] := c;
showMessage('nkl');
if CheckWin(nMat,c) then
begin
FindBestMove := newCoord;
showMessage('1st');
Exit;
end
else nMat[newCoord.x,newCoord.y] := ' ';
end;
end;
end;
//If none win, check for a block
for j := 1 to 3 do
begin
for k := 1 to 3 do
begin
newCoord.x:=j; newCoord.y:=k;
if (nMat[newCoord.x,newCoord.y]=' ') then
begin
nMat[newCoord.x,newCoord.y] := c;
if CheckWin(nMat,Rev(c)) then
begin
FindBestMove := newCoord;
showMessage('2nd');
Exit;
end
else nMat[newCoord.x,newCoord.y]:= ' ';
end;
end;
end;
//If none win and none block, simply choose an empty square at random.
found := false;
while not found do
begin
newCoord.x:=Random(3)+1;
newCoord.y:=Random(3)+1;
found:=nMat[newCoord.x,newCoord.y]=' ';
end;
nMat[newCoord.x,newCoord.y] := c;
bestMove := FindBestMove(nMat, rev(c)); //Continue to find the best move for the opposite player
FindBestMove:=bestMove;
end;
However it doesn’t work. At all.
Any ideas? Guidance would be great.