📢
Admissions Open for August 2026 Batch | Free Career Counselling | Limited Scholarships
Register Now →

Learning Guides

Build a Tic-Tac-Toe Game in Python: Complete Code

Quick answer: Learn how to build a two-player Tic-Tac-Toe game in Python using lists, functions and loops, with complete working code and a win-checking algorithm.

What You Will Build

A console based two-player Tic-Tac-Toe game using a 3x3 board represented as a list, alternating turns, and checking for a win or a draw after each move.

Representing the Board

board = [' ' for _ in range(9)]   # 9 empty cells, indexed 0 to 8

def print_board():
    for row in range(0, 9, 3):
        print(f" {board[row]} | {board[row+1]} | {board[row+2]} ")
        if row < 6:
            print("---+---+---")

Checking for a Winner

def check_winner(player):
    winning_combos = [
        [0, 1, 2], [3, 4, 5], [6, 7, 8],   # rows
        [0, 3, 6], [1, 4, 7], [2, 5, 8],   # columns
        [0, 4, 8], [2, 4, 6]               # diagonals
    ]
    for combo in winning_combos:
        if all(board[i] == player for i in combo):
            return True
    return False

The Main Game Loop

def play_game():
    current_player = 'X'

    for turn in range(9):
        print_board()
        move = int(input(f"Player {current_player}, choose a cell (0-8): "))

        if board[move] != ' ':
            print("Cell already taken, try again")
            continue

        board[move] = current_player

        if check_winner(current_player):
            print_board()
            print(f"Player {current_player} wins!")
            return

        current_player = 'O' if current_player == 'X' else 'X'

    print_board()
    print("It's a draw!")

play_game()

How the Win Check Works

The board's 9 cells are indexed 0 to 8. The 8 possible winning lines, 3 rows, 3 columns and 2 diagonals, are stored as index combinations. all(board[i] == player for i in combo) checks whether every cell in a given combination belongs to the same player.

Possible Improvements

  • Add input validation to reject a move index outside 0 to 8

  • Build a simple AI opponent using the minimax algorithm

  • Add a graphical interface using Tkinter instead of the console

Common Interview Questions

How would you represent a Tic-Tac-Toe board in code?

A common approach is a flat list of 9 elements, indexed 0 to 8, rather than a nested 3x3 list, since it simplifies checking the 8 winning combinations as fixed index lists.

How would you check for a draw?

If all 9 cells are filled and check_winner() has not returned true for either player, the game is a draw, which this implementation handles by simply completing all 9 turns without an early win.

FAQ

Frequently Asked Questions

How do you represent a Tic-Tac-Toe board in Python?

A common approach is a flat list of 9 elements, indexed 0 to 8, which simplifies checking rows, columns and diagonals as fixed sets of index positions.

How do you check for a win in Tic-Tac-Toe programmatically?

Define the 8 possible winning combinations of cell indices, then check if all cells in any one combination belong to the same player.

What is a simple way to add an AI opponent to this game?

Implement the minimax algorithm, which simulates all possible future moves to choose the move that minimises the opponent's best possible outcome.

Want This Mapped to Your Own Background?

A free counselling session will tell you which path fits, and will tell you honestly if none of ours does.

Book Free Career Counselling

Keep Reading

Related Articles