0% found this document useful (0 votes)
45 views11 pages

CSE3664 - ProjectReport - Tic Tac Toe Game With AI Player

This document details the steps to create a Tic Tac Toe game with an AI player using the Minimax algorithm. It describes initializing the game board, displaying it, verifying wins/draws, and implementing the AI to make strategic moves by evaluating all possible game states. Challenges in developing the Minimax logic and integrating the AI into a user interface are also outlined.

Uploaded by

nadiapatowarry
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views11 pages

CSE3664 - ProjectReport - Tic Tac Toe Game With AI Player

This document details the steps to create a Tic Tac Toe game with an AI player using the Minimax algorithm. It describes initializing the game board, displaying it, verifying wins/draws, and implementing the AI to make strategic moves by evaluating all possible game states. Challenges in developing the Minimax logic and integrating the AI into a user interface are also outlined.

Uploaded by

nadiapatowarry
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Department of Computer Science and Engineering

Project Report - Tic Tac Toe Game with AI Player

Course Title: Artificial Intelligence


Course Code: CSE366
Section: 04

Submitted To:
Amit Mandal

Lecturer, Department of Computer Science and Engineering

East West University

Submitted By:

Nadia Sultana 2020-2-60-024


Farhana Moni 2020-2-60-036
Sheikh Reshma Sultana 2020-1-60-140
Nasrin Sultana Sonia 2019-1-60-248

Submission Date: 28th December 2023

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.

Ability to execute strategic manoeuvres in order to compete against a human


adversary.

AI Algorithm: Minimax

The Minimax algorithm is a decision-making technique employed in two-player


games to ascertain the optimal move for a player. It is frequently utilized in games
such as chess, tic-tac-toe, and checkers, where the two player’s alternate making
moves, with the goal of maximizing one's probability of winning while
decreasing the opponent's possibilities.

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.

Evaluation Function: An evaluation function, also known as a utility function


or heuristic function, is employed to assess the quality of a game state. The
purpose of this function is to assign a numerical value to each terminal condition,
reflecting the level of desirability for the player. In games such as tic-tac-toe, the
evaluation function can assign specific values, such as +1 for a victory, -1 for a
defeat, and 0 for a tie.

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.

Alpha-Beta Pruning: The Minimax algorithm can need a significant amount of


computer resources when dealing with game trees that have a large depth. In order
to enhance efficiency, the method can integrate alpha-beta pruning. Alpha-beta
pruning is an algorithmic technique used to eliminate unnecessary branches in a
tree, which do not have any impact on the final conclusion. This decreases the
quantity of nodes that the algorithm must assess, resulting in a significant increase
in speed.

Depth-Limited Search: In practical scenarios, the game tree is frequently


restricted to a specific depth as a result of processing limitations. This indicates
that the algorithm does not examine every potential move until the game is
completed, but instead terminates after a predetermined amount of future steps.

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).

Displaying the Game Board:


 A feature was created to showcase the game board on the console.
Winning condition verification:
 Functions were implemented to verify if there is a win by analyzing rows,
columns, and diagonals.
Detecting a Draw:
 A function was created to identify a draw when all cells are filled.
AI Move:
 The AI has been equipped with the Minimax algorithm to facilitate
strategic decision-making.
 The program assesses all potential movements using recursive analysis and
chooses the optimal move to maximize its probability of winning.
Main Game Loop:
 The primary game loop was implemented to manage the sequential
execution of player and AI moves.
 The program verifies victory conditions, draws, and validates player
moves.

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.

Code and outcomes:

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")

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


self.current_player = 'X'
self.difficulty_level = difficulty_level

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)

self.buttons = [[ttk.Button(self.root, text=' ', style='Square.TButton',


command=lambda row=i, col=j:
self.make_move(row, col))
for j in range(3)] for i in range(3)]

for i in range(3):
for j in range(3):
self.buttons[i][j].grid(row=i, column=j)

def make_move(self, row, col):


if self.board[row][col] == ' ' and self.current_player == 'X':
self.board[row][col] = 'X'
self.buttons[row][col]['text'] = 'X'

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] = ' '

if (self.current_player == 'O' and eval > best_eval) or \


(self.current_player == 'X' and eval < best_eval):

7|Page
best_eval = eval
best_move = (i, j)

return best_move

def minimax(self, depth, maximizing_player):


if self.check_winner() and maximizing_player:
return -1
elif self.check_winner() and not maximizing_player:
return 1
elif self.is_board_full():
return 0

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

You might also like