Python Tic-Tac-Toe Game script
Run a terminal Tic-Tac-Toe game in Python. Learn board state management, turn switching, and win condition checks.
How it Works
Building a game of Tic-Tac-Toe is a classic exercise that reinforces matrix board state representation, loop structures, and conditional comparison logic.
The board is represented as a 3x3 matrix (or a flat list of 9 elements). Two players take turns placing their symbols ('X' or 'O') on the grid. After each move, the script checks if a player has three matching symbols in a row, column, or diagonal.
This implementation includes a game loop that switches active player states, accepts coordinate placements, and automatically stops once a win or tie condition is encountered.
Source Code
A fully functional command line Tic-Tac-Toe game engine running a simulated session.
def print_board(board):
for i in range(3):
row = " | ".join(board[i*3:(i+1)*3])
print(f" {row} ")
if i < 2:
print("---+---+---")
def check_win(board, player):
win_states = [
[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
]
return any(all(board[pos] == player for pos in state) for state in win_states)
def play_tic_tac_toe():
board = [str(i+1) for i in range(9)]
# Simulated sequence of moves (X and O alternating)
moves = [4, 0, 8, 2, 7, 6, 3]
print("Welcome to Tic-Tac-Toe!\n")
print_board(board)
print("\nSimulating Gameplay...")
current_player = 'X'
for move in moves:
if board[move] not in ['X', 'O']:
board[move] = current_player
print(f"\nPlayer {current_player} places on {move+1}:")
print_board(board)
if check_win(board, current_player):
print(f"\nPlayer {current_player} wins the game!")
return
current_player = 'O' if current_player == 'X' else 'X'
print("\nGame ends in a draw!")
play_tic_tac_toe()Welcome to Tic-Tac-Toe!
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Simulating Gameplay...
Player X places on 5:
1 | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
Player O places on 1:
O | 2 | 3
---+---+---
4 | X | 6
---+---+---
7 | 8 | 9
... (moves continue)
Player X wins the game!Real-world Applications
- Interactive command line interface loops
- Simple artificial intelligence minimax routing prototypes
- Learning 2D list array coordinate mappings
Frequently Asked Questions
How can I play against the computer?
To implement an AI opponent, you can use Python's `random` module to select free slots on the board, or use the Minimax algorithm to create an unbeatable opponent.
How do I clear the terminal screen between turns?
You can import `os` and call `os.system('cls' if os.name == 'nt' else 'clear')` to clear standard terminal viewports.
More Examples
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.