Photo by Micheile Henderson on Unsplash

Creating an unbeatable AI in a game of Tic-Tac-Toe

Richard Agyemang
3 min readJul 2, 2021

--

How could I possibly do this project?😢 This silent voice always lurks behind my mind every time I complete a project. Creating a tic-tac-toe game is a real challenge in itself when you’re a new programmer. The logic that goes into creating a game like this can throw you off your guard. It can be extremely frustrating when you have to process all the little pieces of logic that make this game work. The difficulty of creating this game even quadruples when you’re thinking of making this game using factory functions and the module pattern. At least this statement is true for me.

I am writing this short overview about creating this game because it looks like it took me ages to accomplish that. It will be my pleasure that other newbie programmers can take a lesson from my experience in creating this awesome game.

First I had to create the logic to play this game and also creating an unbeatable AI using the minimax algorithm. The bottleneck for me concerning this project was using factory functions in creating this game and model pattern. This way of creating a project was not familiar to me then.

This project pushed me hard to dig deeper into factory functions and the module pattern. I had to revise that section on the Odin project dozens of times. The sticking point for me was not just understanding how factory functions work but also how to use them in a real working program. I struggled a bit with this for a very long time before I could wrap my mind around it. I suggest to anyone who tries this project to take the time to really grasp the concept of factory functions and the module pattern as it is extremely valuable in creating complex programs.

I had to spend countless hours on the minimax algorithm that will enable the second player to play intelligently. This part of the program also forced me to brush up on my knowledge of recursive functions. Also, this particular portion taught me to take a break because there are moments in learning where your diffuse mode works better than your focus mode. In fact, you need these two modes when learning anything. What I have seen to work really well for me is when I encounter a difficult problem I take a break from it for a while then come back to it again and again till I get it.

I cannot say this enough but it pays to write down the whole game plan of your program before writing any line of code. I have been writing about this for some time now but I mostly find myself jumping into code straight away. Trust me this is a bad idea.

This is a link to my game https://github.com/owuracoder/tic-tac-toe.git. The code is kind of messy though

--

--