NNExperiments/src/nn/util/tris.nim

84 lines
2.1 KiB
Nim

import matrix
type
TileKind* = enum
## A tile enumeration kind
Empty = 0,
Self,
Enemy
GameStatus* = enum
## A game status enumeration
Playing,
Win,
Lose,
Draw
TrisGame* = ref object
map*: Matrix[int]
moves*: int
proc newTrisGame*: TrisGame =
## Creates a new TrisGame object
new(result)
result.map = zeros[int]((3, 3))
result.moves = 0
proc get*(self: TrisGame): GameStatus =
## Returns the game status
# Checks for 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 for 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 for diagonals
for i in 0..<2:
if all(self.map.diag(i) == newMatrix[int](@[1, 1, 1])):
return Win
elif all(self.map.diag(i) == 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: TrisGame): string =
## Stringifies self
return $self.map
proc place*(self: TrisGame, 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)
if tile == Self:
inc(self.moves)
when isMainModule:
var game = newTrisGame()
game.place(Enemy, 0, 0)
game.place(Enemy, 0, 1)
assert game.get() == Playing
game.place(Enemy, 0, 2)
assert game.get() == Lose
game.place(Self, 0, 2)
assert game.get() == Playing
game.place(Enemy, 1, 1)
game.place(Enemy, 2, 2)
assert game.get() == Lose
game.place(Self, 2, 2)
assert game.get() == Playing
game.place(Self, 1, 2)
assert game.get() == Win