Day 106: TicTacToe for Virtual Study Group
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
(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.