Table of contents
- Let's first understand the project scope:
- Step 1: Display the Board
- Step 2: Take Player Input
- Step 3: Place the Marker on the Board
- Step 4: Check for a Win
- Step 5: Random module to randomly decide which player goes first
- Step 6: Check for an Empty Space on the Board
- Step 7: Detect a Draw by Checking the Full Board
- Step 8: Player's Move
- Step 9: Ask for a Replay
- Step 10: Game Execution
- Conclusion
In this blog post, we'll build a classic two-player Tic-Tac-Toe game that involves creating a board, taking player input, placing their input on the board, and checking for a win, tie, or ongoing game using Python.
Let's first understand the project scope:
We need to print a board.
Take in players' input.
Place their input on the board.
Check if the game is won, tied, lost, or ongoing.
Repeat the third and fourth points until the game has been won or tied.
Ask if players want to play again.
Step 1: Display the Board
The first step is to create a function that displays the Tic-Tac-Toe board. The display_board
function takes a list representing the current state of the board and prints it on the screen.
Note: To clear the screen between moves we're using: print('\n'*100)
This scrolls the previous board up out of view. Now on to the program!
def display_board(board):
print('\n'*100)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
test_board = ['#','X','O','X','O','X','O','X','O','X']
Step 2: Take Player Input
Next, we need to take player input.
The player_input
function prompts Player 1 to choose 'X' or 'O' and returns the markers for both players accordingly.
def player_input():
marker = ''
while not (marker == 'X' or marker == 'O'):
marker = input('Player 1: Do you want to be X or O? ').upper()
if marker == 'X':
return ('X', 'O')
else:
return ('O', 'X')
TIP๐ก: The input() takes in a string. If you need an integer value, use:
position = int(input('Please enter a number'))
Step 3: Place the Marker on the Board
Now, let's create a function called place_marker
that allows us to put the player's chosen marker ('X' or 'O') on the Tic Tac Toe board at a specified position. This function will be crucial in updating the board with each player's move.
def place_marker(board, marker, position):
board[position] = marker
#You can run the place marker function using test parameters like this:
place_marker(test_board,'$',8)
display_board(test_board)
Step 4: Check for a Win
The win_check
function checks if a player has won the game by examining all possible winning combinations.
def win_check(board,mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top
(board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
(board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom
(board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle
(board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle
(board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side
(board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal
(board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal
#Run a test check
win_check(test_board,'X')
Step 5: Random module to randomly decide which player goes first
In this step, we'll create a function named choose_first
to randomly decide which player gets the first turn. The function will generate a random choice between Player 1 and Player 2, setting the initial momentum for the game.
import random
def choose_first():
if random.randint(0, 1) == 0:
return 'Player 2'
else:
return 'Player 1'
Step 6: Check for an Empty Space on the Board
The space_check
function checks if a specified position on the board is empty.
def space_check(board, position):
return board[position] == ' '
Step 7: Detect a Draw by Checking the Full Board
The full_board_check
will help us determine if there are any available spaces left on the board, thus indicating a potential tie.
def full_board_check(board):
for i in range(1,10):
if space_check(board, i):
return False
return True
Step 8: Player's Move
The player_choice
is a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if it's a free position. If it is, then return the position for later use.
def player_choice(board):
position = 0
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
position = int(input('Choose your next position: (1-9) '))
return position
Step 9: Ask for a Replay
The replay
function asks the player if they want to play again and returns a boolean True
if they do want to play again.
def replay():
return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')
Step 10: Game Execution
Here comes the hero of this whole program, we'll be using while loops and the functions we've made so far to run the game!
#Prints a nice message
print('Welcome to Tic Tac Toe!')
while True:
# Reset the board
theBoard = [' '] * 10
player1_marker, player2_marker = player_input()
turn = choose_first()
print(turn + ' will go first.')
play_game = input('Are you ready to play? Enter Yes or No.')
if play_game.lower()[0] == 'y':
game_on = True
else:
game_on = False
while game_on:
if turn == 'Player 1':
# Player1's turn.
display_board(theBoard)
position = player_choice(theBoard)
place_marker(theBoard, player1_marker, position)
if win_check(theBoard, player1_marker):
display_board(theBoard)
print('Congratulations! You have won the game!')
game_on = False
else:
if full_board_check(theBoard):
display_board(theBoard)
print('The game is a draw!')
break
else:
turn = 'Player 2'
else:
# Player2's turn.
display_board(theBoard)
position = player_choice(theBoard)
place_marker(theBoard, player2_marker, position)
if win_check(theBoard, player2_marker):
display_board(theBoard)
print('Player 2 has won!')
game_on = False
else:
if full_board_check(theBoard):
display_board(theBoard)
print('The game is a draw!')
break
else:
turn = 'Player 1'
if not replay():
break
Conclusion
And there you have itโa fully functional game built using Python ๐ ๐
There can be different ways to build the same, don't worry if your solution looks a little different. Have fun building!
GitHub Gist: https://github.com/Insharamin12/Tic-Tac-Toe-Game