-
-
Notifications
You must be signed in to change notification settings - Fork 102
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
46106b8
commit a2b738e
Showing
4 changed files
with
282 additions
and
303 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 44 additions & 4 deletions
48
exercises/practice/state-of-tic-tac-toe/StateOfTicTacToe.fs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Oops, something went wrong.