Here's a simple Tic Tac Toe game implemented in Python that runs in the command-line interface (CLI). It supports two players taking turns to play the game.
✅ Features:
2-player mode (X and O)
Input validation
Simple grid display
Win and draw detection
🧾 Python Code
python
def print_board(board):
print("\n")
print(f" {board[0]} | {board[1]} | {board[2]} ")
print("---+---+---")
print(f" {board[3]} | {board[4]} | {board[5]} ")
print("---+---+---")
print(f" {board[6]} | {board[7]} | {board[8]} ")
print("\n")
def check_winner(board, player):
win_conditions = [
[0, 1, 2], # Top row
[3, 4, 5], # Middle row
[6, 7, 8], # Bottom row
[0, 3, 6], # Left column
[1, 4, 7], # Middle column
[2, 5, 8], # Right column
[0, 4, 8], # Diagonal \
[2, 4, 6] # Diagonal /
]
for cond in win_conditions:
if board[cond[0]] == board[cond[1]] == board[cond[2]] == player:
return True
return False
def is_draw(board):
return all(cell in ['X', 'O'] for cell in board)
def tic_tac_toe():
board = ['1','2','3','4','5','6','7','8','9']
current_player = 'X'
while True:
print_board(board)
move = input(f"Player {current_player}, enter your move (1-9): ")
if not move.isdigit() or int(move) < 1 or int(move) > 9:
print("Invalid input. Please choose a number between 1 and 9.")
continue
index = int(move) - 1
if board[index] in ['X', 'O']:
print("Cell already taken. Choose another one.")
continue
board[index] = current_player
if check_winner(board, current_player):
print_board(board)
print(f"Player {current_player} wins! 🎉")
break
if is_draw(board):
print_board(board)
print("It's a draw!")
break
# Switch player
current_player = 'O' if current_player == 'X' else 'X'
# Run the game
if __name__ == "__main__":
tic_tac_toe()
▶️ How to Run:
Save the code in a file called tic_tac_toe.py.
Open a terminal or command prompt.
Run it using:
bash
python tic_tac_toe.py
📝 Example Game Flow:
code
1 | 2 | 3
---+---+---
4 | 5 | 6
---+---+---
7 | 8 | 9
Player X, enter your move (1-9): 5