Tic-Tac-Toe

Using records to make a most of a game of 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)
  1. 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’
  2. Create a variable ex3 to represent player 2 being next to move on this board:

     X O X
       X
     O
    
  3. 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 middle O at the front of that player’s list of moves.

  4. Write the function getPiece :: Tttg -> (Int, Int) -> Char, which returns 'X', 'O', or ' ' depending what piece occupies the space.

  5. 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 ")
    
  6. 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))
    
  7. 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 ]