Skip to content

Day 106: TicTacToe for Virtual Study Group

Thoughts for today

Walking through a video taking a functional approach to the Tic-Tac-Toe game for the Clojure study group.

Code from todayλ︎

Functional Tic-Tac-Toeλ︎

Make changes to the design of the board and players to make the code easier to read than the original code in the video by Brian Wills.

Refactor the play-game function to take starting-board and player-sequence as arguments rather than pulling in shared values (def). Passing arguments also means that play-game can be called with different board states, useful for testing especially if a computer opponent was added as an option to the game play.

Refactor: play-game function

src/tictactoe_cli/core.clj
(defn play-game
  "The game loop.
  We iterate through the player sequence (alternate player turns)
  until there is a winner or the board is full."
  [starting-board player-sequence]
  (loop [board starting-board
         player-sequence player-sequence]
    (let [winner (winner? board)]
      (println "Current board:")
      (display-board board)
      (cond
        winner              (println "Player " (player-name winner) " wins!")
        (full-board? board) (println "The game is a draw.")
        :else
        (recur
         (take-turn (first player-sequence) board)
         (rest player-sequence))))))

(comment
  (play-game starting-board player-sequence))

It could be interesting to make an AI for both players and watch the output as a game progresses. A dynamic web page view of the game simulation could producing a simulation like that seen at the end of the War Games movie.


Thank you.

🌐 Practical.li Website

Practical.li GitHub Org practicalli-johnny profile

@practicalli@clj.social @practical_li