Tik Tak Toe AI GAME Documentation
Tik Tak Toe AI GAME 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
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.
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).
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 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
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.
board=["-","-","-",
"-","-","-",
"-","-","-"]
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=[]
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
## 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
## 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
if [plr,plr,plr] in win:
return 1
else:
return 0
def gameOver(st):
def human_turn(board):
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
clean()
print("Humans Turn :")
show_Board()
print("\n")
print("\n")
try:
choice=int(input())
## We will not enter into the loop if move >9 and move<1
if board[choice-1]=='-':
## we are decrementing the posotion by 1 to make it 0 for 1 and so on
choice-=1
board[choice]='O'
print("Human placed 'O' at",choice+1)
show_Board()
return
else:
print("\n")
choice=-1
else:
print("Bad Move")
print("\n")
move=-1
except:
## If a player wins that one gets 1 point and the oponent loses that point
def eva(st):
if winner(st,'X'):
score=+1
elif winner(st,'O'):
score=-1
else:
score=0
return score
# Here is the Minimax Algorithm That takes board, depth and player as a
parameter
def minimax(board,depth,plr):
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]
if depth==0 or gameOver(board):
score=eva(board)
return [-1,score]
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')
else:
score=minimax(board,depth-1,'X')
board[loc]='-'
score[0]=loc
# If it is the O's Turn than if the current score is greater than the best move
if plr=='X':
if best[1]<score[1]:
best=score
else:
# This Will check if the current score is less than the best move
if best[1]>score[1]:
best=score
return best
def compMove():
# the board
depth = len(isSpaceAvailable(board))
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')
board[move[0]]='X'
show_Board()
def clean():
system('cls')
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
print("\n")
compMove()
print("-------------------------This is Your
Turn------------------------------------------------")
print("\n")
human_turn(board)
if winner(board,'O'):
print("Human Won!!!!")
print("\n")
return 0
elif winner(board,'X'):
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("\n")
print("-----------------------------Intelligent AI AGent is
playing--------------------------")
print("\n")
print("\n")
maximizer effects.
l=0
choice = input("!!!!!!!!Want to play!!!!!!!?[y/n]:\n")
print("\n")
if (l >= 1):
print("\n")
if choice=="n"or choice=="N":
break
playGame(board)
board=["-","-","-"
,"-","-","-",
"-","-","-"]
l+=1
if choice=="n" or choice=="N":
break