Tic-Tac-Toe In Python

Tic-Tac-Toe In Python

Introduction

 
Tic Tac Toe is a timeless game that blends simplicity with strategic depth. The game involves two players alternately marking spaces on a 3×3 grid, aiming to place three of their symbols in a row, column, or diagonal to win. 

Despite its straightforward rules, Tic Tac Toe provides valuable insights into game strategy and decision-making. Coding a Tic Tac Toe game offers a fantastic entry point into the world of programming, where you can learn about game design, algorithms, and user interaction in a manageable and engaging way.

Coding a Paint Program in Python

How To Recover your Instagram Password
Learn Python

What You Need To Know

Understanding how to code a Tic Tac Toe game is more than just a programming exercise—it’s an excellent way to grasp fundamental concepts in computer science and game development. 

By building this game, you will gain practical experience with basic programming constructs such as loops, conditionals, and data structures. You’ll also delve into game logic and AI strategies, which are applicable to more complex games. This foundational knowledge is essential for anyone interested in software development, as it lays the groundwork for more advanced projects and enhances problem-solving skills.

Tic-Tac-Toe With Python (Full Code)

def print_board(board):
    # Print the Tic Tac Toe board with current marks
    for row in board:
        print(" | ".join(row))  # Join each row's elements with " | " and print
        print("-" * 9)  # Print a line of dashes to separate rows

def check_win(board, player):
    # Check if the current player has won the game
    # Check rows
    for row in board:
        if all(cell == player for cell in row):  # Check if all cells in the row are the same as the player's mark
            return True

    # Check columns
    for col in range(3):
        if all(board[row][col] == player for row in range(3)):  # Check if all cells in the column are the same as the player's mark
            return True

    # Check diagonals
    if all(board[i][i] == player for i in range(3)) or \
       all(board[i][2-i] == player for i in range(3)):  # Check both main diagonal and anti-diagonal
        return True

    return False  # Return False if no winning condition is met

def is_board_full(board):
    # Check if the board is full (tie game)
    for row in board:
        if " " in row:  # If there is an empty space in any row, board is not full
            return False
    return True  # Return True if board is full

def main():
    board = [[" " for _ in range(3)] for _ in range(3)]  # Create a 3x3 empty Tic Tac Toe board
    players = ['X', 'O']  # Players' marks
    turn = 0  # Initialize turn counter

    print("Welcome to Tic Tac Toe!")  # Print welcome message

    while True:
        print_board(board)  # Display current board
        player = players[turn % 2]  # Determine current player

        print(f"Player {player}'s turn")  # Indicate current player's turn

        while True:
            try:
                row = int(input("Enter row number (1-3): ")) - 1  # Input row number (adjust for zero-based indexing)
                col = int(input("Enter column number (1-3): ")) - 1  # Input column number (adjust for zero-based indexing)

                if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == " ":  # Check if the chosen cell is empty and within board boundaries
                    board[row][col] = player  # Place player's mark on the board
                    break
                else:
                    print("Invalid move. Try again.")  # Notify if move is invalid
            except ValueError:
                print("Invalid input. Please enter a number.")  # Handle invalid input (non-numeric)

        if check_win(board, player):  # Check if current player has won
            print_board(board)  # Display final board
            print(f"Player {player} wins!")  # Announce winner
            break
        elif is_board_full(board):  # Check if board is full (tie game)
            print_board(board)  # Display final board
            print("It's a tie!")  # Announce tie game
            break

        turn += 1  # Increment turn counter

if __name__ == "__main__":
    main()  # Start the Tic Tac Toe game
 
How To Recover your Instagram Password

Improve The Game

Post Comment