Tic-Tac-Toe
We are going to write most of a tic-tac-toe game in Haskell. For uniformity, let us all use these board coordinates:
(0,0) | (1,0) | (2,0)
(0,1) | (1,1) | (2,1)
(0,2) | (1,2) | (2,2)
-
Make a record to hold information for a tic-tac-toe game. Call your record
Tttg
. It must have three fields:- Whose turn is it? (
nextPlayer
) - Where did player 1 play? (
p1moves
) … these are ‘X’ - Where did player 2 play? (
p2moves
) … these are ‘O’
- Whose turn is it? (
-
Create a variable
ex3
to represent player 2 being next to move on this board:X O X X O
-
Create a variable
ex4
to represent player 1 being next to move on this board:X O X X O O
Do this by modifying the lists from
ex3
, adding the bottom middleO
at the front of that player’s list of moves. -
Write the function
getPiece :: Tttg -> (Int, Int) -> Char
, which returns'X'
,'O'
, or' '
depending what piece occupies the space. -
Write a function to create a string representation of the game, including newlines (
"\n"
) for line breaks.printGame :: Tttg -> String printGame _ = "" check_printGame = (printGame ex4 == "XOX\n X \nOO ")
-
Write a function to update the board with the player’s move. Assume that the move is legal. The newly placed piece should go at the front of the list of that player’s occupied squares.
makeMove :: Tttg -> (Int,Int) -> Tttg makeMove game _ = game check_move = (ex4 == makeMove ex3 (1,2))
-
Write the
winner :: Tttg -> Maybe Int
function to determine the winner of the game. You should make your own example of a game that is won and add it to your checks.check_winner = [ winner ex4 == Nothing ]