In this tutorial we will learn how to develop a basic Tic-Tac-Toe game in Python. Tic Tac Toe game has 9 available spaces in which two players, one with cross and other with circle, can place their marks at any place with the target to have 3 marks(cross or circle), in a straight line, vertically, horizontally or diagonally.
In this tutorial, we will use if else statements in Python, to define the conditions for matching the input with the position. We will number each position to store user input, numbering the positions as 1, 2, 3, ... as shown below.
_1_/_2_/_3_
_4_/_5_/_6_
7 / 8 / 9
We also have the two player mode for this game, where as player vs. computer mode too.
Along with this, user will be informed about the rules of the game, by running a basic input command. Similarly, user can see help by entering -h or help, along with other information.
To start the game, user can type new game or start game and press enter.
We have used the time module of python, to make the code execution pause/sleep at times to make the user choose for any option.
Following are the functions we have used and implemented in our python code for creating the tic tac toe game:
def win_check():
# to check who won the game
def rule():
# to define rules for the game
def check_game_o():
# to check the positions of O
def check_game_x():
# to check the positions of X
def computer_turn():
# in single player game, to run computer turn
def write_log():
# write logs in log.txt file
def read_log():
# read logs in log.txt file
Now let's see the running code.
Along with the python code, we also have log.txt file to store logs of the game where we will be storing the player names, along with the information about who win the game.
Conclusion
The Python Tic Tac Toe game is created using the basic features of Python and you should not find anything confusing. We have used basic if-else conditions along with function calls based on user input for showing help messages. If you have any doubt, feel free to share in the comment section below.
This code was submitted by one of our Instagram follower 1908vishalbalhara who is a Python enthusiast and wanted to share this code with our readers.
You may also like: