Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

IMPLEMENTATION OF MINIMAX ALGORITHM

INTRODUCTION TO ARTIFICIAL INTELLIGENCE COURSE REPORT


submitted by

( 5) ADITHYA BIJU
( 6) ADITHYAN A J
(30) E R ARAVIND NAMPOOTHIRI
(34) HARIKRISHNAN P
(35) HENRY B PHILIP

S5 CSE(AI)

Under the guidance of

PROF. ASHA ROSE THOMAS

To

APJ Abdul Kalam Technological University


in partial fulfillment of the requirements for the award of the
Degree of
Bachelor of Technology In Computer Science and Engineering (AI)

DEPARTMENT OF CSE(AI)

ADI SHANKARA INSTITUTE OF ENGINEERING AND


TECHNOLOGY KALADY
JANUARY 2023
Implementation of Minimax algorithm January 2023

ABSTRACT

The minimax algorithm is used to solve adversial search problems in


which goals of agents are in conflict, this is the case for most games.
In a game with two players, the algorithm assumes that one player
wants to maximize (MAX) the score and that the other player wants to
minimize (MIN) the score. The algorithm can be extended to include
more than two players.

The minimax algorithm evaluates all possible plays from the current
game state down to the end of each game and then backs up the values
to the current state. The algorithm assumes that both players’ plays
optimal, the MAX player will chose the play with the highest score
and the MIN player will chose the play with the lowest score.

Department of Computer Science and Engineering (AI), ASIET Page 1


Implementation of Minimax algorithm January 2023

CONTENTS

SI NO. Title Page No


1 Introduction 3
2 Pseudo Code 4
3 Working 5
4 Game Tree 7
5 Source Code 8
6 Output 15
7 Conclusion 18
8 References 19

Department of Computer Science and Engineering (AI), ASIET Page 2


Implementation of Minimax algorithm January 2023

INTRODUCTION

Minimax is a artificial intelligence applied in two player games, such


as knoughts & crosses, checkers, chess and go. This games are known
as zero-sum games, because in a mathematical representation: one
player wins (+1) and other player loses (-1) or both of anyone not to
win (0).

We will present the idea of a game tree followed by the minimax


method to solve games using AI. The game's many states are
represented by nodes in the game tree, which is quite similar to the
planning issues mentioned above. Just little different is the concept.
The nodes in the game tree are placed in levels that represent each
player's turns in the game, with the "root" node representing the
starting position. This would be the blank grid in knoughts & crosses
that hasn't yet had any Xs or Os played. The alternative states that
could result from the first player's moves, whether they be X or O, are
listed under root on the second level.

In knoughts & crosses, this means that either one of the players gets a
line of three and wins, or the board is full and the game ends in a tie.

Department of Computer Science and Engineering (AI), ASIET Page 3


Implementation of Minimax algorithm January 2023

PSEUDO CODE

def minimax(state, depth, player):


if player == MAX:
best = [-1, -1, -infinity]
else:
best = [-1, -1, +infinity]

if depth == 0 or game_over(state):
score = evaluate(state)
return [-1, -1, score]

for cell in empty_cells(state):


x, y = cell[0], cell[1]
state[x][y] = player
score = minimax(state, depth - 1, -player)
state[x][y] = 0
score[0], score[1] = x, y

if player == MAX:
if score[2] > best[2]:
best = score
else:
if score[2] < best[2]:
best = score

return best

Department of Computer Science and Engineering (AI), ASIET Page 4


Implementation of Minimax algorithm January 2023

WORKING

The algorithm search, recursively, the best move that leads


the Max player to win or not lose (draw). It consider the current state
of the game and the available moves at that state, then for each valid
move it plays (alternating min and max) until it finds a terminal state
(win, draw or lose).
The MAX may be X or O and the MIN may be O or X, whatever. The
board is 3x3.

 state: the current board in tic-tac-toe (node)


 depth: index of the node in the game tree
 player: may be a MAX player or MIN player

Both players start with your worst score. If player is MAX, its score is
-inf. Else if player is MIN, its score is +inf.
The best move on the board is [-1, -1] (row and column) for all.
If the depth is equal zero, then the board hasn't new empty cells to
play. Or, if a player wins, then the game ended for MAX or MIN. So
the score for that state will be returned.

 If MAX won: return +1


 If MIN won: return -1

 Else: return 0 (draw)


For each valid moves (empty cells):

 x: receives cell row index


 y: receives cell column index
 state[x][y]: it's like board[available_row][available_col]
receives MAX or MIN player

Department of Computer Science and Engineering (AI), ASIET Page 5


Implementation of Minimax algorithm January 2023

 score = minimax(state, depth - 1, -player):


o state: is the current board in recursion;

o depth -1: index of the next state;

o -player: if a player is MAX (+1) will be MIN (-1) and vice


versa.

The move (+1 or -1) on the board is undo and the row, column are
collected.
For MAX player, a bigger score will be received. For a MIN player, a
lower score will be received. And in the end, the best move is
returned.

Department of Computer Science and Engineering (AI), ASIET Page 6


Implementation of Minimax algorithm January 2023

GAME TREE

Department of Computer Science and Engineering (AI), ASIET Page 7


Implementation of Minimax algorithm January 2023

SOURCE CODE

from math import inf


from random import choice
import platform
import time
from os import system
user = -1
ai = +1
board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
]

# function for heuristic evaluation of state

def evaluate(state):
if wins(state, ai):
score = +1
elif wins(state, user):
score = -1
else:
score = 0
return score

# function for testing if a specific player wins or not

def wins(state, player):


win_state = [
[state[0][0], state[0][1], state[0][2]],
[state[1][0], state[1][1], state[1][2]],
[state[2][0], state[2][1], state[2][2]],
[state[0][0], state[1][0], state[2][0]],
[state[0][1], state[1][1], state[2][1]],
Department of Computer Science and Engineering (AI), ASIET Page 8
Implementation of Minimax algorithm January 2023

[state[0][2], state[1][2], state[2][2]],


[state[0][0], state[1][1], state[2][2]],
[state[2][0], state[1][1], state[0][2]],
]
if [player, player, player] in win_state:
return True
else:
return False

# function for testing if the winner is the user or AI

def game_over(state):
return wins(state, user) or wins(state, ai)

# function for adding each empty cell into a list 'cells'

def empty_cells(state):
cells = []
for x, row in enumerate(state):
for y, cell in enumerate(row):
if cell == 0: cells.append([x, y])
return cells

# function to check if a move is valid (chosen cell is empty) or not

def valid_move(x, y):


if [x, y] in empty_cells(board):
return True
else:
return False

Department of Computer Science and Engineering (AI), ASIET Page 9


Implementation of Minimax algorithm January 2023

# function for execution of a valid move

def set_move(x, y, player):


if valid_move(x, y):
board[x][y] = player
return True
else:
return False

# function to choose the best move using minimax algorithm

def minimax(state, depth, player):


if player == ai:
best = [-1, -1, -inf]
else:
best = [-1, -1, +inf]
if depth == 0 or game_over(state):
score = evaluate(state)
return [-1, -1, score]
for cell in empty_cells(state):
x, y = cell[0], cell[1]
state[x][y] = player
score = minimax(state, depth - 1, -player)
state[x][y] = 0
score[0], score[1] = x, y
if player == ai:
if score[2] > best[2]:
best = score # max value
else:
if score[2] < best[2]:
best = score # min value
return best

Department of Computer Science and Engineering (AI), ASIET Page 10


Implementation of Minimax algorithm January 2023

def clean():
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')

# function for display

def render(state, ai_choice, user_choice):


print('----------------')
for row in state:
print('\n----------------')
for cell in row:
if cell == +1:
print('|', ai_choice, '|', end = '')
elif cell == -1:
print('|', user_choice, '|', end = '')
else:
print('|', ' ', '|', end = '')
print('\n----------------')

# functiom for ai's turn

def ai_turn(ai_choice, user_choice):


depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return
clean()
print('Computer turn [{}]'.format(ai_choice))
render(board, ai_choice, user_choice)
if depth == 9:
x = choice([0, 1, 2])
y = choice([0, 1, 2])

Department of Computer Science and Engineering (AI), ASIET Page 11


Implementation of Minimax algorithm January 2023

else:
move = minimax(board, depth, ai)
x, y = move[0], move[1]
set_move(x, y, ai)
time.sleep(1)

def user_turn(ai_choice, user_choice):


depth = len(empty_cells(board))
if depth == 0 or game_over(board):
return
move = -1
moves = {
1: [0, 0], 2: [0, 1], 3: [0, 2],
4: [1, 0], 5: [1, 1], 6: [1, 2],
7: [2, 0], 8: [2, 1], 9: [2, 2],
} # Dictionary of valid moves
clean()
print('User turn [{}]'.format(user_choice))
render(board, ai_choice, user_choice)
while (move < 1 or move > 9):
try:
move = int(input('Use numpad (1..9): '))
coord = moves[move]
try_move = set_move(coord[0], coord[1], user)
if try_move == False:
print('Bad move')
move = -1
except KeyboardInterrupt:
print('Bye')
exit()
except:
print('Bad choice')

Department of Computer Science and Engineering (AI), ASIET Page 12


Implementation of Minimax algorithm January 2023

def main():
clean()
user_choice = ''
ai_choice = ''
first = ''

# User chooses X or O to play

while user_choice != 'O' and user_choice != 'X':


try:
user_choice = input('\nChoose X or O\nChosen: ').upper()
except KeyboardInterrupt:
print('Bye!')
exit()
except:
print('Invalid choice!')

# Setting computer's choice


if user_choice == 'X':
ai_choice = 'O'
else:
ai_choice = 'X'

# User may start first


clean()
while first != 'Y' and first != 'N':
try:
first = input('Do you wish to start first? [y/n] : ').upper()
except KeyboardInterrupt:
print('Bye!')
exit()
except:
print('Invalid choice!')

Department of Computer Science and Engineering (AI), ASIET Page 13


Implementation of Minimax algorithm January 2023

while len(empty_cells(board)) > 0 and not game_over(board):


if first == 'N':
ai_turn(ai_choice, user_choice)
first = ''
user_turn(ai_choice, user_choice)
ai_turn(ai_choice, user_choice)

# Game over message


if wins(board, user):
clean()
print('Human turn [{}]'.format(user_choice))
render(board, ai_choice, user_choice)
print('YOU WIN!')

elif wins(board, ai):


clean()
print('Computer turn [{}]'.format(ai_choice))
render(board, ai_choice, user_choice)
print('YOU LOSE!')

else:
clean()
render(board, ai_choice, user_choice)
print('DRAW!')

exit()

main()

Department of Computer Science and Engineering (AI), ASIET Page 14


Implementation of Minimax algorithm January 2023

OUTPUT

Choose X or O
Chosen: X
Do you wish to start first? [y/n] : Y
User turn [X]
----------------

----------------
| || || |
----------------
| || || |
----------------
| || || |
----------------
Use numpad (1..9): 1
Computer turn [O]
----------------

----------------
| X || || |
----------------
| || || |
----------------
| || || |
----------------
User turn [X]
----------------

----------------
| X || || |
----------------
| || O || |
----------------
| || || |
----------------
Use numpad (1..9): 4

Department of Computer Science and Engineering (AI), ASIET Page 15


Implementation of Minimax algorithm January 2023

Computer turn [O]


----------------

----------------
| X || || |
----------------
| X || O || |
----------------
| || || |
----------------
User turn [X]
----------------

----------------
| X || || |
----------------
| X || O || |
----------------
| O || || |
----------------
Use numpad (1..9): 3
Computer turn [O]
----------------

----------------
| X || || X |
----------------
| X || O || |
----------------
| O || || |
----------------
User turn [X]
----------------

----------------
| X || O || X |
----------------
| X || O || |
----------------
| O || || |
----------------
Use numpad (1..9): 8
Department of Computer Science and Engineering (AI), ASIET Page 16
Implementation of Minimax algorithm January 2023

Computer turn [O]


----------------

----------------
| X || O || X |
----------------
| X || O || |
----------------
| O || X || |
----------------
User turn [X]
----------------

----------------
| X || O || X |
----------------
| X || O || O |
----------------
| O || X || |
----------------
Use numpad (1..9): 9
----------------

----------------
| X || O || X |
----------------
| X || O || O |
----------------
| O || X || X |
----------------
DRAW!

Department of Computer Science and Engineering (AI), ASIET Page 17


Implementation of Minimax algorithm January 2023

CONCLUSION

Minimax is a decision rule used in decision theory, game theory,


statistics and philosophy for minimizing the possible loss for a worst
case (maximum loss) scenario.
The above program shows a sample game of knoughts & crosses
played using the minimax algorithm.

Department of Computer Science and Engineering (AI), ASIET Page 18


Implementation of Minimax algorithm January 2023

REFERENCES

 Clederson Cruz
Clederson Cruz (cledersonbc.github.io)

 George T. Heineman; Gary Pollice; Stanley Selkow. Algorithms


in a nutshell. O'Reilly, 2009.

 Minimax Algorithm and Tic-Tac-Toe – Vinay Kumar Papsula


https://open.substack.com/pub/vinaypaspula/p/minimax-
algorithm-and-tic-tac-toe-
131ae26d2bf2?utm_campaign=post&utm_medium=web

Department of Computer Science and Engineering (AI), ASIET Page 19

You might also like