Building a Tic Tac Toe Game Using Python

Narottam Kumar
3 min readApr 20, 2021

Most of you know that Bill Gate’s first computer program was a Tic-Tac-Toe game. And he wrote it at age of 13 when many of us don’t know what programming is.

I am here sharing a very simple and easy-to-understand code for building the game. If you know Python basics you can easily impliment them. First, let’s understand more about the game.

It’s a two-player game and players can select cross(X) or circle(O) as their symbol. This game consists of 3*3 boxes, so there are 9 positions available on the board. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.

First design a function that will represent the 3*3 Box. Here we will store the position value of the 3*3 box in a list p. Eg. p = [0,1,2,3,4,5,6,7,8] which will look like below.

def pbox(p):
print(f' %s | %s | %s \n-------|-------|-------\n %s | %s | %s \n-------|-------|-------\n %s | %s | %s ' %(p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]))

The Second function we need is the user input. The user can select any of the boxes (0–8). If the box was not already filled then this function will place the player mark on the provided box number. If it is already filled then the function will ask the user for different input.

def player(pl,s,p):
print('%s : Please select your position between 0-8:'%pl )
i = input()
while (i not in ['0','1','2','3','4','5','6','7','8']):
print('%s : Sorry!! Please select your position between 0-8:'%pl )
i = input()
i = int(i)
while (p[i] == 'X' or p[i] == 'O'):
print('Sorry!! Please select other Box this is already Filled')
i = input()
i = int(i)
p[i] = s
pbox(p)

So the above function will take three inputs. And based on the

  1. pl — Player Name
  2. s — Player mark(O/X)
  3. p — List containing position

Now we will check if the list is filled with player marks. If no place is empty then it will return False. So, that the game will end.

def check(li):
for x in range(9):
if x in li:
return True
return False

Our next function is to check if the player wins the game. We kept all the conditions in the ‘if’ statement.

def win(p,s):
if (p[0] == p[1] == p[2] == s or p[3] == p[4] == p[5] == s or p[6] == p[7] == p[8] == s or p[0] == p[3] == p[6] == s or p[1] == p[4] == p[7] == s or p[2] == p[5] == p[8] == s or p[0] == p[4] == p[8] == s or p[2] == p[4] == p[6] == s):
return True
return False

Lastly our main function.

def main():
p = [0,1,2,3,4,5,6,7,8]
print('Enter Player 1 Name')
p1 = input()
print('Enter Player 2 Name')
p2 = input()
pbox(p)
while check(p):
if(check(p)):
player(p1,'X',p)
if(win(p,'X')):
print('%s won the game'%p1)
break
if check(p):
player(p2,'O',p)
if(win(p,'O')):
print('%s won the game'%p2)
break

Now now the game is ready once you will run main(), it will ask for the player's name.

Thanks for reading. Hope you enjoy this.

--

--