We earn commission when you buy through affiliate links.

This does not influence our reviews or recommendations.Learn more.

Let us create a simple Tic Tac Toe game in Python.

Tic Tac Toe Board

It will help you to build up game logic and understand how to structure code.

Gaming is one of the entertainment that humans have.

We can find different types of games on the web, mobile, desktop, etc.

Tic Tac Toe Win Gameplay

We are not here to make one of those heavy games now.

We are going to create a CLI tic-tac-toe game usingPython.

If you are not familiar with Tic Tac Toe, play it visuallyhereto understand.

Tic Tac Toe Winning Arrangements

Dont worry, even if you dont understand it, we are going to see it.

Tic Tac Toe

The tutorial is divided into three different sections.

In the first section, you will get to know how to play the tic-tac-toe game.

After that, we will see an algorithm that helps us to come up with the game logic.

Finally, we will see the structured code and its explanation.

You may skip the first section if you already know how to play Tic Tac Toe.

So, without further ado, lets dive into our first section.

Playing Tic Tac Toe

There will be two players in a game.

Two signs represent each player.

The general signs used in the game areXandO.

Finally, there will be a board with9boxes.

See the tic-tac-toe board visually.

The gameplay will be as follows.

Lets see some gameplays visually.

The playerXwins the game in the above gameplay.

All boxes diagonally fill withXsigns.

So, the respective player wins the game.

There are a total of8ways to arrange the same sign and win the game.

Lets see all the 8 arrangements that can win the game.

And finally, a draw fills the board without any winning arrangement.

I hope you understand how to Tic Tac Toe now.

Now, its playtime for you.

You may gohereand play it to understand the gameplay completely.

Leave it if you have already got it.

Now, its time to move the algorithm section.

Algorithm

We will now discuss the algorithm to write the code.

This algorithm will help you to write code in anyprogramming languageof your choice.

Lets see how its done.

You may be able to visualize whats happening.

Dont worry, even if you didnt understand it completely.

You will get more clarity once you see the code.

So, lets jump into the code section.

I assume you have Python installed on your PC to try the code.

Code

Go through the below code.

Check out the sample output of the code.

Some major points that help you understand the structure of the code.

Feel free to adapt the structure and improve it based on your project.

Structuring the code is not limited.

Final Words

Happy Coding!

Next, explore how to create number guessing game and Unit Testing with Python unittest Module.