Check procs for sub boards.

This commit is contained in:
2019-10-26 00:15:30 +02:00
parent dcddb96f93
commit b0bdb16b4a
4 changed files with 147 additions and 25 deletions

View File

@@ -1,21 +1,10 @@
import strformat
import sets
type
Board*[T] =
array[3, array[3, T]]
Mark* = enum
mPlayer1, # The mark of the fist player
mPlayer2, # The mark of the second player
mFree # This mark signals that a cell is empty
BoardResult* = enum
rPlayer1, # The first player has won the board
rPlayer2, # The second player has won the board
rDraw, # There is no winner. The board has ended in a draw
rOpen # The game on this board is still ongoing
include libmttt/types
include libmttt/checks
proc newBoard[T](initial: T): Board[T] =
## Create a new game board filled with the initial value
result = [
[initial, initial, initial],
[initial, initial, initial],
@@ -23,20 +12,38 @@ proc newBoard[T](initial: T): Board[T] =
]
proc newMetaBoard[T](val: T): Board[Board[T]] =
## Create the meta board, composed out of 9 normal boards.
[
[newBoard(val), newBoard(val), newBoard(val)],
[newBoard(val), newBoard(val), newBoard(val)],
[newBoard(val), newBoard(val), newBoard(val)]
]
proc createBoard*(): Board[Board[Mark]] =
newMetaBoard(mFree)
proc newGame*(player1, player2: Player): GameState =
## Create a new game board
GameState(
players: [player1, player2],
currentPlayer: player1,
result: rOpen,
board: newMetaBoard(mFree))
proc checkBoard*(board: Board[Mark]): BoardResult =
for x in 0 ..< board.len:
for y in 0 ..< board.len:
echo fmt"Cell (x: {x}, y: {y}) = {board[x][y]}"
## Perform a check on a single sub board to see its result
# Create a seconded, transposed board.
# This way 'checkRows' can be used to check the columns
var transposed = newBoard(mFree);
for x in 0 .. 2:
for y in 0 .. 2:
transposed[x][y] = board[y][x]
var states: HashSet[BoardResult]
states.init()
for b in [board, transposed]:
states.incl(checkRows(b))
return selectResult(states)
proc checkBoard*(board: Board[Board[Mark]]): BoardResult =
## Perform a check on a metaboard to see the overall game result
rOpen