Added initial work on tic tac toe

This commit is contained in:
Nocturn9x 2023-01-11 14:23:30 +01:00
parent d813d30eaa
commit 93196c4200
4 changed files with 1219 additions and 1 deletions

1
.gitignore vendored
View File

@ -2,4 +2,3 @@
nimcache/ nimcache/
nimblecache/ nimblecache/
htmldocs/ htmldocs/

107
src/game.nim Normal file
View File

@ -0,0 +1,107 @@
# Copyright 2022 Mattia Giambirtone & All Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import util/matrix
type
TileKind* = enum
## A tile enumeration kind
Empty = 0,
Self,
Enemy
GameStatus* = enum
## A game status enumeration
Playing,
Win,
Lose,
Draw
TicTacToeGame* = ref object
map*: Matrix[int]
last: TileKind
proc newTicTacToe*: TicTacToeGame =
## Creates a new TicTacToe object
new(result)
result.map = zeros[int]((3, 3))
proc get*(self: TicTacToeGame): GameStatus =
## Returns the game status
# Checks the rows
for _, row in self.map:
if all(row == newMatrix[int](@[1, 1, 1])):
return Win
elif all(row == newMatrix[int](@[2, 2, 2])):
return Lose
# Checks the columns
for _, col in self.map.transpose():
if all(col == newMatrix[int](@[1, 1, 1])):
return Win
elif all(col == newMatrix[int](@[2, 2, 2])):
return Lose
# Checks the diagonals
if all(self.map.diag() == newMatrix[int](@[1, 1, 1])):
return Win
elif all(self.map.diag() == newMatrix[int](@[2, 2, 2])):
return Lose
# Top right diagonal (we flip the matrix left to right so
# that the diagonal gets shifted on the other side)
elif all(self.map.fliplr().diag() == newMatrix[int](@[1, 1, 1])):
return Win
elif all(self.map.fliplr().diag() == newMatrix[int](@[2, 2, 2])):
return Lose
# No check was successful and there's no empty slots: draw!
if not any(self.map == 0):
return Draw
# There are empty slots and no one won yet, we're still in game!
return Playing
proc `$`*(self: TicTacToeGame): string =
## Stringifies self
for i, row in self.map:
for j, e in row:
if e == 0:
result &= "_"
elif e == 1:
result &= "X"
else:
result &= "O"
if j in 0..8:
result &= " "
if i < 2:
result &= "\n"
proc place*(self: TicTacToeGame, tile: TileKind, x, y: int) =
## Places a tile onto the playing board
if TileKind(self.map[x, y]) == Empty:
self.map[x, y] = int(tile)
proc asGame*(self: Matrix[int]): TicTacToeGame =
## Wraps a 3x3 matrix into a tris game
## object
assert self.shape == (3, 3)
new(result)
result.map = self
proc build*(data: seq[int]): TicTacToeGame =
## Builds a tris game from a flat
## sequence
new(result)
result.map = newMatrixFromSeq[int](data, (3, 3))

96
src/player.nim Normal file
View File

@ -0,0 +1,96 @@
# Copyright 2022 Mattia Giambirtone & All Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import game
import util/matrix
type
Move = ref object
## A specific state in a
## tic-tac-toe match, with
## all of its children states
state: Matrix[int]
# Since tic-tac-toe is a rather
# simple game, we can generate all
# possible (legal) board configurations
# and then look up the current board when
# playing against the user in order to find
# the best move to win the match
next: array[9, Move]
parent: Move
depth: int
proc generateMoves*(map: Matrix[int], turn: TileKind, depth: int = 0): Move =
## Generates the full tree of all
## possible tic tac toe moves starting
## from a given board state
new(result)
result.state = map.copy()
result.depth = depth
if result.state.asGame().get() != Playing:
# The game is over, no need to generate
# any more moves!
return
for row in 0..<map.shape.rows:
for col in 0..<map.shape.cols:
if TileKind(result.state[row, col]) == Empty:
let index = row * map.shape.cols + col
new(result.next[index])
result.next[index].parent = result
var copy = result.state.copy()
copy[row, col] = turn.int()
result.next[index] = generateMoves(copy, if turn == Self: Enemy else: Self, depth + 1)
proc exists*(map: Matrix[int], tree: Move): int =
## Returns the depth of a given move in
## the solution tree. A return value of -1
## indicates the move is illegal
if all(map == tree.state):
echo map.asGame()
return tree.depth
else:
var i = 0
var idx: tuple[row, col: int]
while i < 9:
idx = ind2sub(i, map.shape)
if tree.next[i].isNil() or tree.next[i].state[idx.row, idx.col] != map[idx.row, idx.col]:
inc(i)
continue
elif map.exists(tree.next[i]) != -1:
return tree.next[i].depth
inc(i)
return -1
proc print(self: Move) =
## Traverses the move tree recursively
## (meant for debugging)
if self.isNil():
return
var board = self.state.asGame()
echo board
echo board.get(), "\n"
for i in 0..<9:
print(self.next[i])
when isMainModule:
var g = build(@[0, 0, 0, 0, 0, 0, 0, 0, 0])
let m = generateMoves(g.map, Self)
g = build(@[1, 1, 2, 2, 2, 1, 1, 2, 1])
echo g.map.exists(m)
g = build(@[1, 1, 2, 2, 2, 1, 1, 2, 2])
echo g.map.exists(m)

1016
src/util/matrix.nim Normal file

File diff suppressed because it is too large Load Diff