module TicTacToe where
import Control.Monad
import Control.Monad.Operational
import Control.Monad.State
import Data.Either
import Data.List
import System.Random
data PlayerI a where
ReadBoard :: PlayerI Board
PlayMove :: Int -> PlayerI Bool
type Player m a = ProgramT PlayerI m a
readBoard = singleton ReadBoard
playMove = singleton . PlayMove
runGame :: Player IO () -> Player IO () -> IO ()
runGame player1 player2 = eval' initialGameState player1 player2
where
eval' game p1 p2 = viewT p1 >>= \p1view -> eval game p1view p2
eval :: GameState
-> ProgramViewT PlayerI IO () -> Player IO ()
-> IO ()
eval game (Return _) _ = return ()
eval game (ReadBoard :>>= p1) p2 = eval' game (p1 (board game)) p2
eval game (PlayMove mv :>>= p1) p2 =
case makeMove mv game of
Nothing -> eval' game (p1 False) p2
Just game'
| won game' -> let p = activePlayer game in
putStrLn $ "Player " ++ show p ++ " has won!"
| draw game'-> putStrLn $ "It's a draw."
| otherwise -> eval' game' p2 (p1 True)
main = do
g <- getStdGen
runGame playerHuman (playerAI g)
data Symbol = X | O deriving (Eq,Show)
type Square = Either Int Symbol
type Board = [[Square]]
data GameState = Game { board :: Board, activePlayer :: Symbol }
initialGameState :: GameState
initialGameState = Game (map (map Left) [[1,2,3],[4,5,6],[7,8,9]]) X
possibleMoves :: Board -> [Int]
possibleMoves board = [k | Left k <- concat board]
makeMove :: Int -> GameState -> Maybe GameState
makeMove k (Game board player)
| not (k `elem` possibleMoves board) = Nothing
| otherwise = Just $ Game (map (map replace) board) (switch player)
where
replace (Left k') | k' == k = Right player
replace x = x
switch X = O
switch O = X
won :: GameState -> Bool
won (Game board _) = any full $ diagonals board ++ rows board ++ cols board
where
full [a,b,c] = a == b && b == c
diagonals [[a1,_,b1],
[_ ,c,_ ],
[b2,_,a2]] = [[a1,c,a2],[b1,c,b2]]
rows = id
cols = transpose
draw :: GameState -> Bool
draw (Game board _) = null (possibleMoves board)
showSquare = either (\n -> " " ++ show n ++ " ") (concat . replicate 3 . show)
showBoard :: Board -> String
showBoard board =
unlines . surround "+---+---+---+"
. map (concat . surround "|". map showSquare)
$ board
where
surround x xs = [x] ++ intersperse x xs ++ [x]
printBoard = putStr . showBoard
playerHuman :: Player IO ()
playerHuman = forever $ readBoard >>= liftIO . printBoard >> doMove
where
doMove :: Player IO ()
doMove = do
liftIO . putStrLn $ "At which number would you like to play?"
n <- liftIO getLine
b <- playMove (read n)
unless b $ do
liftIO . putStrLn $ "Position " ++ show n ++ " is already full."
doMove
playerAI :: Monad m => StdGen -> Player m ()
playerAI = evalStateT ai
where
ai :: Monad m => StateT StdGen (ProgramT PlayerI m) ()
ai = forever $ do
board <- lift $ readBoard
n <- uniform (possibleMoves board)
lift $ playMove n
where
uniform :: Monad m => [a] -> StateT StdGen m a
uniform xs = do
gen <- get
let (n,gen') = randomR (1,length xs) gen
put gen'
return (xs !! (n1))