-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
HumanvsAI_Minimax.py
157 lines (132 loc) · 5.63 KB
/
HumanvsAI_Minimax.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
from math import inf as infinity
game_state = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
players = ['X','O']
def play_move(state, player, block_num):
if state[int((block_num-1)/3)][(block_num-1)%3] == ' ':
state[int((block_num-1)/3)][(block_num-1)%3] = player
else:
block_num = int(input("Block is not empty, ya blockhead! Choose again: "))
play_move(state, player, block_num)
def copy_game_state(state):
new_state = [[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
for i in range(3):
for j in range(3):
new_state[i][j] = state[i][j]
return new_state
def check_current_state(game_state):
# Check horizontals
if (game_state[0][0] == game_state[0][1] and game_state[0][1] == game_state[0][2] and game_state[0][0] != ' '):
return game_state[0][0], "Done"
if (game_state[1][0] == game_state[1][1] and game_state[1][1] == game_state[1][2] and game_state[1][0] != ' '):
return game_state[1][0], "Done"
if (game_state[2][0] == game_state[2][1] and game_state[2][1] == game_state[2][2] and game_state[2][0] != ' '):
return game_state[2][0], "Done"
# Check verticals
if (game_state[0][0] == game_state[1][0] and game_state[1][0] == game_state[2][0] and game_state[0][0] != ' '):
return game_state[0][0], "Done"
if (game_state[0][1] == game_state[1][1] and game_state[1][1] == game_state[2][1] and game_state[0][1] != ' '):
return game_state[0][1], "Done"
if (game_state[0][2] == game_state[1][2] and game_state[1][2] == game_state[2][2] and game_state[0][2] != ' '):
return game_state[0][2], "Done"
# Check diagonals
if (game_state[0][0] == game_state[1][1] and game_state[1][1] == game_state[2][2] and game_state[0][0] != ' '):
return game_state[1][1], "Done"
if (game_state[2][0] == game_state[1][1] and game_state[1][1] == game_state[0][2] and game_state[2][0] != ' '):
return game_state[1][1], "Done"
# Check if draw
draw_flag = 0
for i in range(3):
for j in range(3):
if game_state[i][j] == ' ':
draw_flag = 1
if draw_flag == 0:
return None, "Draw"
return None, "Not Done"
def print_board(game_state):
print('----------------')
print('| ' + str(game_state[0][0]) + ' || ' + str(game_state[0][1]) + ' || ' + str(game_state[0][2]) + ' |')
print('----------------')
print('| ' + str(game_state[1][0]) + ' || ' + str(game_state[1][1]) + ' || ' + str(game_state[1][2]) + ' |')
print('----------------')
print('| ' + str(game_state[2][0]) + ' || ' + str(game_state[2][1]) + ' || ' + str(game_state[2][2]) + ' |')
print('----------------')
def getBestMove(state, player):
'''
Minimax Algorithm
'''
winner_loser , done = check_current_state(state)
if done == "Done" and winner_loser == 'O': # If AI won
return (1,0)
elif done == "Done" and winner_loser == 'X': # If Human won
return (-1,0)
elif done == "Draw": # Draw condition
return (0,0)
moves = []
empty_cells = []
for i in range(3):
for j in range(3):
if state[i][j] == ' ':
empty_cells.append(i*3 + (j+1))
for empty_cell in empty_cells:
move = {}
move['index'] = empty_cell
new_state = copy_game_state(state)
play_move(new_state, player, empty_cell)
if player == 'O': # If AI
result,_ = getBestMove(new_state, 'X') # make more depth tree for human
move['score'] = result
else:
result,_ = getBestMove(new_state, 'O') # make more depth tree for AI
move['score'] = result
moves.append(move)
# Find best move
best_move = None
if player == 'O': # If AI player
best = -infinity
for move in moves:
if move['score'] > best:
best = move['score']
best_move = move['index']
else:
best = infinity
for move in moves:
if move['score'] < best:
best = move['score']
best_move = move['index']
return (best, best_move)
# PLaying
play_again = 'Y'
while play_again == 'Y' or play_again == 'y':
game_state = [[' ',' ',' '],
[' ',' ',' '],
[' ',' ',' ']]
current_state = "Not Done"
print("\nNew Game!")
print_board(game_state)
player_choice = input("Choose which player goes first - X (You - the petty human) or O(The mighty AI): ")
winner = None
if player_choice == 'X' or player_choice == 'x':
current_player_idx = 0
else:
current_player_idx = 1
while current_state == "Not Done":
if current_player_idx == 0: # Human's turn
block_choice = int(input("Oye Human, your turn! Choose where to place (1 to 9): "))
play_move(game_state ,players[current_player_idx], block_choice)
else: # AI's turn
_,block_choice = getBestMove(game_state, players[current_player_idx])
play_move(game_state ,players[current_player_idx], block_choice)
print("AI plays move: " + str(block_choice))
print_board(game_state)
winner, current_state = check_current_state(game_state)
if winner is not None:
print(str(winner) + " won!")
else:
current_player_idx = (current_player_idx + 1)%2
if current_state == "Draw":
print("Draw!")
play_again = input('Wanna try again?(Y/N) : ')
if play_again == 'N':
print('GG!')