CPG/src/player.nim

97 lines
3.1 KiB
Nim

# 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)