Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Create a Tic Tac Toe Game in Python: Step-by-Step Code Tutorial

Tic Tac Toe Game in Python is an interesting project you can try. It’s a cool and fun project of solving a challenge and can help you master basic concepts in Python. Creating a fun tic tac toe game helps you grow your skills.

You can use a good Python editor such as Pycharm or the command line interface.

How to play Tic Toc Game?

Tic tac toe game is a simple two-player game that anyone can play without needing a game board. It involves two players marking different cells until the game ends, in a win or tie is achieved.

Here’s how to play the tic tac toe game.

Step 1) The tic tac toe game begins with empty cells in a square grid. This is the tic tac toe board.

Step 2) Both players choose from two symbols, usually Xs or Os. You can use any other unique symbol in the game.

Step 3) The current player marks in turns by filling out the cells of the tic tac toe board until a player fills a winning combination. That is an entire row, column, or diagonal with the same sign.

Step 4) A game tie is also possible in case all cells are full with no apparent winner

Requirements

Building the tic tac toe Python project requires a beginner-level understanding of Python programming language. It includes understanding “for” loops and iterations and what an if statement is used in Python.

You also need to have Python and a Python text editor installed on your computer to complete the tic-tac-toe Python project. As this is a beginner-level tic tac-toe game in Python, you’ll not need any Python library.

You may need some debugging skills in order to find solutions to bugs in your code and you should also have an adequate understanding of the game components.

Tic Tac Toe Python Algorithm

Follow these steps to create a tic tac toe game in Python programming language:

Step 1) Create the board to begin the tic tac toe game.

Step 2) Request the user to decide on the game board dimensions.

Step 3) Randomly choose the first player.

Step 4) Tic tac toe game starts.

Step 5) Players play by selecting an empty spot on the board.

Step 6) Fill the empty selected spot with the player’s sign.

Step 7) Determine if a player wins or gets a tie in the game using the game logic.

Step 8) Display the game board after every play if no player wins or gets a tie to the second player.

Step 9) Display a tie or win message, respectively.

Step 10) End the tic tac toe game with options to start a new game.

Full Python code for tic tac toe

# Guru99
# Code developed by Guru99.com
# Guru99 tic-tac-toe game
#Get input
def getInput(prompt, cast=None, condition=None, errorMessage=None):
 while True:
 try:
 val = cast(input(prompt))
 assert condition is None or condition(val)
 return val
 except:
 print(errorMessage or "Invalid input.")
# Print the game board
def printBoard(board):
 print()
 for row in board:
 print(*row)
 print()
# Check if player won using the winning combinations
def checkWin(board):
 # Check rows
 for row in range(len(board)):
 for col in range(len(board)-1):
 if board[row][col] == "_" or board[row][col+1] == "_" or board[row][col] != board[row][col+1]:
 break
 else:
 return True
 # Check column numbers
 for col in range(len(board)):
 for row in range(len(board)-1):
 if board[row][col] == "_" or board[row+1][col] == "_" or board[row][col] != board[row+1][col]:
 break
 else:
 return True
 # Check left diagonal
 for cell in range(len(board)-1):
 if board[cell][cell] == "_" or board[cell+1][cell+1] == "_" or board[cell][cell] != board[cell+1][cell+1]:
 break
 else:
 return True
 # Check right diagonal
 for cell in range(len(board)-1):
 emptyCell = board[cell][len(board)-cell-1] == "_" or board[cell+1][len(board)-cell-2] == "_"
 different = board[cell][len(board)-cell-1] != board[cell+1][len(board)-cell-2]
 if emptyCell or different:
 break
 else:
 return True
 # No win
 return False
# Play tic tac toe game
def play():
 # Introduction
 print("------------\nN-DIMENSIONAL TIC TAC TOE game by guru 99.com \n------------")
 # Set up variables
 N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ",
 cast=int,
 condition=lambda x: x >= 3,
 errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com")
 board = [['_'] * N for _ in range(N)]
 used = 0
 turn = 0
 # Play guru99 tic tac toe game in Python using while infinite loop
 while True:
 # Print guru99 tic tac toe game board
 printBoard(board)
 # Get user pick
 pick = getInput(prompt=f"Player {turn+1} - Pick location (row, col): ",
 cast=lambda line: tuple(map(int, line.split(" "))),
 condition=lambda pair: min(pair) >= 0 and max(pair) < N and board[pair[0]][pair[1]] == "_",
 errorMessage="Invalid input. Please enter a valid, unoccupied location as an integer pair.")
 # Populate location
 board[pick[0]][pick[1]] = "X" if turn == 0 else "O"
 used += 1
 # Check for win
 #Guru99 tutorial
 if checkWin(board):
 printBoard(board)
 print(f"Game over, Player {turn+1} wins.")
 break
 # Check for tie
 elif used == N*N:
 printBoard(board)
 print("Game over. Players have tied the match.")
 print("Guru99.com tic tac toe game ")
 break
 # If no win yet, update next user
 turn = (turn+1)%2
 # Check for rematch
 playAgain = getInput(prompt="Play Guru99 tic tac toe_Game again? (y/n): ",
 cast=str,
 condition=lambda ans: ans.strip("\n").lower() in {"y", "n"},
 errorMessage="Invalid input. Please enter 'y' or 'n'.")
 if playAgain == 'n':
 # End the game
 print("\nGuru99 TicTacToe game ended.")
 return
 else:
 # Rematch
 play()
# Main
if __name__ == '__main__':
 play()

Once you run the source code above, below is the expected output for a 3 X 3 tic tac toe board:

------------
N-DIMENSIONAL TIC TAC TOE game by guru 99.com
------------
Guru99 says>>> Enter N, the dimensions of the board: 3
_ _ _
_ _ _
_ _ _
Player 1 - Pick location (row, col): 1 1
_ _ _
_ X _
_ _ _
Player 2 - Pick location (row, col): 0 1
_ O _
_ X _
_ _ _
Player 1 - Pick location (row, col): 1 2
_ O _
_ X X
_ _ _
Player 2 - Pick location (row, col): 0 2
_ O O
_ X X
_ _ _
Player 1 - Pick location (row, col): 1 0
_ O O
X X X
_ _ _
Game over, Player 1 wins.
Play Guru99 tic tac toe_Game again? (y/n):

Full Code Breakdown

Creating tic tac toe in Python is simple. Let’s dissect the different functions in bits to understand what’s going on for each line:

Printing the board

The Tic tac toe board is the main game display. In, Python display window is used to show the game board.

Here are the steps that help you to create a board for tic tac toe in Python:

Python code for Tic Tac Toe

def getInput(prompt, cast=None, condition=None, errorMessage=None):
 while True:
 try:
 val = cast(input(prompt))
 assert condition is None or condition(val)
 return val
 except:
 print(errorMessage or "Invalid input.")
# Print the board
def printBoard(board):
 print()
 for row in board:
 print(*row)
 print()
N = getInput(prompt="Guru99 says>>> Enter N, the dimensions of the board: ",
 cast=int,
 condition=lambda x: x >= 3,
 errorMessage="Invalid input. Please enter an integer greater than or equal to 3 as explained on guru99.com")
board = [['_'] * N for _ in range(N)]
used = 0
turn = 0
printBoard(board)

Code output:

------------
N-DIMENSIONAL TIC TAC TOE game by guru 99.com
------------
Guru99 says>>> Enter N, the dimensions of the board: 3
_ _ _
_ _ _
_ _ _

Tic Tac Toe Game – winning arrangement

To check if any player won, we need to check the winning combinations across the rows, columns, and diagonals. If there is a winner, we need to show a winning message.

Rows

Columns

For the columns, we repeat the same function as in rows. We check if a player won after each player chooses their place.

Diagonal row wins

For the left diagonal, the task becomes simpler. We’re always going to be comparing the cells in the diagonals. However, in case there is no winner, we can proceed to the next instruction.

Play game logic

This is the main game function. For this we can use variables that store information.

Conclusion


Python

  1. Python Module Importing – A Practical Guide with Examples
  2. Python abs() Function: Compute Absolute Values for Numbers & Complex Numbers
  3. Python Image Processing with Pillow: Comprehensive Guide
  4. Check Your Python Version on Linux, macOS, and Windows: A Quick Guide
  5. Master Python String Operations: Replace, Join, Split, Reverse, and Case Conversion
  6. Python Matrix Operations with NumPy: Transpose, Addition, Multiplication & Slicing – A Practical Guide
  7. Master Python File Handling: Create, Read, Write, and Open Text Files with Ease
  8. Python Glossary: Essential Terms and Definitions
  9. Master Emoji Handling in Python: Convert, Display, and Use Unicode Emoticons
  10. Real Python Office Hours: Live Q&A Sessions for Python Learners