Untitled

 avatar
unknown
plain_text
2 months ago
3.4 kB
1
Indexable
import tkinter as tk
import random

class TicTacToeGame:
    def __init__(self, master):
        self.master = master
        self.master.title("Tic-Tac-Toe")
        
        # The game board, a list of buttons
        self.board = [None] * 9
        self.buttons = [None] * 9
        self.current_player = "X"  # X starts the game
        self.game_over = False
        
        self.create_buttons()

    def create_buttons(self):
        """
        Creates a 3x3 grid of buttons.
        """
        for i in range(9):
            self.buttons[i] = tk.Button(self.master, text=" ", font=("Arial", 24), width=5, height=2,
                                        command=lambda i=i: self.on_button_click(i))
            row, col = divmod(i, 3)
            self.buttons[i].grid(row=row, column=col)
            self.board[i] = None  # Initially, no moves on the board.

    def on_button_click(self, index):
        """
        Handles the button click event, placing X or O based on the current player.
        """
        if self.board[index] is not None or self.game_over:
            return  # Do nothing if the cell is already filled or the game is over
        
        self.board[index] = self.current_player
        self.buttons[index].config(text=self.current_player)
        
        # Check for win or tie
        if self.check_win():
            self.display_winner(f"Player {self.current_player} wins!")
            return
        if self.is_full():
            self.display_winner("It's a tie!")
            return
        
        # Switch player
        self.current_player = "O" if self.current_player == "X" else "X"
        
        # If it's computer's turn (O), let the computer play
        if self.current_player == "O" and not self.game_over:
            self.computer_move()

    def check_win(self):
        """
        Checks if the current player has won the game.
        """
        # Winning combinations (index positions in the 3x3 grid)
        win_combinations = [
            [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 combination in win_combinations:
            if self.board[combination[0]] == self.board[combination[1]] == self.board[combination[2]] != None:
                return True
        return False

    def is_full(self):
        """
        Checks if the board is full.
        """
        return all(cell is not None for cell in self.board)

    def display_winner(self, message):
        """
        Displays the winner message and disables all buttons.
        """
        self.game_over = True
        for button in self.buttons:
            button.config(state="disabled")
        
        winner_label = tk.Label(self.master, text=message, font=("Arial", 16))
        winner_label.grid(row=3, column=0, columnspan=3)

    def computer_move(self):
        """
        Makes a random move for the computer (player "O").
        """
        available_moves = [i for i in range(9) if self.board[i] is None]
        if available_moves:
            move = random.choice(available_moves)
            self.on_button_click(move)

def main():
    root = tk.Tk()
    game = TicTacToeGame(root)
    root.mainloop()

if __name__ == "__main__":
    main()
Leave a Comment