 # How to make a simple tic tac toe game in Python

Yes, we can do fun stuffs with python; it’s not always about the black screen. Tic-Tac-Toe, or Noughts and Crosses (as the British call it), is one of the simplest fun games to play. You can either play it online against a computer or enjoy it with a friend.

Here we have shown how to create the game in python. What we have here are three code buckets. The first one is for automatic tit-tac-toe: the computer plays against itself and you just watch. The second code lets you play against the computer, and the last code runs for you to play with a friend.

If you understand the python syntax already then the codes would not present much difficulty to grasp, just the numpy and random libraries were used.

Related article
How to use math functions in Python

Check out our guide on how to use Python functions if you want to refresh your knowledge about Python functions.

So let us look at the three code classes.

#### Automatic Tic-Tac-Toe

I derive pleasure in watching my computer play against itself, it makes me feel like a robotics engineer.

```# Tic-Tac-Toe Program using
# random number in Python

# importing all necessary libraries
import numpy as np
import random
from time import sleep

# Creates an empty board
def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))

# Check for empty places on board
def possibilities(board):
l = []

for i in range(len(board)):
for j in range(len(board)):

if board[i][j] == 0:
l.append((i, j))
return(l)

# Select a random place for the player
def random_place(board, player):
selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)

# Checks whether the player has three
# of their marks in a horizontal row
def row_win(board, player):
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three
# of their marks in a vertical row
def col_win(board, player):
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[y][x] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
win = True

for x in range(len(board)):
if board[x, x] != player:
win = False
return(win)

# Evaluates whether there is
# a winner or a tie
def evaluate(board):
winner = 0

for player in [1, 2]:
if (row_win(board, player) or
col_win(board,player) or
diag_win(board,player)):

winner = player

if np.all(board != 0) and winner == 0:
winner = -1
return winner

# Main function to start the game
def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)

while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)

# Driver Code
print("Winner is: " + str(play_game()))
```

#### Playing Tic-Tac-Toe with your Computer

They say humans are smarter than computers? Let a game be the judge.

(This code was written by Benjamin Ononugbu)

```import time
import random as r
def makeboard(board):
print(board,'|',board,'|',board)
print('--+---+--')
print(board,'|',board,'|',board)
print('--+---+--')
print(board,'|',board,'|',board)

def winning_checker(board,tom,user):
row1 = [board,board,board]
row2 = [board,board,board]
row3 = [board,board,board]
col1 = [board,board,board]
col2 = [board,board,board]
col3 = [board,board,board]
dia1 = [board,board,board]
dia2 = [board,board,board]
for row in [row1,row2,row3,col1,col2,col3,dia1,dia2]:
if row == [user,user,user]:
return 'you win'
break
if row == [tom,tom,tom]:
return 'computer wins'
break

def AI_simulator(board,tom,user,u):
row1 = [board,board,board]
row2 = [board,board,board]
row3 = [board,board,board]
col1 = [board,board,board]
col2 = [board,board,board]
col3 = [board,board,board]
dia1 = [board,board,board]
dia2 = [board,board,board]
tabs = [row1,row2,row3,col1,col2,col3,dia1,dia2]
for row in tabs:
if row == [' ',tom,tom]:
x = tabs.index(row)
if x == 0:
board = tom
if x == 1:
board = tom
if x == 2:
board = tom
if x == 3:
board = tom
if x == 4:
board = tom
if x == 5:
board = tom
if x == 6:
board = tom
if x == 7:
board = tom
print('tom played:')
makeboard(board)
break
elif row == [tom,' ',tom]:
x = tabs.index(row)
if x == 0:
board = tom
if x == 1:
board = tom
if x == 2:
board = tom
if x == 3:
board = tom
if x == 4:
board = tom
if x == 5:
board = tom
if x == 6:
board = tom
if x == 7:
board = tom
print('tom played:')
makeboard(board)
break
elif row == [tom,tom,' ']:
x = tabs.index(row)
if x == 0:
board = tom
if x == 1:
board = tom
if x == 2:
board = tom
if x == 3:
board = tom
if x == 4:
board = tom
if x == 5:
board = tom
if x == 6:
board = tom
if x == 7:
board = tom
print('tom played:')
makeboard(board)
break
if (row != [' ',tom,tom] and row != [tom,' ',tom] and row != [tom,tom,' ']):
time.sleep(1)
AI_block(board,tom,user)

def AI_block(board,tom,user):
row1 = [board,board,board]
row2 = [board,board,board]
row3 = [board,board,board]
col1 = [board,board,board]
col2 = [board,board,board]
col3 = [board,board,board]
dia1 = [board,board,board]
dia2 = [board,board,board]
tabs = [row1,row2,row3,col1,col2,col3,dia1,dia2]
for row in tabs:
if row == [' ',user,user]:
x = tabs.index(row)
if x == 0:
board = tom
if x == 1:
board = tom
if x == 2:
board = tom
if x == 3:
board = tom
if x == 4:
board = tom
if x == 5:
board = tom
if x == 6:
board = tom
if x == 7:
board = tom
print('tom played:')
makeboard(board)
break
elif row == [user,' ',user]:
x = tabs.index(row)
if x == 0:
board = tom
if x == 1:
board = tom
if x == 2:
board = tom
if x == 3:
board = tom
if x == 4:
board = tom
if x == 5:
board = tom
if x == 6:
board = tom
if x == 7:
board = tom
print('tom played:')
makeboard(board)
break
elif row == [user,user,' ']:
x = tabs.index(row)
if x == 0:
board = tom
if x == 1:
board = tom
if x == 2:
board = tom
if x == 3:
board = tom
if x == 4:
board = tom
if x == 5:
board = tom
if x == 6:
board = tom
if x == 7:
board = tom
print('tom played:')
makeboard(board)
break
if (row != [' ',user,user] and row != [user,' ',user] and row != [user,user,' ']):
AI_decisionbox(board,tom,user)

def AI_decisionbox(board,tom,user):
count = 0
for posn in range(9):
if board[posn] == ' ':
board[posn] = user
row1 = [board,board,board]
row2 = [board,board,board]
row3 = [board,board,board]
col1 = [board,board,board]
col2 = [board,board,board]
col3 = [board,board,board]
dia1 = [board,board,board]
dia2 = [board,board,board]
tabs = [row1,row2,row3,col1,col2,col3,dia1,dia2]
for row in tabs:
if (row == [' ',user,user]) or (row == [user,' ',user]) or (row == [user,user,' ']):
count += 1
if count >= 2:
board[posn] = tom
print('tom played:')
makeboard(board)
break
else:
board[posn] = ' '
count = 0
if count < 2: while True: n = r.choice([0,2,6,8]) if board[n] == ' ': board[n] = tom print('tom played: ') makeboard(board) break else: nu = r.randint(0,8) if board[nu] == ' ': board[nu] = tom print('tom played: ') makeboard(board) break while True: entry = input('choose between O and X: ') user = entry.upper() while user not in ['X','O','x','o']: print('X and O are the recommended markers') entry = input() user = entry.upper() if (user == 'X') or (user == 'x'): tom = 'O' else: tom = 'X' board = [' ',' ',' ',' ',' ',' ',' ',' ',' '] k = 0 u = 0 t = 0 corners = [0,2,6,8] while True: if k == 0: makeboard(board) num = int(input('choose a number between 0 and 8: ')) while True: if num > 8:
print('number must be from 1 to 8')
num = int(input('enter number again'))
break
while True:
if board[num] != ' ':
print('this number has been chosen please choose another')
num =int(input())
else:
board[num] = user
print('you played:')
makeboard(board)
break
if u >= 2:
winning_checker(board,tom,user)
if winning_checker(board,tom,user) == 'you win':
time.sleep(1)
print('you win')
break
u += 1
if k == 4:
print('the game ends in a draw')
break
print('its tom turn')
time.sleep(1)
if t == 0:
while True:
if board == ' ':
board = tom
print('tom played:')
makeboard(board)
break
elif board != ' ':
p = r.choice(corners)
if board[p] == ' ':
board[p] = tom
print('tom played:')
makeboard(board)
break
#else:
#nu = r.randint(0,8)
#if board[nu] == ' ':
#board[nu] = tom
#print('tom played: ')
#makeboard(board)
#break
if t > 0:
if t == 1:
if (board == user and board == user) or (board == user and board == user):
while True:
q = r.choice([1,3,5,7])
if board[q] == ' ':
board[q] = tom
print('tom played:')
makeboard(board)
break
else:
AI_simulator(board,tom,user,u)
winning_checker(board,tom,user)
else:
AI_simulator(board,tom,user,u)
winning_checker(board,tom,user)
if winning_checker(board,tom,user) == 'computer wins':
print('tom wins')
break
t += 1
k += 1
time.sleep(1)
print('Do you want to play again')
time.sleep(1)
reply = input('enter yes to play again: ')
continue
else:
time.sleep(1)
print('thank you for playing')
break
```

#### Playing Tic-Tac-Toe with your friend

Do you have a friend around? Why not share the fun?

```def tic_tac_toe():
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end = False
win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))

def draw():
print(board, board, board)
print(board, board, board)
print(board, board, board)
print()

def p1():
n = choose_number()
if board[n] == "X" or board[n] == "O":
print("\nYou can't go there. Try again")
p1()
else:
board[n] = "X"

def p2():
n = choose_number()
if board[n] == "X" or board[n] == "O":
print("\nYou can't go there. Try again")
p2()
else:
board[n] = "O"

def choose_number():
while True:
while True:
a = input()
try:
a  = int(a)
a -= 1
if a in range(0, 9):
return a
else:
print("\nThat's not on the board. Try again")
continue
except ValueError:
print("\nThat's not a number. Try again")
continue

def check_board():
count = 0
for a in win_commbinations:
if board[a] == board[a] == board[a] == "X":
print("Player 1 Wins!\n")
print("Congratulations!\n")
return True

if board[a] == board[a] == board[a] == "O":
print("Player 2 Wins!\n")
print("Congratulations!\n")
return True
for a in range(9):
if board[a] == "X" or board[a] == "O":
count += 1
if count == 9:
print("The game ends in a Tie\n")
return True

while not end:
draw()
end = check_board()
if end == True:
break
print("Player 1 choose where to place a cross")
p1()
print()
draw()
end = check_board()
if end == True:
break
print("Player 2 choose where to place a nought")
p2()
print()

if input("Play again (y/n)\n") == "y":
print()
tic_tac_toe()

tic_tac_toe()
```

There you have it. The game is afoot!