0% found this document useful (0 votes)
124 views

Tik Tak Toe AI GAME Documentation

The document describes the Minimax algorithm, a backtracking algorithm used in game theory to select the optimal move for a player by assuming the other player will also play optimally. It works by having one player act as the maximizer, trying to maximize their score, and the other act as the minimizer, trying to minimize the maximizer's score. The algorithm involves building a game tree, evaluating leaf nodes, and propagating scores back up the tree from the perspective of each player. It is commonly used for turn-based games like Tic-Tac-Toe and Chess. Pseudocode is provided to illustrate how the algorithm traverses the tree and selects moves. Limitations include slow performance for complex games and potential improvements using

Uploaded by

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

Tik Tak Toe AI GAME Documentation

The document describes the Minimax algorithm, a backtracking algorithm used in game theory to select the optimal move for a player by assuming the other player will also play optimally. It works by having one player act as the maximizer, trying to maximize their score, and the other act as the minimizer, trying to minimize the maximizer's score. The algorithm involves building a game tree, evaluating leaf nodes, and propagating scores back up the tree from the perspective of each player. It is commonly used for turn-based games like Tic-Tac-Toe and Chess. Pseudocode is provided to illustrate how the algorithm traverses the tree and selects moves. Limitations include slow performance for complex games and potential improvements using

Uploaded by

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

Documentation

Artificial intelligence

SUBMITTED BY
SYED SHEHAR YAR RAZA SHAH
0004_BSCS_2017_2021
SECTION A

Submitted to
Sir Ali Raza Shah

GC UNIVERSITY LAHORE

Computer Science DEPARTMENT

Minimax Algorithm: -
A backtracking algorithm that can be used for decisions. It can
also be used for the game theory to select the most suitable move for the player by
assuming that another player will also have to play optimally. It is basically used in
games where 2 players can play 1 is max and other one is min. some of the games
in which minimax can be used are e.g. Tic-Tac-Toe, Chess etc.
The names that can be used for those 2 players are maximizer
and minimizer. The maximizer by the name shows that it always tries to get the
highest score, and minimizer on the other hand will try to reduce its effect and tries
to get the lowest possible score. Every board has a state and it is associated with a
value. If in each state, the hand of the maximizer is high then it must have assigned
some positive value. If the minimizer is in a better position (has higher hand), then
it will have some negative value. If the game is in a tie state, such a state in which
neither maximizer has upper hand nor minimizer has upper hand has given 0 value.
The board values can be calculated by some heuristics that are unique for every
type of game.

Pseudo code for minimax: -


minimax (node, depth, maxplayer)
If depth==0 or node ==terminal node
Return static evaluation of node
If maxplayer then
Max-evaluation= -infinity
For every child of the node
Evaluation= minimax (child, depth-1, False)
Max-evaluation= max (Max-evaluation, evaluation)
Return (Max-evaluation)

Else
Min-evaluation= +infinity
For every child of the node
Evaluation= minimax (child, depth-1, True)
Min-Evaluation= min (Min-evaluation, evaluation)
Return (Min-evaluation)

Working: -
Our first and primary goal is to find the optimal move for the player.
For that purpose, we can select the node that has best evaluation score. For the
smarter move, we adopt a policy of look ahead and evaluate the opponent potential
moves.
For every move, we look ahead as many moves as possible. This
algorithm assumes that the opponent will also play optimally.
First, we select the root node upper node and then choose the best possible move.
We calculate the scores of theses nodes based on their evaluation scores. In our
case, evaluation function can only assign scores to the leaves. Therefor, we reach
leaves with scores recursively, and then back propagate those scores.

Maximizer firstly starts from the root node and then chooses the move that has the
best score. But there is a bit of bad luck that only the leaves have the evaluation
scores with them, hence by following the algorithm we must reach that leaf nodes
recursively. By looking at the given game tree it is the maximizer turn to take a
move from the leaf node, so the nodes which have minimum scores are selected
node 3 and node 4. it tries to pick best moves similarly, until it reaches the root
node.
Now, formally look at the steps followed by this algorithm: -
 Builds the game tree completely.
 Look at the scores of leaves that are evaluated by using the
evaluation function.
 Return scores from leaf to root by considering the type of player.
 Max player will take that child that has maximum
score.
 Min player will select that child that has minimum
score.
 Select the node with maximum value at the root node and then
performs corresponding moves.
Properties of the minimax algorithm: -
 It is complete, it will surely find a solution in the finite search
tree.
 This algorithm is optimal if players play optimally.
 The time complexity of this algorithm is O (b^m) because it
uses DFS for the game tree where b is the branching factor and
m is the maximum depth of the tree.
 Space complexity of this algorithm is also similar to the DFS
which is O (bm).

Limitations of the Minimax algorithm: -


One of its main draw backs is that it gets really slow for the complex
games such as Chess etc. There is a huge branching factor for this kind of games,
and lot of choices exists for a player to decide. Minimax algorithm can be
improved by alpha-beta pruning.

Conclusion: -
It is one of the most popular algorithms for computer board games. It
can be widely used in turn-based games. It is a good choice if the players have the
complete information about the game. It might not be good for the games which
have huge branching factors. Nonetheless, given a proper implementation, it can be
a smart AI.
Tic-Tac-Toe: -
Tic tac toe is a simple game with only 255,168 possible games that a player
can play. It is a trivial number for todays computers that is why it is considered to
be solved game. It means that the outcome can be predicted given any state.it is so
simple game that we can generate the entire game tree without any trouble in
comparison to chess where are 69,352,859,712,417 possible games that can be
possibly played after just 10 moves.
X O X’s turn for maximizing
O O
X X

X X O O’s turn to minimizing


X O O O
O O X O X X
X X X O O X
+1 X X
X’s turn +0
-1

X X O X X O
O O O O O
X X X O X

X O O -1 X O
O O X O O X
+0
X X X O X
O’s turn
+1 +0

X X O
O O X
X X X
X O O X X O
O O X +0
O O X
X X X X O X
+1 +0

Tic-Tac-Toe we can also call it as noughts and crosses or X’s


and O’s. It is paper and pencil game in which two players can participate. X and O
who take the turn try to make 3 X’s on a row, column, diagonal or 3 O’s on a row
row, column, diagonal to win the game. Technically, speaking Tic-Tac-Toe is zero
sum game which means that each participant gain is equal to the other participant
losses. If two players X and O play and if player X got +1 point, then player Y will
surely lose 1 point. So, total gain/losses sum is equal to zero.
Consider the following example in which X wins the game.

X
O X

O X O X
O
X X
Return BestMove
O X O X O X
AI agent always tries to O X O X O X look for
the best move considering X X X O X X O X that its
opponent also plays optimally
and sensibly.

At the End Code


from math import inf

from os import system


import random

## This is used for Declaring the Board


#At first we declare a board list with 9 empty spaces
# So we can make 9! possible moves
# when one player chooses its turn then 8 empty spaces will be there
#after that when the oponent player chooses its turn than 7 empty places will be
left
# this process proceeds untill there is no empty space left or there is no winner

board=["-","-","-",
"-","-","-",
"-","-","-"]

## This is how we can show the board starting from 0-8


## There are total 9 positions in it

def show_Board():
print("-------------------Displaying Game Board--------------------------")

print("\n")

print("->",board[0] + " | " +"->", board[1] + " | " +"->", board[2] + " | " +
"\n" +
"->",board[3] + " | " + "->",board[4] + " | " + "->",board[5] + " | " +
"\n" +
"->",board[6] + " | " + "->",board[7] + " | " + "->",board[8] + " | " +
"\n")

print("\n")

## Here we are checking that if the space is available or not to insert the next
move
def isSpaceAvailable(board):

l=[]

## enumerate function will return idices as well as value

for i,j in enumerate(board):

## it checks if the value is not inserted

if j=='-':
l.append(i)

return l

## Below some of the states are defined through which a fate of the game can be
decided

## There is a win in row 1 taht is 0,1,2, also there is a win in row 2 that is 3,4,5,
similary there

##is a win in row 3 that is 6,7,8

## There is a win in column 1 taht is 0,3,6 also there is a win in column 2 that is
1,4,7, similary there

##is a win in column 3 that is 2,5,8

## For diagonals there is going to be win in 0,4,8 positions and 2,4,6 positions as
well

def winner(st,plr):
win=[

#Row 1

[st[0],st[1],st[2]],

#Row 2

[st[3],st[4],st[5]],

#Row 3

[st[6],st[7],st[8]],

# Column 1

[st[0],st[3],st[6]],

#Column 2

[st[1],st[4],st[7]],

# Column 3

[st[2],st[5],st[8]],

# Diagonal 1

[st[0],st[4],st[8]],

#Diagonal 2

[st[2],st[4],st[6]]
]
"""" This condition is used to check if three same letters

in a row, column or diagonal and it will return true if

three same letters matches in a row,column or diadonal,

otherwise it will return false"""

if [plr,plr,plr] in win:

return 1
else:

return 0

def gameOver(st):

## it will check if there is a winner or not by calling another function winner

return winner(st,'X') or winner(st,'O')

## this function will decide the humans turn what he is going to do

def human_turn(board):

## depth will give that length of the board that is available


## for inserting the move
## we will also check if it is a terminal state or not
## if terminal state than we will just return and print the result

depth=len(isSpaceAvailable(board))

if depth==0 or gameOver(board):
return

move=-1

## This loop will work untill move is less than 9 but greater than 1

while move<1 or move>9:

clean()
print("Humans Turn :")
show_Board()

print("----------------------This is Your Turn---------------------------")

print("\n")

print("Please Enter position from 1-9:")

print("\n")

## conveting a string to int number

try:
choice=int(input())

## We will not enter into the loop if move >9 and move<1

if choice<=9 and choice>=1:

## we enter a position-1 into the board because we are counting

## positions from 0-8 that in turn equal to 1-9

if board[choice-1]=='-':
## we are decrementing the posotion by 1 to make it 0 for 1 and so on

choice-=1

## We are inserting X in the board

board[choice]='O'
print("Human placed 'O' at",choice+1)

## We Are displaying the board

show_Board()
return
else:

## If user enters a letter into a position that is already occupied then


## We wil show this message

print("This position is not available dude!!!")

print("\n")
choice=-1
else:

## if user enters greater than 9 and less than 1


## We print a message in which we will indicate that its a bad move

print("Bad Move")

print("\n")
move=-1
except:

print("You must have to enter a number")


print("\n")

## Evaluation Function is defined here

## If there is a win By O then score is +1

## If X wins the game than score is -1

## And if the game is drawn than there is score of 0

## From this function it is clear that it is a zero sum game

## If a player wins that one gets 1 point and the oponent loses that point

## So the sum will become zero

## And if the game is tie than also there is a score of 0

def eva(st):

## It will check if there is O winner So score is +1

if winner(st,'X'):

score=+1

# This will check if the game is won by X So the score is -1

elif winner(st,'O'):

score=-1

# This is the condition for a Tie Game

else:
score=0

return score

# Here is the Minimax Algorithm That takes board, depth and player as a
parameter

def minimax(board,depth,plr):

# This Condition checks Whether the Current turn is of player O


# So giving the worst possible value to the maximizer
# So that later that value can be easily increased

if plr=='X':

best=[-1,-inf]

# This Else is for the minimizer So also we gave a worst possible value
# to the minimizer

else:

best=[-1,inf]

# This condition will check if it is a termianl state


# if terminal state than return the score

if depth==0 or gameOver(board):

score=eva(board)
return [-1,score]

# If not terminal state than allowing a player to place its move


# in a available space of the board
for loc in isSpaceAvailable(board):

board[loc]=plr

# This will check if the player is O so recursive call for minimax is done here
# And it will return the max score of the minimax recursive call

if plr=='X':
score=minimax(board,depth-1,'O')

# iT will return Recursive call for that minimax algorithm


# and will give min of score of minimax recursive call

else:

score=minimax(board,depth-1,'X')

board[loc]='-'
score[0]=loc

# it will check if its O's Turn or not

# If it is the O's Turn than if the current score is greater than the best move

# than we will assign that score to that best move

# Because it is the maximizer turn

if plr=='X':

if best[1]<score[1]:
best=score
else:
# This Will check if the current score is less than the best move

# it will assign that score to the best move

# because it is the minimizer turn

if best[1]>score[1]:
best=score
return best

# This Function is specially designed for the AI agent move

def compMove():

# Depth is variable that will hold the length

# it will hold the length of available spots of

# the board

depth = len(isSpaceAvailable(board))

# It will check if it a terminal node

# if terminal node than we will return

if depth == 0 or gameOver(board):
return

clean()

print("Computer turn:")
# for the computer turn we will cal the minimax function
# so that computer move can work optimally
# and it will choose the best move

move=minimax(board,depth,'X')

# inserting O into the Board

board[move[0]]='X'

print("Computer places 'X' at",move[0]+1)

# displaying the board after inserting

show_Board()

# This Function will clean the board

def clean():

system('cls')

# we Are defining the main function

def playGame(board):
# This condition will check if the depth is greater than 9
# and also that game is not over
# game over when a player won or there are no space left on the board

while len(isSpaceAvailable(board))>0 and not gameOver(board):

# This a placing computer the first move

print("-------------------At First Our Maximizer (Computer) is going to


choose the move-------------------------------")

print("\n")

compMove()

# After computer there is a turn of the human

print("-------------------------This is Your
Turn------------------------------------------------")

print("\n")

human_turn(board)

# This condition checks if player X has Won


# if Player X has won Then it will oprint a message showing that
# Human Has Won the Game

if winner(board,'O'):

print("--------------------Game has ended--------------------")

print("Human Won!!!!")
print("\n")
return 0

# This Condition is used for checking that If there is a winner in O


# If O has Won the game than it will print a message showing that computer has
won

elif winner(board,'X'):

print("--------------------------Game has ended--------------------")

print("Computer Won!!!!!")

print("\n")
return 0
else:

# if wo found no winner in X
# nor in O then
# It will surely be a draw match

print("Draw")

print("\n")

return 0

while(playGame):

print("-----------------------------Welcome to the Tic Tac Toe


Game-------------------------")

print("\n")

print("-----------------------------Intelligent AI AGent is
playing--------------------------")

print("\n")

print("-----------------------------If you have the courage than beat


him------------------------")

print("\n")

""" Tic tac toe is a 2 player game

in which one player is maximizer and the other is minimizer

maximizer will try to take the maximum value

on the other hand minimizer will try to reduce the

maximizer effects.

In it terminal state occurs if same letters found in the same row,

column or diagonal and also if none of these condition occurs

than it will be a tie


"""

l=0
choice = input("!!!!!!!!Want to play!!!!!!!?[y/n]:\n")
print("\n")

while (choice=="y"or choice=="Y"):

if (l >= 1):

print("You want to play again????")


print("\n")

choice=(input("Please Enter your choice!!!!"))

print("\n")
if choice=="n"or choice=="N":
break

playGame(board)

board=["-","-","-"
,"-","-","-",
"-","-","-"]

# If you want to continue or not


# If you want game to be continued than press Y
# else if you press n then the game will end

l+=1

if choice=="n" or choice=="N":

break

You might also like