-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIO.hs
82 lines (68 loc) · 2.37 KB
/
IO.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module IO where
-- Not sure why, but the bestMove function couldn't be used without importing
-- all of these manually. If we can figure out how to import everything that might
-- be a little nicer. -SV
import Game
( showColor,
testBoard,
Board,
Color(Yellow, Red),
Game,
bestMove,
validMovesBoard )
import GHC.IO
import Data.List (intersperse, transpose)
-- IO Functions (Section 2) -----------------
--
-- -- Output formnat: (First color is the player whose turn it is, then it's just the board with \n to separate rows)
-- -- RRRRRYRR
-- -- RYRYRYR
-- -- RYRYRYR
-- -- RYRYRYR
--
outputBoard :: Board -> IO ()
outputBoard board = putStrLn $ printBoard board
writeGame :: Game -> FilePath -> IO ()
writeGame game path = writeFile path (showGame game)
loadGame :: FilePath -> IO Game
loadGame path = do
contents <- readFile path
return (readGame contents)
-- IO action to output a best move.
putBestMove :: Game -> IO ()
putBestMove game = do
let move = bestMove game
putStrLn ("Best move: column #" ++ show move)
-- Reads a game from a string using the output format we defined on line 30.
readGame :: String -> Game
readGame (player:board) =
let
readColor 'R' = Red
readColor 'Y' = Yellow
readColor _ = error "Invalid color"
in
(map (map readColor) (lines board), readColor player)
-- Outputs a game using the output format from line 30.
showGame :: Game -> String
showGame game =
let
board = fst game
player = snd game
showRow row = [showColor color | color <- row]
in
-- append the player, then each row of the board
showColor player : unlines (map showRow board)
-- Converts the board to a nice string.
-- If you want to print a pretty version to IO, use the IO wrapper instead.
printGame :: Game -> String
printGame (board, color) = printBoard board
-- Converts a board to a nice string.
printBoard :: Board -> String
printBoard board = unlines $ map (intersperse '|') $ reverse $ transpose $ padBoard board
where
padCol col = colToString col ++ replicate (6 - length col) ' '
padBoard = map padCol
-- Prints a given column of colors in reverse. This is just so that we can rotate the board 90 degrees and everything still lines up.
colToString :: [Color] -> [Char]
colToString [] = ""
colToString lst = foldr (\x y -> showColor x : y) "" $ reverse lst