Skip to content

Commit

Permalink
state-of-tic-tac-toe: fix generator
Browse files Browse the repository at this point in the history
  • Loading branch information
ErikSchierboom committed Oct 22, 2024
1 parent 46106b8 commit a2b738e
Show file tree
Hide file tree
Showing 4 changed files with 282 additions and 303 deletions.
14 changes: 8 additions & 6 deletions exercises/practice/state-of-tic-tac-toe/.meta/Example.fs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ type Board = Cell [,]
let won (player: Cell) (board: Board) =
let winning = [| player; player; player |]

Array.init 3 (fun i -> board[i, i]) = winning ||
Array.init 3 (fun i -> board[i, 2 - i]) = winning
|| Array.init 3 (fun i -> board[i, *]) |> Array.contains winning
|| Array.init 3 (fun i -> board[*, i]) |> Array.contains winning

let gameState (board: Board) =
Array.init 3 (fun i -> board[i, i]) = winning
|| Array.init 3 (fun i -> board[i, 2 - i]) = winning
|| Array.init 3 (fun i -> board[i, *])
|> Array.contains winning
|| Array.init 3 (fun i -> board[*, i])
|> Array.contains winning

let gamestate (board: Board) =
let numCells cell =
board
|> Seq.cast
Expand Down
48 changes: 44 additions & 4 deletions exercises/practice/state-of-tic-tac-toe/StateOfTicTacToe.fs
Original file line number Diff line number Diff line change
@@ -1,7 +1,47 @@
module StateOfTicTacToe

// TODO: define the 'EndGameState' type
// TODO: define the 'GameError' type
type EndGameState =
| Win
| Draw
| Ongoing

let gameState board =
failwith "Please implement the 'gameState' function"
type GameError =
| ConsecutiveMovesBySamePlayer
| WrongPlayerStarted
| MoveMadeAfterGameWasDone

type Cell = char
type Board = Cell [,]

let won (player: Cell) (board: Board) =
let winning = [| player; player; player |]

Array.init 3 (fun i -> board[i, i]) = winning
|| Array.init 3 (fun i -> board[i, 2 - i]) = winning
|| Array.init 3 (fun i -> board[i, *])
|> Array.contains winning
|| Array.init 3 (fun i -> board[*, i])
|> Array.contains winning

let gamestate (board: Board) =
let numCells cell =
board
|> Seq.cast
|> Seq.filter ((=) cell)
|> Seq.length

let numNaughts = numCells 'O'
let numCrosses = numCells 'X'

if abs (numCrosses - numNaughts) > 1 then
Error ConsecutiveMovesBySamePlayer
elif numNaughts > numCrosses then
Error WrongPlayerStarted
elif won 'X' board && won 'O' board then
Error MoveMadeAfterGameWasDone
elif won 'X' board || won 'O' board then
Ok Win
elif numNaughts + numCrosses = 9 then
Ok Draw
else
Ok Ongoing
Loading

0 comments on commit a2b738e

Please sign in to comment.