Tic-Tac-Toe Python Game Engine With an AI Player


Let's break down the code step by step. I'll provide explanations along with the code snippets.

Step 1: Import Libraries

import tkinter as tk

from tkinter import messagebox

Here, we import the tkinter library for creating the graphical user interface (GUI) and the messagebox module to display message boxes.

Step 2: Define Utility Functions for the Game Engine

# ... (code for print_board, is_winner, is_board_full, get_empty_cells, minimax, get_best_move)

These functions are part of the Tic-Tac-Toe game engine. They handle operations like printing the game board, checking for a winner, checking if the board is full, finding empty cells, and implementing the Minimax algorithm for the AI player.

Step 3: Create a GUI Class

class TicTacToeGUI:

    def __init__(self, root):

        self.root = root

        self.root.title("Tic Tac Toe")

        self.board = [[' ' for _ in range(3)] for _ in range(3)]

        self.buttons = [[None for _ in range(3)] for _ in range(3)]

 

        for i in range(3):

            for j in range(3):

 

self.buttons[i][j] = tk.Button(root, text='',font=('normal', 20), width=6, height=2,command=lambda row=i, col=j:self.on_button_click(row, col))

 

        self.buttons[i][j].grid(row=i, column=j)

 

        self.player_turn = True  # True for 'X', False for 'O'

This class, TicTacToeGUI, initializes the GUI. It creates the main window (root), sets its title, and creates the game board and buttons. The buttons are arranged in a 3x3 grid, and their click events are linked to the on_button_click method.

Step 4: Handle Button Clicks

    def on_button_click(self, row, col):

        if self.board[row][col] == ' ':

            if self.player_turn:

                self.board[row][col] = 'X'

            else:

                self.board[row][col] = 'O'

                ai_move = get_best_move(self.board)

                self.board[ai_move[0]][ai_move[1]] = 'O'

 

            self.update_buttons()

 

            if is_winner(self.board, 'X'):

                self.show_winner_message('Player X wins!')

            elif is_winner(self.board, 'O'):

                self.show_winner_message('AI player wins!')

            elif is_board_full(self.board):

                self.show_tie_message()

            else:

                self.player_turn = not self.player_turn

This method is called when a button is clicked. It updates the game board based on the player's move and the AI's move. It then checks if there's a winner or if the game is a tie, and updates the GUI accordingly.

Step 5: Update Buttons on the GUI

    def update_buttons(self):

        for i in range(3):

            for j in range(3):

                self.buttons[i][j].config(text=self.board[i][j])

This method updates the text on the buttons to reflect the current state of the game board.

Step 6: Display Winner and Tie Messages

    def show_winner_message(self, message):

        messagebox.showinfo("Game Over", message)

        self.reset_game()

 

    def show_tie_message(self):

        messagebox.showinfo("Game Over", "It's a tie!")

        self.reset_game()

These methods display message boxes with information about the game outcome (winner or tie). They then call the reset_game method to prepare for a new game.

Step 7: Reset the Game

    def reset_game(self):

        for i in range(3):

            for j in range(3):

                self.board[i][j] = ' '

                self.buttons[i][j].config(text='')

        self.player_turn = True

This method resets the game board and buttons for a new game.

Step 8: Main Execution

if __name__ == "__main__":

    root = tk.Tk()

    game_gui = TicTacToeGUI(root)

    root.mainloop()

This code creates the main window (root) and the TicTacToeGUI instance, then starts the main event loop using root.mainloop() to keep the GUI running.

Now, you can run this code in a Python environment, and a Tic-Tac-Toe game window with a graphical interface will appear. You can play against the AI player, and the GUI will handle the game mechanics and display the results.


DOWNLODE CODE


Post a Comment

0 Comments