How to Make a Tic Tac Toe Game in Python with Code Example

โšก Smart Summary

Tic Tac Toe in Python is a beginner-friendly project that recreates the classic two-player grid game. Building it strengthens core skills such as loops, conditionals, lists, functions, and recursion while checking rows, columns, and diagonals for a winner.

  • ๐ŸŽฎ Gameplay: Two players mark X and O on a square grid until one completes a row, column, or diagonal.
  • ๐Ÿงฉ Core logic: Nested lists store the board while loops and conditionals drive turns and detect a win or tie.
  • ๐Ÿ—๏ธ Build steps: Create the board, choose the first player, take input, mark cells, then check for a winner each round.
  • ๐Ÿ” Replay: A recursive play() call restarts the match, and input validation blocks occupied or out-of-range moves.
  • ๐Ÿค– AI relevance: The same board is an ideal playground for the minimax algorithm and reinforcement-learning agents.
  • ๐Ÿ› ๏ธ Tools: Only Python and an editor such as PyCharm are needed; no external libraries are required.

Tic Tac Toe Game in Python

Tic Tac Toe Game in Python is an interesting project you can try. It is 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 the Tic Tac Toe Game?

Tic Tac Toe 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 a tie.

Here is 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 for 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 will 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()

Tic Tac Toe Python Code output

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 us dissect the different functions in bits to understand what is going on for each line:

Printing the board

The Tic Tac Toe board is the main game display. In Python, a 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

  • For the row, the function takes every consecutive pair of columns and checks for a winning combination.
  • The first player to fill the rows wins. The second player thus loses.
  • If a pair of consecutive columns are the same, then it is obvious that all elements within that row are the same.
  • If two of them are different or the row contains an empty cell, there is still no winner.
  • We then implement losing conditions and add a break. If any of these losing conditions are true, we did not have a winner in the checked row.
  • The else statement gives a true return to show that there is a winner.
  • The break breaks out of this loop to proceed to the next row.

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 are 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.

  • The first variable is the board size stored in “N”. The game will get the board size after asking the user to enter a number.
  • So, when you enter the value, it is processed.
  • We also create an error message to show the players when any invalid number is typed.
  • We can then create two variables that fill in an “X” or an “O” when a cell is filled.
  • Then show the players the game board. After this, get the player’s input.
  • The logic will then mark the selected cell as filled and check for a win or draw.
  • If there is no winner, the game asks the next player to play. If there is a win or draw, the game can ask the users if they want a new game.

FAQs

Yes. Tic Tac Toe is a classic beginner project that turns loops, conditionals, and functions into a working game. It builds confidence, reinforces core syntax, and prepares you for larger projects without needing any external libraries.

It reinforces nested lists for the board, for loops and while loops for turns, if statements for win checks, functions for structure, and recursion for restarting. These fundamentals transfer directly to more advanced Python programs.

Yes. Beyond the console version, libraries such as Tkinter and Pygame add clickable buttons, a drawn grid, and mouse input. The game logic stays the same; only the display and input layers change.

Tic Tac Toe is a solved game. When both players play optimally, every threat can be blocked, so no one can force a win. That is why a flawless match, human or computer, always finishes in a tie.

A basic console version takes a beginner one to three hours once loops and conditionals feel familiar. Adding input validation, a scalable board, or a graphical interface extends the project across a weekend of practice.

Replace one player with a minimax function. It recursively explores every possible move, scoring wins, losses, and draws, then picks the move with the best guaranteed outcome. On a small board this makes the computer impossible to beat.

Yes. Reinforcement learning agents such as Q-learning improve by playing thousands of games and rewarding winning moves. Boards are stored as arrays with NumPy, letting the model learn a near-optimal strategy without hard-coded rules.

Yes. GitHub Copilot and similar AI assistants can scaffold the board, turn loop, and win checks from a short prompt. Treat the output as a first draft, then test edge cases like ties and invalid moves yourself.

Summarize this post with: