Naughts and Crosses with Python

With enhancing technologies, naughts and crosses, a very common tic-tac-toe game, has moved from paper to our laptops. This is an attempt to design the same using Python.

Yãshñã Bëhërã
Apr 3 · 6 min read

Python is a great language to learn for the beginners. Once the basic syntaxes are grasped, it’s best to start making own projects. Projects are a great way to learn, because it gives an opportunity to apply the knowledge acquired as otherwise, it is difficult to retain the same.

I have been learning Python for a while now. As one of my first mini-projects I designed a simple tic-tac-toe game. It is a common 2-player game where one player plays crosses (X) and the other plays naughts(O), each player taking turns to play. The player who gets three marks on the board in a row, column, or diagonally, wins. In case neither of the players is able to get this, the game then ends in a draw. The steps to create this game on Python using some of the basic functions are described in the succeeding steps.

Step 1: Grid Board Design

Start making the tic-tac-toe grid by definingdisplay_board()function, which will display it in a grid format when printed

def display_board(board):
testing_board=[" "]*10

This is how the board will be printed

Step 2: Choosing Each Player’s Marker

Next the players’ marker are made by creating player_input()function by using while loop for player 1 to choose his/her marker; X or O. Once the marker has been chosen by player 1, then the alternate marker is automatically allotted to player 2 using if function.

def player_input():
marker=" "
while marker !="x" or marker !="o":
marker= input("player 1 choose x,o: ")
if marker=="o":
elif marker=="x":
return ("x","o")
return("Please choose appropriate marker")

Step 3: Deciding the First Move

Import random library to decide which player will start the game. It is a built-in library in Python, which is used to generate random numbers between two given numbers. Define a function first_move() to generate a random number using random_randint()function between 0 and 1 to decide which player is going to start first. If the random number is equal to 1, then player 1 will start the game. If it is 0 then player 2 will start the game.

import randomdef first_move():
if random.randint(0,1)==0:
return "player 2 will start the game"
return "player 1 will start the game"

Step 4: Deciding Where to Move the Marker

For placing the marker on a given position, define a function handle_turn() in which pass 3 parameters; board, marker and position. In this board would be the tic-tac-toe grid. Marker would be X and O. Position would be the spot where the marker would be placed on the board. Equate marker to the position on the board.

The markers can be placed on the grid using the numbers 1–9 of the computer keyboard. The design is inspired by the numerical pad on keyboards.

Microsoft Number Pad
def handle_turn(board,marker,position):

Step 5: Free Space for Next Move

Checking for free space, which means empty positions on the board, is the next step. In free space check whether any particular position on the board is freely available or not. Define space_free() function in which board and position would be passed as parameters, where it will return boolean true, if board at that position is equal to empty string.

def space_free(board,position):
return board[position]==" "

Step 6: Full Board Check

Do full board check to ascertain if all the positions on the board are occupied or not. In fullboadcheck() function pass board as a parameter. Use for loop that goes for i in range 1 to 10, where i is all the possible positions on the board. Using if function state that if any given position of i on the board is empty, then the board is not full and it will return false.

def fullboardcheck(board):
for i in range(1,10):
if space_free(board, i):
return False
return True

Step 7: The Next Move

Next make player_choice() function that will take input from the player regarding where to place marker on the board for the next move if it is a free position. If the position number given by the player is already occupied, for eg, if player 1 has chosen position 5 and in next turn player 2 also tries to place marker on the same position, then player 2 will be asked to choose a different position that is not occupied. This can be done by using a while loop that will check if the player is inputting wrong number or any letter in position number that is not in the range between 1 to 9. It also checks whether that position space is still available or not.

def player_choice(board):
position = 0

while position not in range(1,10)or not space_free(board, position):
position = int(input('Choose your next position: (1-9) '))
return position

Step 7: Winner

Next check for wins. Make check_win() function in which pass board and marker as parameters, which is going to check the board row wise, column wise and diagonally for win. Win is when three markers on the board of a player are aligned vertically, horizontally, or diagonally.

def check_win(board, mark):
return ((board[7]==mark and board[8]==mark and board[9]==mark)or
(board[4]==mark and board[5]==mark and board[6]==mark)or
(board[1]==mark and board[2]==mark and board[3]==mark)or
(board[7]==mark and board[4]==mark and board[1]==mark)or
(board[8]==mark and board[5]==mark and board[2]==mark)or
(board[9]==mark and board[6]==mark and board[3]==mark)or
(board[7]==mark and board[5]==mark and board[3]==mark)or
(board[9]==mark and board[5]==mark and board[1]==mark))

Step 8: Replay

For this make a function for game to restart. Define replay() function, which will take input from the player to play again or not.

def replay():
return input('Do you want to play again? Enter Yes or No: ')

Step 9: Combining all Together

Consolidate all the above functions together to create the game. Start with whileloop, which creates an infinite loop, the code keeps on executing as long as a given boolean condition evaluates to true. Set up the board, assign player1_markerand player2_markeras player_input()where the players decide their markers and assign first_move()as turn that decides which player will go first. Initiate the game taking input from the player. If ready to play, enter Yes or No. If the player enters yes, then the game starts. Players are asked which position they want to mark so on and so forth. Once the game is finished, option is offered whether they want to replay or not.

while True:
theBoard = [' '] * 10
player1_marker, player2_marker = player_input()
turn = first_move()
print (turn + " and will go first")

#game play
play_game = input('Are you ready to play? Enter Yes or No.')
if play_game == ("Yes"):
game_is_on = True
game_is_on = False
while game_is_on:
if turn=="player 1":
print ("player 1")

if check_win(theBoard,player1_marker):
print('Congratulations! player 1 has won the game!')
if fullboardcheck(theBoard):
print('The game is a draw!')
turn = 'player 2'
print ("player 2")
position = player_choice(theBoard)
handle_turn(theBoard, player2_marker, position)
if check_win(theBoard, player2_marker):
print('Player 2 has won the game!')
if fullboardcheck(theBoard):
print('The game is a draw!')
turn = 'player 1'

if not replay():

This is how one can play their own game

For further references on the code, click here.

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data…

Sign up for Analytics Vidhya News Bytes

By Analytics Vidhya

Latest news from Analytics Vidhya on our Hackathons and some of our best articles! Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem

Yãshñã Bëhërã

Written by

Analytics Vidhya

Analytics Vidhya is a community of Analytics and Data Science professionals. We are building the next-gen data science ecosystem

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store