Python Tic Tac Toe Game

Spread the love

In this tutorial we are going to see how we can implement the tic tac toe game in Python. We can either make use of random numbers for the computer move or we can develop a simple algorithm which will play the role of a computer. 
Let us first see the representation of our board. For the purpose of this tutorial every place in the board is given a number. The board will look like this.

So when we say the 9th position is being assigned an X it means the last box of the board will be assigned an X.
Using Random Numbers:
Here we can keep a list of blank spaces on the board. Everytime when it’s computer’s turn we will generate a random number between [0,size_of_list-1] and computer will play that the move on the number present on that index. Here is the code-snippet for the computer move using a random number generator.def computer_move():
empty_place = []
# If I can win, others don’t matter.
for i in range(1,10):
if board[i-1] == i-1 :
if len(empty_place) > 0 :
idx = random.randint(0,len(empty_place)-1)
move = empty_place[idx]
return make_move(board,computer,move)

return (False,False)Here empty_place will store all the positions on the board which are empty and then we will take a random positions from the list and make sure that the computer’s move.
Developing Computer Algorithm: 
The algorithm will consist of five steps:
First we will see if there is a move that computer can make which will win the game. If there is so, take that move. Otherwise, go to step 2.
See if there is a move that player can make which will cause computer to lose game. If there is so, move there to block the player. Otherwise, go to step 3.
Check if any of the corner spaces (spaces 1, 3, 7, or 9) are free. If so, move there. If no corner piece is free, then go to step 4.
Check if the center is free or not. If so, move there. If it isn’t, then go to step 5.
Move on any of the side pieces (spaces 2, 4, 6, or 8). Now there are no more steps, because if execution reaches step 5 the side spaces are the only spaces left.
Our simple algorithm is now ready. Let us first complete other requirements and then we will see the code for this algorithm.
We will need to display the board after every turn.
For the board we will take a list of size 9 which will contain the position at the start and later they will be changed to X and O.
At the start of the game, we first need to decide player will get X or O and whose turn will be first. This can be either done automatically using random number or we can take input from user. For this tutorial we are doing it using random numbers.
We will then create a new board (i.e A list having values from 1 to 9). 
To check if move is valid: 
Everytime we are making a move we should keep in mind that the position should not be already occupied (If a position contain the X or O then its occupied otherwise it will contain position number).
To check if player has won: 
To check if a player won we have to check 2 diagonal entries, 3 rows and 3 columns. We will make a list of all the winning combinations and go through each after every turn of player or computer to check if they won.
The winning combinations are as below: 
Row-wise: (0,1,2), (3,4,5), (6,7,8)
Column-wise: (0,3,6), (1,4,7), (2,5,8)
Diagonal-wise: (0,4,8), (2,4,6)
To check next move of computer: 
If in a turn computer cannot win and we aren’t blocking the players pieces then we have to decide what move computer will play (i.e. If we are at step 3 of algorithm). Now according to the preference of our algorithm we should first check corner places, then center and then the rest. So we will create a list which will store these steps in the correct order and we will go through this list and make our move.
Corner: (1,3,7,9)
Center: (5)
Others: (2,4,6,8).
Now let us see how the code looks : 
Python Tic Tac Toe Game Code
import random
import sys

board=[i for i in range(0,9)]
player, computer = ”,”


# Table

# Function to print the board
def print_board():
counter = 0
for i in range(0,9):
if board[i] == ‘X’ or board[i] == ‘O’ :
print(board[i],end = ‘ ‘)
else :
print(” “,end = ‘ ‘)
if counter%3 ==0 :
print(“”,end = ‘n———-n’)
else :
print(“| “,end=”)

# This function will decide player will play with X or O
def select_char():
if random.randint(0,1) == 0:
return (‘X’,’O’)
return (‘O’,’X’)

# Function to decide a valid move.
def can_move(brd, player, move):
if move in tab and brd[move-1] == move-1:
return True
return False

# Function to check if win condition is satisfied.
def can_win(brd, player, move):
for i in brd:
if i == player: places.append(x);
for tup in winners:
for ix in tup:
if brd[ix] != player:
if win == True:
return win

def make_move(brd, player, move, undo=False):
if can_move(brd, player, move):
brd[move-1] = player
win=can_win(brd, player, move)
if undo:
brd[move-1] = move-1
return (True, win)
return (False, False)

def random_move():
empty_place = []
# If I can win, others don’t matter.
for i in range(1,10):
if board[i-1] == i-1 :
if len(empty_place) > 0 :
idx = random.randint(0,len(empty_place)-1)
move = empty_place[idx]
return make_move(board,computer,move)

return (False,False)

# AI goes here
def computer_move():
# If the computer can win in this turn, it will take the turn.
for i in range(1,10):
if make_move(board, computer, i, True)[1]:
if move == -1:
# If player can win next turn then we have to block that.
for i in range(1,10):
if make_move(board, player, i, True)[1]:
if move == -1:
# Otherwise, try to take one of the desired places.
for tup in moves:
for mv in tup:
if move == -1 and can_move(board, computer, mv):
return make_move(board, computer, move)

def is_full():
for i in range(0,9):
if board[i] == i:
return True
return False

player, computer = select_char()
print(‘Player is [%s] and computer is [%s]’ % (player, computer))

turn = random.randint(0,1)

if turn == 0 :
print(“Player will play first.”)
else :
print(“Computer will play first.”)

result=”It’s a tie !!”

while is_full():
print(‘Make your move [1-9] : ‘, end=”)
move = int(input())
moved, won = make_move(board, player, move)
if not moved:
print(‘ >> Invalid number ! Try again !’)

if won:
result=’ You won !!’
elif computer_move()[1]:
result=’ You lose !!’

Player is [X] and computer is [O]Computer will play first.| | ———-| | ———-| | ———-
O | | ———-| | ———-| | ———-Make your move [1-9] : 2O | X | ———-| | ———-O | | ———-Make your move [1-9] : 4O | X | O ———-X | | ———-O | | ———-Make your move [1-9] : 5O | X | O ———-X | X | O ———-O | | ———-Make your move [1-9] : 😯 | X | O ———-X | X | O ———-O | X | ———-You won !!
In the replace computer_move with random_move in the function calling then the computer will take random moves instead of using the algorithm as discussed before.
Commet down below if you have any queries related to python tic tac toe game implementation.
The post Python Tic Tac Toe Game appeared first on The Crazy Programmer.

X ITM Cloud News


Next Post

GitHub Finally has Launched its Mobile App

Sun Nov 24 , 2019
Spread the love          Microsoft acquisition “GitHub” has news from their cosmos to give more than 40 million developers and contributors a reason to celebrate. Undoubtedly, 2018 has been a favorite year for developers with the expansion of the open-source community (GitHub), adding up approx. 10 million new users from around 70 countries and […]

Cloud Computing – Consultancy – Development – Hosting – APIs – Legacy Systems

X-ITM Technology helps our customers across the entire enterprise technology stack with differentiated industry solutions. We modernize IT, optimize data architectures, and make everything secure, scalable and orchestrated across public, private and hybrid clouds.

This image has an empty alt attribute; its file name is x-itmdc.jpg

The enterprise technology stack includes ITO; Cloud and Security Services; Applications and Industry IP; Data, Analytics and Engineering Services; and Advisory.

Watch an animation of  X-ITM‘s Enterprise Technology Stack

We combine years of experience running mission-critical systems with the latest digital innovations to deliver better business outcomes and new levels of performance, competitiveness and experiences for our customers and their stakeholders.

X-ITM invests in three key drivers of growth: People, Customers and Operational Execution.

The company’s global scale, talent and innovation platforms serve 6,000 private and public-sector clients in 70 countries.

X-ITM’s extensive partner network helps drive collaboration and leverage technology independence. The company has established more than 200 industry-leading global Partner Network relationships, including 15 strategic partners: Amazon Web Services, AT&T, Dell Technologies, Google Cloud, HCL, HP, HPE, IBM, Micro Focus, Microsoft, Oracle, PwC, SAP, ServiceNow and VMware