-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine.py
402 lines (346 loc) · 11.8 KB
/
engine.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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import math
import random
import time
ROW_COUNT = 6
COLUMN_COUNT = 7
tree = []
min_tree = {}
def convert_from_string_to_grid(state):
grid = [[0] * 7 for _ in range(6)]
for i in range(0, 6):
for j in range(0, 7):
grid[i][j] = int(state[i * 7 + j])
return grid
def convert_from_grid_to_string(grid):
state = ""
for i in range(0, 6):
for j in range(0, 7):
state += str(grid[i][j])
return state
def drop_piece(state, col, piece):
for row in range(5, -1, -1):
if state[row * 7 + col] == "0":
newstate = (
state[: row * 7 + col] + str(piece)[0] + state[row * 7 + col + 1 :]
)
break
return newstate
def is_valid_location(state, col):
return state[col] == "0"
def get_valid_locations(state):
locations = []
for col in range(7):
if is_valid_location(state, col):
locations.append(col)
return locations
def get_score(state, col, piece, depth, option):
next_state = drop_piece(state, col, piece)
if option == 1:
new_dict = {
next_state: {
"depth": depth - 1,
"piece": piece % 2 + 1,
"value": 0,
"childs": [],
}
}
value = minimax(next_state, depth - 1, piece % 2 + 1, False, new_dict)
new_dict[next_state]["value"] = value
min_tree[state]["childs"].append(new_dict)
return value
else:
new_dict = {
next_state: {
"depth": depth - 1,
"piece": piece % 2 + 1,
"value": 0,
"childs": [],
}
}
value = minimax_alpha_beta(
next_state, depth - 1, -math.inf, math.inf, piece % 2 + 1, False, new_dict
)
new_dict[next_state]["value"] = value
min_tree[state]["childs"].append(new_dict)
return value
def minimax_heuristic(state, player):
# return 100
board = convert_from_string_to_grid(state)
num_of_four = count_window(board, 4, player)
num_of_three = count_window(board, 3, player)
num_of_two = count_window(board, 2, player)
num_of_four_opp = count_window(board, 4, player % 2 + 1)
# num_of_three_opp = count_window(board, 3, player % 2 + 1)
# num_of_two_opp = count_window(board, 2, player % 2 + 1)
# num_of_fail_loase=fail_loses(board,4,player%2+1)
if (
num_of_four == 0
and num_of_three == 0
and num_of_two == 0
and num_of_four_opp == 0
# and num_of_three_opp == 0
):
return 0
return (
(10**10) * num_of_four
# + 1000 * num_of_three
# + 100 * num_of_two
# - 1 * num_of_two_opp
# - (10**6) * num_of_three_opp
- (10**8) * num_of_four_opp
# + 1000 * count_potential_future_wins(board, player)
# -10000 * count_potential_future_wins(board, player % 2+1)
)
def count_window(board, window, player):
number_of_windows = 0
# Hirozontal windows
for i in range(6):
for j in range(7 - window + 1):
if (
board[i][j : j + window].count(player) == window
and board[i][j : j + window].count(player % 2 + 1) == 0
):
number_of_windows += 1
# Vertical windows
for i in range(6 - window + 1):
for j in range(7):
arr = [board[i + k][j] for k in range(window)]
if arr.count(player) == window and arr.count(player % 2 + 1) == 0:
number_of_windows += 1
# Diagonal windows
for i in range(6 - window + 1):
for j in range(7 - window + 1):
arr = [board[i + k][j + k] for k in range(window)]
if arr.count(player) == window and arr.count(player % 2 + 1) == 0:
number_of_windows += 1
# Negative Diagonal windows
for i in range(6 - window + 1):
for j in range(7 - window + 1):
arr = [board[i + window - 1 - k][j + k] for k in range(window)]
if arr.count(player) == window and arr.count(player % 2 + 1) == 0:
number_of_windows += 1
return number_of_windows
# def evaluate_window(window, piece):
# opponent_piece = "1" if piece == "2" else "2"
# score = 0
# if window.count("2") == 4:
# score += 100000
# elif window.count("2") == 3 and window.count("0") == 1:
# score += 100
# if window.count("2") == 2 and window.count("0") == 2:
# score += 2
# if window.count("1") == 4:
# score -= 10000
# elif window.count("1") == 3 and window.count("0") == 1:
# score -= 500
# elif window.count("1") == 2 and window.count("0") == 2:
# score -= 1
# return score
def evaluate_window(window, piece):
"""Evaluates the score of a given window for a specific piece."""
opponent_piece = "1" if piece == "2" else "2"
score = 0
# Evaluate offensive potential
consecutive_pieces = window.count(str(piece))
free_slots = window.count("0")
if consecutive_pieces == 4:
score += 100000 # Win condition
elif consecutive_pieces == 3 and free_slots == 1:
score += 5000 # Strong winning opportunity
elif consecutive_pieces == 2 and free_slots == 2:
score += 200 # Potential winning connection
elif consecutive_pieces == 2 and free_slots > 2:
score += 10 # Encourage building connections
# Evaluate defensive potential
opponent_consecutive = window.count(str(opponent_piece))
if opponent_consecutive == 3 and free_slots == 1:
score -= 4000 # Block opponent's strong winning opportunity
elif opponent_consecutive == 2 and free_slots == 2:
score -= 100 # Block opponent's potential winning connection
elif opponent_consecutive == 2 and free_slots > 2:
score -= 5 # Discourage opponent from building connections
# Consider position in the board (center prioritization)
center_column = window[2] == piece
if center_column:
score += 15 # Encourage occupying the center
return score
def score_position(state, piece):
rows = ROW_COUNT
cols = COLUMN_COUNT
score = 0
center_array = [state[r * cols + cols // 2] for r in range(rows)]
center_count = center_array.count(piece)
score += center_count * 6
# Score horizontal
for r in range(rows):
for c in range(cols - 3):
start = r * cols + c
window = state[start : start + 4]
score += evaluate_window(window, piece)
# Score vertical
for c in range(cols):
for r in range(rows - 3):
start = r * cols + c
window = state[start : start + 4 * cols : cols]
score += evaluate_window(window, piece)
# Score positively sloped diagonals
for r in range(3, rows):
for c in range(cols - 3):
start = r * cols + c
window = [state[start - i * (cols - 1)] for i in range(4)]
score += evaluate_window(window, piece)
# Score negatively sloped diagonals
for r in range(3, rows):
for c in range(3, cols):
start = r * cols + c
window = [state[start - i * (cols + 1)] for i in range(4)]
score += evaluate_window(window, piece)
return score
def is_terminal(state):
# Check for draw
if "0" not in state:
return True
return False
def minimax(state, depth, piece, maximizingPlayer, tree):
global NODE_EXPANDED
NODE_EXPANDED += 1
if depth == 0 or is_terminal(state):
value = score_position(state, piece)
return value
valid_location = get_valid_locations(state)
if maximizingPlayer:
value = -math.inf
for col in valid_location:
child = drop_piece(state, col, piece)
new_dict = {
child: {
"depth": depth - 1,
"piece": piece % 2 + 1,
"value": 0,
"childs": [],
}
}
value = max(
value, minimax(child, depth - 1, piece % 2 + 1, False, new_dict)
)
new_dict[child]["value"] = value
tree[state]["childs"].append(new_dict)
return value
else:
value = math.inf
for col in valid_location:
child = drop_piece(state, col, piece)
new_dict = {
child: {
"depth": depth - 1,
"piece": piece % 2 + 1,
"value": 0,
"childs": [],
}
}
value = min(value, minimax(child, depth - 1, piece % 2 + 1, True, new_dict))
new_dict[child]["value"] = value
tree[state]["childs"].append(new_dict)
return value
def minimax_alpha_beta(state, depth, alpha, beta, piece, maximizingPlayer, tree):
global NODE_EXPANDED
NODE_EXPANDED += 1
if depth == 0 or is_terminal(state):
return score_position(state, piece)
valid_location = get_valid_locations(state)
if maximizingPlayer:
value = -math.inf
for col in valid_location:
child = drop_piece(state, col, piece)
new_dict = {
child: {
"depth": depth - 1,
"piece": piece % 2 + 1,
"value": 0,
"childs": [],
}
}
value = max(
value,
minimax_alpha_beta(
child, depth - 1, alpha, beta, piece % 2 + 1, False, new_dict
),
)
alpha = max(alpha, value)
if beta <= alpha:
break
new_dict[child]["value"] = value
tree[state]["childs"].append(new_dict)
return value
else:
value = math.inf
for col in valid_location:
child = drop_piece(state, col, piece)
new_dict = {
child: {
"depth": depth - 1,
"piece": piece % 2 + 1,
"value": 0,
"childs": [],
}
}
value = min(
value,
minimax_alpha_beta(
child, depth - 1, alpha, beta, piece % 2 + 1, True, new_dict
),
)
beta = min(beta, value)
if beta <= alpha:
break
new_dict[child]["value"] = value
tree[state]["childs"].append(new_dict)
return value
def agent(grid, depth, option):
global NODE_EXPANDED
NODE_EXPANDED = 0
min_tree.clear()
state = convert_from_grid_to_string(grid)
min_tree[state] = {
"depth": depth,
"piece": 1,
"value": 0,
"childs": [],
}
valid_moves = get_valid_locations(state)
scores = dict(
zip(
valid_moves,
[get_score(state, col, 2, depth, option) for col in valid_moves],
)
)
max_cols = [key for key in scores.keys() if scores[key] == max(scores.values())]
# print("max cols are", max_cols)
res = random.choice(max_cols)
min_tree[state]["value"] = scores[res]
return res, min_tree, NODE_EXPANDED
def print_tree(tree, indent=0):
state = list(tree.keys())[0]
print(
" " * indent
+ f"{state} | Depth: {tree[state]['depth']}, Piece: {tree[state]['piece']}, Value: {tree[state]['value']}"
)
childs = tree[state]["childs"]
for child in childs:
print_tree(child, indent + 1)
board = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0],
[1, 2, 1, 2, 0, 2, 2],
[1, 2, 2, 1, 1, 2, 1],
]
def main():
start = time.time()
Res = agent(board, 8, 2)
print(Res[0], Res[2])
end = time.time()
print(end - start)
if __name__ == "__main__":
main()