Python Project – Tic Tac Toe Game

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

# Simple Tic Tac Toe Game 

# Create the game board
board = []
for i in range(9):
    board.append(" ")

# Function to display the board
def display_board():
    print()
    print(board[0] + " | " + board[1] + " | " + board[2])
    print("--+---+--")
    print(board[3] + " | " + board[4] + " | " + board[5])
    print("--+---+--")
    print(board[6] + " | " + board[7] + " | " + board[8])
    print()

# Function to check for a winner
def check_winner(player):
    wins = [
        [0, 1, 2], [3, 4, 5], [6, 7, 8],  # rows
        [0, 3, 6], [1, 4, 7], [2, 5, 8],  # columns
        [0, 4, 8], [2, 4, 6]              # diagonals
    ]
    for combo in wins:
        if board[combo[0]] == board[combo[1]] == board[combo[2]] == player:
            return True
    return False

# Main game loop
def play_game():
    current_player = "X"
    for turn in range(9):
        display_board()
        move = int(input(f"Player {current_player}, choose your move (1-9): ")) - 1
        if board[move] != " ":
            print("That spot is taken. Try again.")
            continue
        board[move] = current_player
        if check_winner(current_player):
            display_board()
            print(f"Player {current_player} wins!")
            return
        current_player = "O" if current_player == "X" else "X"
    display_board()
    print("It's a draw!")

# Start the game
play_game()

 

Your opinion matters
Please write your valuable feedback about DataFlair on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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