September 11, 2024

Tic-Tac-Toe in Python

Tic-Tac-Toe is a classic game that can be implemented in Python for practice. Below is a simple text-based version of the game that can be played in the console. The game allows two players to take turns marking a 3×3 grid, with the goal of getting three of their marks in a row, column, or diagonal.

1. Game Implementation

Here’s a complete Python program for a basic two-player Tic-Tac-Toe game:

# Tic-Tac-Toe Game

def print_board(board):
    print("  | 1 | 2 | 3 ")
    print("--------------")
    for i, row in enumerate(board):
        print(f"{i+1} | {' | '.join(row)} |")
        print("--------------")

def check_winner(board, player):
    # Check rows
    for row in board:
        if all([cell == player for cell in row]):
            return True

    # Check columns
    for col in range(3):
        if all([board[row][col] == player for row in range(3)]):
            return True

    # Check diagonals
    if all([board[i][i] == player for i in range(3)]):
        return True
    if all([board[i][2-i] == player for i in range(3)]):
        return True

    return False

def is_full(board):
    return all([cell != ' ' for row in board for cell in row])

def tic_tac_toe():
    board = [[' ' for _ in range(3)] for _ in range(3)]
    players = ['X', 'O']
    turn = 0

    while True:
        print_board(board)
        current_player = players[turn % 2]
        print(f"Player {current_player}'s turn")
        
        try:
            row = int(input("Enter row (1-3): ")) - 1
            col = int(input("Enter column (1-3): ")) - 1
        except ValueError:
            print("Invalid input. Please enter numbers only.")
            continue

        if row not in range(3) or col not in range(3):
            print("Invalid position. Please enter values between 1 and 3.")
            continue

        if board[row][col] != ' ':
            print("Cell already taken. Choose another cell.")
            continue

        board[row][col] = current_player

        if check_winner(board, current_player):
            print_board(board)
            print(f"Player {current_player} wins!")
            break

        if is_full(board):
            print_board(board)
            print("It's a draw!")
            break

        turn += 1

if __name__ == "__main__":
    tic_tac_toe()
    

2. How the Code Works

  • print_board(board): This function prints the current state of the board.
  • check_winner(board, player): This function checks if the given player has won by checking rows, columns, and diagonals.
  • is_full(board): This function checks if the board is full (i.e., no empty spaces left).
  • tic_tac_toe(): The main game loop handles player turns, checks for a win or draw, and updates the board accordingly.

3. Running the Game

To run the Tic-Tac-Toe game, save the code to a file named tic_tac_toe.py and execute it using Python:

$ python tic_tac_toe.py
    

Follow the prompts to enter row and column numbers to place your mark. The game will continue until a player wins or the board is full.

Conclusion

This basic implementation of Tic-Tac-Toe in Python demonstrates how to handle user input, manage game state, and check for win conditions. It’s a good exercise for beginners to practice programming fundamentals and logic.