Minmax Algorithm
Minmax Algorithm
Name : sivamurugan.B
Minmax Algorithm
Program:
def game_over(state):
return wins(state,hum) or wins(state, comp)
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
pg. 1
def valid_move(x,y):
if [x,y] in empty_cells(board):
return True
else:
return False
def set_move(x,y,player):
if valid_move(x,y):
board[x][y] = player
return True
else:
return False
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 == comp:
if score[2]>best[2]:
best = score
else:
if score[2]<best[2]:
best = score
return best
def clean():
os_name = platform.system().lower()
if 'windows' in os_name:
system('cls')
else:
system('clear')
def render(state,c_choice,h_choice):
chars = {
-1:h_choice,
+1:c_choice,
0:''
}
str_line = '--------------'
print('\n'+str_line)
for row in state:
for cell in row:
symbol = chars[cell]
print(f'| {symbol} |',end = '')
print('\n'+str_line)
pg. 2
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)
if depth==9:
x = choice([0,1,2])
y = choice([0,1,2])
else:
move = minimax(board, depth, comp)
x,y = move[0], move[1]
set_move(x,y,comp)
time.sleep(1)
clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)
if not can_move:
print('Bad move')
move=-1
except (EOFError, KeyboardInterrupt):
print('Bye')
exit()
except(KeyError, ValueError):
print("Bad choice")
def main():
clean()
h_choice = ''
c_choice = ''
first = ''
except(KeyError, ValueError):
print('Bad choice')
if h_choice == 'X':
c_choice = 'O'
else:
c_choice = 'X'
pg. 3
clean()
while first != 'Y' and first != 'N':
try:
first = input('First to start?[y/n]:').upper()
except(EOFError, KeyboardInterrupt):
print("Bye")
exit()
except(KeyError, ValueError):
print("Bad choice")
human_turn(c_choice, h_choice)
ai_turn(c_choice, h_choice)
if wins(board, hum):
clean()
print(f'Human turn [{h_choice}]')
render(board, c_choice, h_choice)
print("YOU WIN")
elif wins(board, comp):
clean()
print(f'Computer turn [{c_choice}]')
render(board, c_choice, h_choice)
print("YOU LOSE")
else:
clean()
render(board, c_choice, h_choice)
print("DRAW")
exit()
if __name__ == '__main__':
main()
pg. 4
OUTPUT:
Choose X or O
Chosen:X
First to start?[y/n]:y
Human turn [X]
--------------
| || || |
--------------
| || || |
--------------
| || || |
--------------
Use numpad(1..9)1
Computer turn [O]
--------------
| X || || |
--------------
| || || |
--------------
| || || |
--------------
Human turn [X]
--------------
| X || O || |
pg. 5