How to Create an Interactive Tic Tac Toe Game with Python
Learn how to create an interactive Tic-Tac-Toe game using Python
6 min read
In this 5th post of our blog <Code/Week> with Yashraj we are going to make a game that we are playing since our childhood. From scribing it on the back side of our notebook in boring history classes to playing it using Python is much more fun.
While learning Python I came across the idea of developing this game and the most fascinating thing about it is that it does not include any OOP concept or any advanced Python module. So, everything you require to build this game is a basic understanding of Python functions, variables, operators, lists, loops etc. Also, you can play it on any computer with an internet connection. Just go to your browser and search for the python compiler and just go there, copy and paste all of this code in the same sequence and you are good to go.
Having the right kind of planning before executing any project is very essential as it helps us to make the project with ease and less confusion. So, we are going to break this project into small functions and then finally we will join them in the final block of code.
Designing the board...
Let's make the board as simple as possible. We will use the Numpad of a keyboard as our reference. So each number on the Numpad represents the position of your marker(X or O).
The above image is for your reference where the numbers shown on the right-hand side are the corresponding lines of code in the below code snippet.
Here, the indices
board[ ] is the placeholder and [space] is the empty space to make your board look nice.
First, we need to import
clear_output method from
IPython.display module. This will help us to clear previous output and give us a neat and clean experience after every turn.
Second, we need to define a function to display the board on which we are going to play and don't forget to call the
from IPython.display import clear_output def display_board(board): clear_output() print(' | | ') #1 print(board + ' | ' + board + ' | ' + board) #2 print('--|----|--') #3 print(' | | ') #4 print(board + ' | ' + board + ' | ' + board) #5 print(' | | ') #6 print('--|----|--') #7 print(board + ' | ' + board + ' | ' + board) #8 print(' | | ') #9
Now, we have made the function of displaying board.
Accepting user input
Player input: assign their marker as 'X' or 'O'
This will ask the user for their choice of the marker.
def user_input(): marker = ' ' while marker not in ['X', 'O']: marker = input('Player 1, select X or O: ').upper() if marker == 'X': return ('X', 'O') else: return ('O', 'X')
This assigns a marker at the specific position given by the user on the game board.
def place_marker(board, marker, position): board[position] = marker
Check if someone wins!
win_check(board, mark) function is used to check the possible situation when a player can win. So, there are in total 8 possible situations when a player can win.
def win_check(board, mark): return((board == mark and board == mark and board == mark) or # top line (board == mark and board == mark and board == mark) or # middle line (board == mark and board == mark and board == mark) or # bottom line (board == mark and board == mark and board == mark) or # 1st vertical (board == mark and board == mark and board == mark) or # 2nd vertical (board == mark and board == mark and board == mark) or # 3rd vertical (board == mark and board == mark and board == mark) or # diagonal (board == mark and board == mark and board == mark)) # diagonal
Who's going first?
When we used to play this game on paper, we used to randomly decide who will go first. Likewise, in Python, there is a module
random which has a method
randint through which the computer can randomly decide which player will play first.
from random import randint def chose_first(): if randint(0,1) == 0: return 'Player 2' else: return('Player 1')
Is there any vacancy?
While playing we can manually detect that we should not place our marker at any position where there is no vacancy. But the computer does not know that he needs a vacancy to place a marker. So, we need to tell it that where there is no vacancy, there should be no re-assignation of the marker.
This we can do by taking in two arguments -
position. Remember that we have
board[ ] indices in our board. This will help us to set the position.
def space_check(board, position): if board[position] == ' ': return True else: return False
This checks if the board is full
This function will be used at that point in the game when both players have come to a point when nobody is going to win as there is no space left to place the marker.
def full_board_check(board): while ' ' in board: return False
This asks next position from the player and checks whether that position is vacant or not.
def player_choice(board): position = 0 while position not in [1,2,3,4,5,6,7,8,9] and space_check(board, position): position = int(input('Please select your next position(1-9): ')) return position
Do you want to play again?
This is a very useful function in the game. With the help of this function, we won't need to rerun the entire program to play the game again. This will run the program in the loop, till the time you want.
def replay(): permission = ' ' while permission not in ['Y', 'N']: permission = input("Do you want to keep playing 'Y' or 'N': ").upper() if permission == 'Y': return True elif permission == 'N': return False
BRINGING EVERYTHING TOGETHER!
Now that we have our blocks ready, let's build our castle by joining these blocks and remembering to place them in perfect places.
print('Welcome to Tic-Tac-Toe !') # While loop to keep running the game while True: #play game ## Set everything up(board, whos first, chose marker - x/o) the_board = [' ']*10 player1_marker, player2_marker = user_input() print('\n') turn = chose_first() print(turn + ' will go first') play_game = input('Ready to play? Yes or No') if play_game.lower() == 'y': game_on = True else: game_on = False ## game play while game_on: # player1 turn if turn == 'Player 1': #show board display_board(the_board) #choose position position = player_choice(the_board) #place the marker on position place_marker(the_board, player1_marker, position) #check if they won if win_check(the_board, player1_marker): display_board(the_board) print('Player 1 has won!!!') game_on = False #check if there is a tie else: if full_board_check(the_board): display_board(the_board) print('TIE GAME!!!') game_on = False else: #No tie or no win, next player turn turn = 'Player 2' #player 2 turn else: #show board display_board(the_board) #choose position position = player_choice(the_board) #place the marker on position place_marker(the_board, player2_marker, position) #check if they won if win_check(the_board, player2_marker): display_board(the_board) print('Player 2 has won!!!') game_on = False #check if there is a tie else: if full_board_check(the_board): display_board(the_board) print('TIE GAME!!!') game_on = False else: #No tie or no win, next player turn turn = 'Player 1' if not replay(): break # Break out of while loop on replay()
Congratulations!, on making a game by using python. In this game, I've not used Graphical User Interface(GUI) to make it easy for you. If you think that I should use GUI let me know in the comments and next week we will be experiencing a good GUI.
I appreciate your comments, likes and shares. So, please do as much as possible as it helps me to be motivated and keep writing such blog articles for you guys.
Thank you. See you next week!
Did you find this article valuable?
Support Yashraj Singh Negi by becoming a sponsor. Any amount is appreciated!