/
Noninteractive.hs
47 lines (31 loc) · 1.06 KB
/
Noninteractive.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
module XO.CLI.Orchestrator.Noninteractive (run) where
import Data.Maybe (maybe)
import XO.AI (getPositions)
import XO.Game (Game, Outcome(Win, Squash), new, outcome, play, renew, turn)
import XO.Mark (Mark)
import XO.CLI.Random (randomElem)
run :: Mark -> Int -> IO ()
run = runLoop . new
runLoop :: Game -> Int -> IO ()
runLoop game rounds
| rounds == 0 = return ()
| otherwise = do
finalGame <- playOneGame game
if rounds == 1 then
putStrLn ""
else
runLoop (renew finalGame) (rounds-1)
playOneGame :: Game -> IO Game
playOneGame game = do
nextGame <- playOneTurn game
maybe (playOneGame nextGame) (handleGameOver nextGame) (outcome nextGame)
playOneTurn :: Game -> IO Game
playOneTurn game = do
position <- randomElem $ getPositions game
let Right nextGame = play position game
return nextGame
handleGameOver :: Game -> Outcome -> IO Game
handleGameOver game outcome = putStr (showOutcome outcome game) >> return game
showOutcome :: Outcome -> Game -> String
showOutcome Win = show . turn
showOutcome Squash = const "."