Merl's Blog

End Game

End game, this usually refers to chess or a lesser Avengers movie. They undid what made Infinity War interesting. You can’t bring everyone back that you killed off. That defeats the purpose!

Sorry for spoilers and going off topic.

In my Tic Tac Toe game I wanted any player to have the opportunity to play again after they completed a game without having to run the program again. So if they were having the time of their lives playing Tic Tac Toe over and over again, they could do so without having to start the program over again.

I was under the impression that it would be challenging because there was a game loop that was in the way.

(defn game-loop [game-id db-type]
 (let [[game id] (continue-game? game-id)]
   (ui/print-id-and-board id game)
   (loop [game game]
     (let [game (gm/play-round db-type game)
           new-board (game/convert-moves-to-board game)]
       (if (board/game-over? new-board game)
         (ui/print-end game)
         (recur game))))))

I was nervous because there is this loop that has quite a lot going on. Especially that continue-game? function. There is much going on under the hood.

This is one of those moments where I am so happy I was wrong. Given it did take me some time, and I laugh now because everything seems so simple now. But I do have the ability to continue this loop no problem. And everything runs quite smoothly.

(defn end-game [game db-type]
 (let [game-id (data/get-next-game-id)]
   (ui/print-end game)
   (if (ui/play-again-message)
     (game-loop game-id db-type))))


(defn game-loop [game-id db-type]
 (let [[game id] (continue-game? game-id)]
   (ui/print-id-and-board id game)
   (loop [game game]
     (let [game (gm/play-round db-type game)
           new-board (game/convert-moves-to-board game)]
       (if (board/game-over? new-board game)
         (end-game game db-type)
         (recur game))))))


In reality I did have to change a few details inside of continue-game? but they were minor and just helped make this process easier.

I suppose that is the great concept of OCP. if my code is written well I can just add new functionality without making major changes to my previous code.

Best,

Merl