CSE3664 - ProjectReport - Tic Tac Toe Game With AI Player
CSE3664 - ProjectReport - Tic Tac Toe Game With AI Player
Submitted To:
Amit Mandal
Submitted By:
1|Page
Introduction
This article details the procedural steps involved in creating a Tic Tac Toe game
with an artificial intelligence player using the Minimax algorithm. The main goal
was to develop a sophisticated AI adversary that could offer a demanding
gameplay encounter for human participants.
Project Goal
Tic Tac Toe Game: Creating a program that allows two players, one human
and one AI, to alternate turns and make movements on a game board. The
game must accurately process legal moves, identify a victory or draw, and
deliver suitable feedback to the players.
AI Player: Developing an AI player by implementing a suitable algorithm,
such as the Minimax algorithm, to generate intelligent movements. The AI
should possess the capability to discern the optimal move by considering
the present configuration of the board and strategically aim to secure
victory or prevent the opponent from achieving it.
Game Interface: Creating an intuitive interface to enhance the ease of
communication between the human player and the AI. The interface should
exhibit the Tic Tac Toe board, elicit the human player's move, and exhibit
the AI's move.
Difficulty Levels: Incorporation of distinct difficulty levels for the AI
player, with varying levels of intellect. For instance, we can offer three
levels of difficulty: easy, medium, and hard, each corresponding to distinct
AI techniques.
2|Page
Problem Description:
This research will explore the realm of game-playing agents and artificial
intelligence.
The goal is to create a Tic Tac Toe game implementation that incorporates an
artificial intelligence player.
AI Algorithm: Minimax
The Minimax algorithm is a method used to determine the optimal move in a two-
player game with perfect information. It works by considering all possible moves
and their potential outcomes, and then selecting the move that maximizes the
player's chances of winning while minimizing the opponent's chances.
Game tree: The Minimax method initiates by creating a game tree that depicts
every conceivable action and its corresponding outcomes. The tree's levels
correspond to each player's turn, while its branches indicate the available moves
for each player. The tree grows continuously until it achieves a final state, such
as a victory, defeat, or tie, or until a predetermined depth is reached.
3|Page
Optimizing and minimizing: The Minimax method iterates between two distinct
sorts of nodes within the game tree:
Max Nodes: These nodes correspond to the player who aims to maximize their
score, such as the person striving to achieve victory. During each maximum node,
the algorithm chooses the child node with the highest score in order to optimize
the player's probability of winning.
Min Nodes: These nodes correspond to the opponent player, whose objective is
to minimize the score of the current player. During each min node, the algorithm
chooses the kid node with the lowest score in order to maximize the weakness of
the current player's position, as desired by the opponent.
Backtracking: During the exploration of the game tree, the algorithm returns to
previous nodes, transmitting the highest scores discovered up to that point. The
procedure iterates until it reaches the root of the tree, at which point the algorithm
chooses the move that leads to the child node with the maximum score for the
maximizing player.
Development Process
The development process can be divided into several key steps:
4|Page
Game Initialization:
The Tic Tac Toe game was started with a grid size of 3x3.
The board was depicted as a list consisting of 9 components, with each
element initially assigned the value of ' ' (empty).
Obstacles Encountered:
We lack expertise in Python. We encountered numerous challenges pertaining to
the grammar of Python. We encountered numerous mistakes during the coding
phase of our project. We have had difficulties concerning the storylines as well.
Through extensive deliberation and numerous iterations, we successfully
resolved the issues at hand.
The development of the Minimax algorithm and the verification of its accurate
evaluation of all potential game states posed a significant challenge.
5|Page
User Interface Integration:
Incorporating the AI into a user-friendly interface to enhance gameplay
encountered several complications.
Enhancing Performance:
Enhancing the algorithm's efficiency for larger game boards and more intricate
games can pose a challenge.
import tkinter as tk
from tkinter import ttk, messagebox
import random
class TicTacToeGUI:
def __init__(self, difficulty_level):
self.root = tk.Tk()
self.root.title("Tic Tac Toe")
style = ttk.Style()
style.configure('TButton', font=('Arial', 18), width=6, height=3)
style.configure('Square.TButton', width=6, height=3)
style.configure('PlayerX.TButton', foreground='blue', width=6,
height=3)
style.configure('PlayerO.TButton', foreground='red', width=6, height=3)
for i in range(3):
for j in range(3):
self.buttons[i][j].grid(row=i, column=j)
6|Page
self.buttons[row][col].configure(style='PlayerX.TButton')
if self.check_winner():
messagebox.showinfo("Game Over", "You win!")
self.reset_game()
elif self.is_board_full():
messagebox.showinfo("Game Over", "It's a draw!")
self.reset_game()
else:
self.current_player = 'O'
self.ai_move()
def ai_move(self):
if self.current_player == 'O':
if self.difficulty_level == 'easy':
empty_cells = [(i, j) for i in range(3) for j in range(3) if
self.board[i][j] == ' ']
row, col = random.choice(empty_cells)
else: # Use Minimax for medium and hard difficulty levels
row, col = self.get_best_move()
self.board[row][col] = 'O'
self.buttons[row][col]['text'] = 'O'
self.buttons[row][col].configure(style='PlayerO.TButton')
if self.check_winner():
messagebox.showinfo("Game Over", "AI wins!")
self.reset_game()
elif self.is_board_full():
messagebox.showinfo("Game Over", "It's a draw!")
self.reset_game()
else:
self.current_player = 'X'
def get_best_move(self):
best_move = None
best_eval = float('-inf') if self.current_player == 'O' else float('inf')
for i in range(3):
for j in range(3):
if self.board[i][j] == ' ':
self.board[i][j] = 'O' if self.current_player == 'O' else
'X'
eval = self.minimax(0, False) if self.current_player == 'O'
else self.minimax(0, True)
self.board[i][j] = ' '
7|Page
best_eval = eval
best_move = (i, j)
return best_move
if maximizing_player:
max_eval = float('-inf')
for i in range(3):
for j in range(3):
if self.board[i][j] == ' ':
self.board[i][j] = 'O'
eval = self.minimax(depth + 1, False)
self.board[i][j] = ' '
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = float('inf')
for i in range(3):
for j in range(3):
if self.board[i][j] == ' ':
self.board[i][j] = 'X'
eval = self.minimax(depth + 1, True)
self.board[i][j] = ' '
min_eval = min(min_eval, eval)
return min_eval
def check_winner(self):
for i in range(3):
if all(self.board[i][j] == self.current_player for j in range(3))
or \
all(self.board[j][i] == self.current_player for j in range(3)):
return True
if all(self.board[i][i] == self.current_player for i in range(3)) or \
all(self.board[i][2 - i] == self.current_player for i in range(3)):
return True
return False
def is_board_full(self):
return all(self.board[i][j] != ' ' for i in range(3) for j in range(3))
8|Page
def reset_game(self):
for i in range(3):
for j in range(3):
self.board[i][j] = ' '
self.buttons[i][j]['text'] = ' '
self.buttons[i][j].configure(style='Square.TButton')
self.current_player = 'X' if self.difficulty_level == 'easy' else 'O'
if __name__ == "__main__":
difficulty_level = input("Choose difficulty level (easy, medium, hard):
").lower()
if difficulty_level not in ['easy', 'medium', 'hard']:
print("Invalid difficulty level. Defaulting to easy.")
difficulty_level = 'easy'
gui = TicTacToeGUI(difficulty_level)
gui.root.mainloop()
outcomes:
9|Page
10 | P a g e
Conclusion:
Ultimately, the incorporation of a Minimax AI into the Tic Tac Toe game has
yielded a captivating and astute gaming encounter. The Minimax algorithm is a
fundamental tool for constructing intelligent AI players in diverse games. Despite
facing obstacles during the creation process, the outcome is a fully operational
and engaging game that effectively demonstrates the capabilities of AI in the
gaming industry. Possible additions could include incorporating supplementary
functionalities such as varying levels of difficulty, augmenting the visual aspects,
and improving the overall user experience.
11 | P a g e