Python
Python

 

Introduction

Tic-Tac-Toe is a classic two-player game played on a 3×3 grid. The objective of the game is to place three of your marks (either “X” or “O”) in a row, column, or diagonal before your opponent does. This Python program is designed to simulate a simple version of the game that can be played in the console, where two players take turns to input their moves.

Objective

The goal of this program is to create a simple, interactive Tic-Tac-Toe game where two players can take turns to place their marks on the grid, and the game will check for a winner or a tie at the end of each turn. The program will display the board after each move and announce the winner once the game concludes.

Python Code


# Tic-Tac-Toe Game in Python

# Function to print the board
def print_board(board):
    for i in range(3):
        print(" | ".join(board[i]))
        if i < 2:
            print("---------")
    print()

# Function to check if a player has won
def check_win(board, player):
    # Check rows, columns and diagonals for a win
    for i in range(3):
        if all([board[i][j] == player for j in range(3)]) or all([board[j][i] == player for j in range(3)]):
            return True

    if board[0][0] == player and board[1][1] == player and board[2][2] == player:
        return True
    if board[0][2] == player and board[1][1] == player and board[2][0] == player:
        return True

    return False

# Function to check if the board is full (tie condition)
def check_tie(board):
    for row in board:
        if " " in row:
            return False
    return True

# Function to play the game
def play_game():
    board = [[" " for _ in range(3)] for _ in range(3)]  # Initialize an empty board
    current_player = "X"
    
    while True:
        print_board(board)
        print(f"Player {current_player}'s turn!")
        
        # Input for row and column
        while True:
            try:
                row, col = map(int, input("Enter row and column (0, 1, 2) separated by space: ").split())
                if row not in range(3) or col not in range(3) or board[row][col] != " ":
                    print("Invalid move, try again!")
                else:
                    break
            except ValueError:
                print("Please enter valid integers separated by a space.")
        
        # Place the current player's mark
        board[row][col] = current_player
        
        # Check if the current player has won
        if check_win(board, current_player):
            print_board(board)
            print(f"Player {current_player} wins!")
            break
        
        # Check if the game is a tie
        if check_tie(board):
            print_board(board)
            print("It's a tie!")
            break
        
        # Switch players
        current_player = "O" if current_player == "X" else "X"

# Main function to start the game
if __name__ == "__main__":
    play_game()

Explanation of the Program

This Python program simulates a Tic-Tac-Toe game in the console. Let’s break down the structure of the program:

  • Function print_board(board): This function prints the current state of the board. It iterates through the 3×3 grid and prints each row. If the row is not the last one, it also prints a separator line.
  • Function check_win(board, player): This function checks whether the given player (either “X” or “O”) has won. It checks all rows, columns, and both diagonals for three consecutive marks of the player.
  • Function check_tie(board): This function checks if the board is full, indicating a tie. If there are no empty spaces left, the game ends in a tie.
  • Function play_game(): This is the main game loop. It initializes the empty board, alternates between players, and handles the game logic such as checking for valid moves, checking for wins or ties, and displaying the board after each move.
  • Input and output: The program accepts user input for the row and column (separated by space) for each move, and outputs the current state of the board after every move. If a player wins or the game ends in a tie, it announces the result and ends the game.

How to Run the Program

To run this Tic-Tac-Toe program:

    1. Ensure you have Python installed on your computer. You can download it from the official Python website.
    2. Save the Python code in a file named tic_tac_toe.py.
    3. Open a terminal or command prompt and navigate to the folder where the file is saved.
    4. Run the following command to start the game:
python tic_tac_toe.py
  1. The game will start, and you will be prompted to enter your moves one by one. Follow the on-screen instructions to play the game!
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)