-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTicTacToe.hs
52 lines (41 loc) · 1.57 KB
/
TicTacToe.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
{-# LANGUAGE TupleSections #-}
module TicTacToe where
import Types
import qualified Data.Map as Map
other :: Piece -> Piece
other X = O
other O = X
legal :: [Int]
legal = [1, 2, 3]
emptyBoard :: Board
emptyBoard = Map.empty
winningPositions :: [[Position]]
winningPositions = [map (1,) legal, -- first three are vertical
map (2,) legal,
map (3,) legal,
map (,1) legal, -- next three are horizontal
map (,2) legal,
map (,3) legal,
map (\x -> (x, x)) legal, -- last two are diagonal
[(x, y) | x <- legal, y <- legal, x + y == 4]]
win :: Board -> Piece -> Bool
win board piece = any (threeInARow board piece) winningPositions
threeInARow :: Board -> Piece -> [Position] -> Bool
threeInARow board piece lane = all (== Just piece) [Map.lookup spot board
| spot <- lane]
draw :: Board -> Bool
draw board = Map.size board == 9 && not (win board X) && not (win board O)
gameOver :: Board -> (Bool, Maybe Piece)
gameOver board
| win board X = (True, Just X)
| win board O = (True, Just O)
| draw board = (True, Nothing)
| otherwise = (False, Nothing)
makeMove :: Board -> Piece -> Maybe Position -> Either YourError Board
makeMove _ _ Nothing = Left BadInput
makeMove board piece (Just (x, y)) =
if x `notElem` legal || y `notElem` legal
then Left OutOfBounds
else case Map.lookup (x, y) board of
Just _ -> Left NonEmptySquare
Nothing -> Right $ Map.insert (x, y) piece board