--- Tic-tac-toe is a paper-and-pencil game for two players who take turns marking the spaces
--- in a three-by-three grid with X or O.
--- The player who succeeds in placing three of their marks in a horizontal, vertical, or
--- diagonal row is the winner. It is a solved game, with a forced draw assuming best play from both players.
module Logic.Game;

import Stdlib.Prelude open;
import Logic.Extra open public;
import Logic.Board open public;
import Logic.GameState open public;

--- Checks if we reached the end of the game.
checkState : GameState  GameState
  | (state b p e) :=
      (won (state b p e))
        (terminate ("Player " ++str showSymbol (switch p) ++str " wins!")))
        (draw (state b p e))
        (state b p (terminate "It's a draw!"))
        (state b p e));

--- Given a player attempted move, updates the state accordingly.
playMove : Maybe Nat  GameState  GameState
  | nothing (state b p _) :=
    state b p (continue "\nInvalid number, try again\n")
  | (just k) (state (board s) player e) :=
      (not (elem (==) k (possibleMoves (flatten s))))
        (board s)
        (continue "\nThe square is already occupied, try again\n"))
          (board (map (map (replace player k)) s))
          (switch player)

--- Returns ;just; if the given ;Nat; is in range of 1..9
validMove (n : Nat) : Maybe Nat := if (n <= 9 && n >= 1) (just n) nothing;
Last modified on 2024-04-19 16:39 UTC