Define game.new()=
Prgm
a:={_}
b:={_}
c:={_}
d:={_}
DelVar grid
grid:=newMat(3,3)
block.c:=0
block.r:=0
EndPrgm
Define place(x,y)=
Prgm
If 1>x>3 or 1>y>3 or grid[x,y]≠0
Disp "Invalid move."
Else
grid[x,y]:=1
a:=augment(a,{x})
b:=augment(b,{y})
turn:=0
win(x,y)
EndIf
EndPrgm
Define win(x,y)=
Prgm
diaguno:=grid[1,1]+grid[2,2]+grid[3,3]
diagdos:=grid[1,3]+grid[2,2]+grid[3,1]
For n,1,3
column:=mat▶List(grid*[[1][1][1]])[n]
row:=mat▶List([1,1,1]*grid)[n]
If column=2
block.c:=n
If row=2
block.r=n
If column=3 or row=3 or diaguno=3 or diagdos=3 Then
Disp "Player wins."
n:=3
turn:=-1
ElseIf sum(mat▶List(grid))>44 Then
Disp "Tie game."
n:=3
turn=-1
ElseIf column=30 or row=30 or diaguno=30 or diagdos=30 Then
Disp "Computer wins."
n:=3
EndIf
EndFor
If turn=0 Then
computer(x,y)
EndIf
End Prgm
Define computer(x,y)=
Prgm
If block.c>0 Then
For n,1,3
If grid[block.c,n]=0 Then
x:=block.c
y:=n
EndIf
EndFor
ElseIf block.r>0 Then
For n,1,3
If grid[n,block.r]=0 Then
x:=n
y:=block.r
EndIf
EndFor
While grid[x,y]≠0
x:=randInt(1,3)
y:=randInt(1,3)
EndWhile
grid[x,y]:=10
c:=augment(c,{x}
d:=augment(d,{y}
turn:=1
win(x,y)
EndPrgm
a,b and c,d are shown on a scatter plot graph, with a window of 0<x<4 and 0<y<4, as crosses and big empty circles. The usual lines of a Tic-Tac-Toe game are simply drawn in with segments.
I would like to how to make the computer have somewhat of an intelligence too, instead of just being random and typically losing.
February 17 [6:00] - I changed any boolean value checkers to be more effecient (ex: While grid[x,y]=1 or grid[x,y]=10 to While grid[x,y]≠0), and added something of an AI. At the moment the AI blocks you vertically and horizontally, but not diagonally. I'm making this update right now because I'm getting a really unexpected error. For some reason, the AI won't block you horizontally right after blocking you vertically, but it will do fine otherwise, it seems like. Take a look at my game below. I've recreated the issue a few times, too..
game.new()
place(2,2)
- computer places at 1,1
place(2,1)
- computer places at 2,3
place(1,2)
- computer places at 3,3
3 - - o
2 x x -
1 o x -
0 1 2 3
Read the coordinates as if the table is in the first quadrant of a graph.. because it is.
Please tell me what I did wrong. Other optimizations are still welcomed, by the way.