Of course! Here is a well-structured and commented Python code for a command-line Tic-Tac-Toe game.
This code is broken down into functions for clarity and is easy to follow, making it great for learning.
Features
- A clear 3x3 board display.
- Input validation (checks for numbers 1-9 and if the spot is already taken).
- Alternating turns between 'X' and 'O'.
- Detection of win and draw conditions.
- An option to play again after a game ends.
The Code
# A list to represent the Tic-Tac-Toe board
# We use numbers 1-9 to show the user which spot corresponds to which number
board = [str(i) for i in range(1, 10)]
current_player = "X"
game_is_still_going = True
def display_board():
"""Prints the current state of the game board to the console."""
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 handle_turn(player):
"""Gets the player's move and updates the board."""
print(f"Player {player}'s turn.")
position = input("Choose a position from 1-9: ")
# Loop until the user enters a valid input
while True:
# Check if the input is a number between 1 and 9
if not position.isdigit() or not (1 <= int(position) <= 9):
position = input("Invalid input. Please choose a number from 1-9: ")
continue
position = int(position) - 1 # Convert to a 0-8 index
# Check if the chosen spot is already taken
if board[position] in ["X", "O"]:
position = input("Position already taken. Choose a different position: ")
else:
break # Valid input, exit the loop
board[position] = player
def check_if_game_over():
"""Checks for a win or a draw and updates the global game state."""
check_for_winner()
check_if_tie()
def check_for_winner():
"""Checks all possible winning combinations (rows, columns, diagonals)."""
global game_is_still_going
# Check rows
row_1 = board[0] == board[1] == board[2]
row_2 = board[3] == board[4] == board[5]
row_3 = board[6] == board[7] == board[8]
# Check columns
col_1 = board[0] == board[3] == board[6]
col_2 = board[1] == board[4] == board[7]
col_3 = board[2] == board[5] == board[8]
# Check diagonals
diag_1 = board[0] == board[4] == board[8]
diag_2 = board[2] == board[4] == board[6]
if row_1 or row_2 or row_3 or col_1 or col_2 or col_3 or diag_1 or diag_2:
game_is_still_going = False
# The winner is the player who just made a move
winner = "O" if current_player == "X" else "X"
display_board()
print(f"Congratulations! Player {winner} won!")
return winner
return None
def check_if_tie():
"""Checks if the board is full, resulting in a tie."""
global game_is_still_going
# If there are no more numbers on the board, it's a tie
if all(spot in ["X", "O"] for spot in board):
game_is_still_going = False
display_board()
print("It's a tie!")
return True
return False
def flip_player():
"""Switches the current player from 'X' to 'O' or vice-versa."""
global current_player
if current_player == "X":
current_player = "O"
else:
current_player = "X"
def play_game():
"""The main function that orchestrates the entire game."""
global board, current_player, game_is_still_going
while True:
# Reset the game state for a new game
board = [str(i) for i in range(1, 10)]
current_player = "X"
game_is_still_going = True
print("--- Welcome to Tic Tac Toe! ---")
while game_is_still_going:
display_board()
handle_turn(current_player)
check_if_game_over()
flip_player()
# Ask the user if they want to play again
play_again = input("Play again? (y/n): ").lower()
if play_again != 'y':
print("Thanks for playing!")
break
# Start the game
if __name__ == "__main__":
play_game()
How to Run the Code
- Save the code in a file named
tictactoe.py.
- Open your terminal or command prompt.
- Navigate to the directory where you saved the file.
- Run the script with the command:
python tictactoe.py
You will see the welcome message and the initial board, and you can start playing!
Explanation of Key Parts
-
board = [str(i) for i in range(1, 10)]: This creates a list representing the 3x3 grid. We initialize it with strings '1' through '9' so the user knows which number to type for each cell.
-
display_board(): This function simply prints the board list in a user-friendly 3x3 format.
-
handle_turn(player): This is the core of user interaction.
- It prompts the current player for their move.
- It uses a
while True loop to continuously ask for input until it's valid.
- It validates that the input is a number from 1-9 and that the chosen spot is not already marked with an 'X' or 'O'.
- Finally, it updates the
board list with the player's mark.
-
check_for_winner(): This function explicitly checks all 8 possible winning conditions (3 rows, 3 columns, and 2 diagonals). If a win is found, it declares the winner and sets game_is_still_going to False.
-
check_if_tie(): A tie occurs when all spots are filled, and no one has won. This function checks if every spot on the board is either an 'X' or an 'O'. If so, it declares a tie and ends the game.
-
flip_player(): A simple but crucial function that switches the current_player variable between 'X' and 'O' after each turn.
-
play_game(): This is the main game loop.
- An outer
while True loop handles the "play again" functionality.
- At the start of each new game, it resets the
board, current_player, and game_is_still_going variables.
- An inner
while game_is_still_going loop runs for a single match, calling the other functions in the correct order: display, get move, check for game over, and flip player.