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.
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):
print(board[7]+"|"+board[8]+"|"+board[9])
print("-|-|-")
print(board[4]+"|"+board[5]+"|"+board[6])
print("-|-|-")
print(board[1]+"|"+board[2]+"|"+board[3])
print("-|-|-")
testing_board=[" "]*10
display_board(testing_board)
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":
return("o","x")
elif marker=="x":
return ("x","o")
else:
return("Please choose appropriate marker")
player_input()
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"
else:
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.
def handle_turn(board,marker,position):
board[position]=marker
handle_turn(testing_board,"x",5)
display_board(testing_board)
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 while
loop, 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_marker
and player2_marker
as 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
else:
game_is_on = Falsewhile game_is_on:
if turn=="player 1":
display_board(theBoard)
print ("player 1")
position=player_choice(theBoard)
handle_turn(theBoard,player1_marker,position)
if check_win(theBoard,player1_marker):
display_board(theBoard)
print('Congratulations! player 1 has won the game!')
game_is_on=False
else:
if fullboardcheck(theBoard):
display_board(theBoard)
print('The game is a draw!')
break
else:
turn = 'player 2'else:
display_board(theBoard)
print ("player 2")
position = player_choice(theBoard)
handle_turn(theBoard, player2_marker, position)if check_win(theBoard, player2_marker):
display_board(theBoard)
print('Player 2 has won the game!')
game_is_on=Falseelse:
if fullboardcheck(theBoard):
display_board(theBoard)
print('The game is a draw!')
break
else:
turn = 'player 1'
if not replay():
break
This is how one can play their own game
For further references on the code, click here.