Skip to content

Instantly share code, notes, and snippets.

@Newky
Created December 22, 2011 23:10
Show Gist options
  • Save Newky/1512255 to your computer and use it in GitHub Desktop.
Save Newky/1512255 to your computer and use it in GitHub Desktop.
Sample Paper Haskell Q4.
import Data.List
data Piece = X | O deriving (Ord, Eq, Show)
data Board = Board [(Int, Int, Piece)] deriving(Ord, Eq,Show)
winning_combinations = [[(a,0), (a,1), (a,2)] | a <- [0..2] ] ++ [[(0,a), (1,a), (2,a)] | a <- [0..2] ] ++ [[(0,0), (1,1), (2,2)], [(0,2), (1,1), (2,0)]]
over2 :: Board -> Bool
over2 (Board []) = False
over2 (Board x) = is_winner newx winning_combinations
where newx = sortBy compare x
is_winner x [] = False
is_winner x (w:wc)
| (length newx == 3) = all_X || all_Y || is_winner x wc
| otherwise = is_winner x wc
where newx = filter (\(x,y, _) -> (x, y) `elem` w ) x
all_X = foldr (&&) True $ map (\(_, _, p) -> p == X) newx
all_Y = foldr (&&) True $ map (\(_, _, p) -> p == O) newx
play :: Board -> Board
play (Board []) = (Board [(0, 0, X)])
play (Board x) = (Board (new_piece:x))
where next_piece = get_next x
coords = [ (x, y) | (x, y, _) <- x]
all = [(x, y) | x <- [0 .. 2], y <- [0..2]]
next_coord = filter (\x -> not (elem x coords)) all
new_piece = (\(x, y) p -> (x, y, p)) (next_coord !! 0) next_piece
get_next :: [(Int, Int, Piece)] -> Piece
get_next x = get_next' x 0 0
get_next' :: [(Int, Int, Piece)] -> Int -> Int -> Piece
get_next' [] x o
| x > o = O
| otherwise = X
get_next' ((_, _, X):xs) x o = get_next' xs (x+1) o
get_next' ((_, _, O):xs) x o = get_next' xs (x+1) o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment