PYTHON Tic Tac Toe PART 2: The Opponent

Link to GitHub


For anyone that has not read ‘PYTHON Tic Tac Toe PART 1: The Game’, I created a primitive Tic Tac Toe game using python and the pygame library. However, in this part of the project, I will take things a step further and create four sepearate playable modes. The first mode is Local: 2 Player which is already implemented but had to be slightly restructured in the class. The other three modes will be playable versus the computer and are called CPU: Random, CPU: Difficult, and CPU: Mega Difficult.

Updates to Code

The first thing I did was recode the main file to have a Main Menu that displayed the four selections for the player to choose from.

Next, I created a helper function module to organize helper functions I need, specifically one for rendering text to simplify my code. Functions are meant to do one thing only and do that one thing well. Functions are vital for modularizing and maintaining quality code.

Then I broke up some game logic in the TicTacToe class to better support the ability to play the game under a select mode. Specifically, I created a method for each mode that will handle events for their respective game mode. I also added the class self.mode variable and passed it to the class constructor to maintain a reference for the current game mode.


Each game mode is fully functional except CPU: Mega Difficult which I will need to correct.

  • Local: 2 Player is fully functional, just as before
  • CPU: Random works great but is extremely easy as your CPU opponent has no strategy aside from complete randomness.
  • CPU: Difficult implements a minimax algorithm to maximize on the CPU’s chances and is significantly more difficult to play against compared to CPU: Random. However, it does not perform optimally in many cases.
  • CPU: Mega Difficult has the same minimax algorithm. I tried hard to optimize it for all game states but have not made any progress in the right direction so I decided I will revisit it another day when I can get a second opinion.

I am extremely pleased with how the first three modes turned out and I hope I can optimize CPU: Mega Difficult in the near future.

TicTacToe Main Menu
TicTacToe Screen

Next up???

Stay tuned for the final iteration I have planned for my project!

  • Part 3: Creating a tic tac toe visualizer