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.
Keep Reading
Related Articles
Learning Guides
INNER JOIN in SQL with Examples: Complete Beginner's Guide
Learn INNER JOIN in SQL with practical examples, syntax, interview questions, and real-world use cases. A complete beginner-friendly SQL JOI
Learning Guides
OUTER JOIN in SQL: Complete Guide with Examples for Beginners
Master OUTER JOIN in SQL with practical examples and real-world scenarios. Learn LEFT JOIN, RIGHT JOIN, FULL OUTER JOIN, syntax, use cases,
Learning Guides
Multi-Row Functions in SQL: Complete Guide with Examples
Learn multi-row (aggregate) functions in SQL including SUM, AVG, COUNT, MIN, MAX, GROUP BY and HAVING, with practical examples, NULL handlin