-
Notifications
You must be signed in to change notification settings - Fork 13
/
checkers.py
482 lines (440 loc) · 19.5 KB
/
checkers.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
from copy import deepcopy
import time
import math
ansi_black = "\u001b[30m"
ansi_red = "\u001b[31m"
ansi_green = "\u001b[32m"
ansi_yellow = "\u001b[33m"
ansi_blue = "\u001b[34m"
ansi_magenta = "\u001b[35m"
ansi_cyan = "\u001b[36m"
ansi_white = "\u001b[37m"
ansi_reset = "\u001b[0m"
class Node:
def __init__(self, board, move=None, parent=None, value=None):
self.board = board
self.value = value
self.move = move
self.parent = parent
def get_children(self, minimizing_player, mandatory_jumping):
current_state = deepcopy(self.board)
available_moves = []
children_states = []
big_letter = ""
queen_row = 0
if minimizing_player is True:
available_moves = Checkers.find_available_moves(current_state, mandatory_jumping)
big_letter = "C"
queen_row = 7
else:
available_moves = Checkers.find_player_available_moves(current_state, mandatory_jumping)
big_letter = "B"
queen_row = 0
for i in range(len(available_moves)):
old_i = available_moves[i][0]
old_j = available_moves[i][1]
new_i = available_moves[i][2]
new_j = available_moves[i][3]
state = deepcopy(current_state)
Checkers.make_a_move(state, old_i, old_j, new_i, new_j, big_letter, queen_row)
children_states.append(Node(state, [old_i, old_j, new_i, new_j]))
return children_states
def set_value(self, value):
self.value = value
def get_value(self):
return self.value
def get_board(self):
return self.board
def get_parent(self):
return self.parent
def set_parent(self, parent):
self.parent = parent
class Checkers:
def __init__(self):
self.matrix = [[], [], [], [], [], [], [], []]
self.player_turn = True
self.computer_pieces = 12
self.player_pieces = 12
self.available_moves = []
self.mandatory_jumping = False
for row in self.matrix:
for i in range(8):
row.append("---")
self.position_computer()
self.position_player()
def position_computer(self):
for i in range(3):
for j in range(8):
if (i + j) % 2 == 1:
self.matrix[i][j] = ("c" + str(i) + str(j))
def position_player(self):
for i in range(5, 8, 1):
for j in range(8):
if (i + j) % 2 == 1:
self.matrix[i][j] = ("b" + str(i) + str(j))
def print_matrix(self):
i = 0
print()
for row in self.matrix:
print(i, end=" |")
i += 1
for elem in row:
print(elem, end=" ")
print()
print()
for j in range(8):
if j == 0:
j = " 0"
print(j, end=" ")
print("\n")
def get_player_input(self):
available_moves = Checkers.find_player_available_moves(self.matrix, self.mandatory_jumping)
if len(available_moves) == 0:
if self.computer_pieces > self.player_pieces:
print(
ansi_red + "You have no moves left, and you have fewer pieces than the computer.YOU LOSE!" + ansi_reset)
exit()
else:
print(ansi_yellow + "You have no available moves.\nGAME ENDED!" + ansi_reset)
exit()
self.player_pieces = 0
self.computer_pieces = 0
while True:
coord1 = input("Which piece[i,j]: ")
if coord1 == "":
print(ansi_cyan + "Game ended!" + ansi_reset)
exit()
elif coord1 == "s":
print(ansi_cyan + "You surrendered.\nCoward." + ansi_reset)
exit()
coord2 = input("Where to[i,j]:")
if coord2 == "":
print(ansi_cyan + "Game ended!" + ansi_reset)
exit()
elif coord2 == "s":
print(ansi_cyan + "You surrendered.\nCoward." + ansi_reset)
exit()
old = coord1.split(",")
new = coord2.split(",")
if len(old) != 2 or len(new) != 2:
print(ansi_red + "Illegal input" + ansi_reset)
else:
old_i = old[0]
old_j = old[1]
new_i = new[0]
new_j = new[1]
if not old_i.isdigit() or not old_j.isdigit() or not new_i.isdigit() or not new_j.isdigit():
print(ansi_red + "Illegal input" + ansi_reset)
else:
move = [int(old_i), int(old_j), int(new_i), int(new_j)]
if move not in available_moves:
print(ansi_red + "Illegal move!" + ansi_reset)
else:
Checkers.make_a_move(self.matrix, int(old_i), int(old_j), int(new_i), int(new_j), "B", 0)
for m in range(8):
for n in range(8):
if self.matrix[m][n][0] == "c" or self.matrix[m][n][0] == "C":
self.computer_pieces += 1
elif self.matrix[m][n][0] == "b" or self.matrix[m][n][0] == "B":
self.player_pieces += 1
break
@staticmethod
def find_available_moves(board, mandatory_jumping):
available_moves = []
available_jumps = []
for m in range(8):
for n in range(8):
if board[m][n][0] == "c":
if Checkers.check_moves(board, m, n, m + 1, n + 1):
available_moves.append([m, n, m + 1, n + 1])
if Checkers.check_moves(board, m, n, m + 1, n - 1):
available_moves.append([m, n, m + 1, n - 1])
if Checkers.check_jumps(board, m, n, m + 1, n - 1, m + 2, n - 2):
available_jumps.append([m, n, m + 2, n - 2])
if Checkers.check_jumps(board, m, n, m + 1, n + 1, m + 2, n + 2):
available_jumps.append([m, n, m + 2, n + 2])
elif board[m][n][0] == "C":
if Checkers.check_moves(board, m, n, m + 1, n + 1):
available_moves.append([m, n, m + 1, n + 1])
if Checkers.check_moves(board, m, n, m + 1, n - 1):
available_moves.append([m, n, m + 1, n - 1])
if Checkers.check_moves(board, m, n, m - 1, n - 1):
available_moves.append([m, n, m - 1, n - 1])
if Checkers.check_moves(board, m, n, m - 1, n + 1):
available_moves.append([m, n, m - 1, n + 1])
if Checkers.check_jumps(board, m, n, m + 1, n - 1, m + 2, n - 2):
available_jumps.append([m, n, m + 2, n - 2])
if Checkers.check_jumps(board, m, n, m - 1, n - 1, m - 2, n - 2):
available_jumps.append([m, n, m - 2, n - 2])
if Checkers.check_jumps(board, m, n, m - 1, n + 1, m - 2, n + 2):
available_jumps.append([m, n, m - 2, n + 2])
if Checkers.check_jumps(board, m, n, m + 1, n + 1, m + 2, n + 2):
available_jumps.append([m, n, m + 2, n + 2])
if mandatory_jumping is False:
available_jumps.extend(available_moves)
return available_jumps
elif mandatory_jumping is True:
if len(available_jumps) == 0:
return available_moves
else:
return available_jumps
@staticmethod
def check_jumps(board, old_i, old_j, via_i, via_j, new_i, new_j):
if new_i > 7 or new_i < 0:
return False
if new_j > 7 or new_j < 0:
return False
if board[via_i][via_j] == "---":
return False
if board[via_i][via_j][0] == "C" or board[via_i][via_j][0] == "c":
return False
if board[new_i][new_j] != "---":
return False
if board[old_i][old_j] == "---":
return False
if board[old_i][old_j][0] == "b" or board[old_i][old_j][0] == "B":
return False
return True
@staticmethod
def check_moves(board, old_i, old_j, new_i, new_j):
if new_i > 7 or new_i < 0:
return False
if new_j > 7 or new_j < 0:
return False
if board[old_i][old_j] == "---":
return False
if board[new_i][new_j] != "---":
return False
if board[old_i][old_j][0] == "b" or board[old_i][old_j][0] == "B":
return False
if board[new_i][new_j] == "---":
return True
@staticmethod
def calculate_heuristics(board):
result = 0
mine = 0
opp = 0
for i in range(8):
for j in range(8):
if board[i][j][0] == "c" or board[i][j][0] == "C":
mine += 1
if board[i][j][0] == "c":
result += 5
if board[i][j][0] == "C":
result += 10
if i == 0 or j == 0 or i == 7 or j == 7:
result += 7
if i + 1 > 7 or j - 1 < 0 or i - 1 < 0 or j + 1 > 7:
continue
if (board[i + 1][j - 1][0] == "b" or board[i + 1][j - 1][0] == "B") and board[i - 1][
j + 1] == "---":
result -= 3
if (board[i + 1][j + 1][0] == "b" or board[i + 1][j + 1] == "B") and board[i - 1][j - 1] == "---":
result -= 3
if board[i - 1][j - 1][0] == "B" and board[i + 1][j + 1] == "---":
result -= 3
if board[i - 1][j + 1][0] == "B" and board[i + 1][j - 1] == "---":
result -= 3
if i + 2 > 7 or i - 2 < 0:
continue
if (board[i + 1][j - 1][0] == "B" or board[i + 1][j - 1][0] == "b") and board[i + 2][
j - 2] == "---":
result += 6
if i + 2 > 7 or j + 2 > 7:
continue
if (board[i + 1][j + 1][0] == "B" or board[i + 1][j + 1][0] == "b") and board[i + 2][
j + 2] == "---":
result += 6
elif board[i][j][0] == "b" or board[i][j][0] == "B":
opp += 1
return result + (mine - opp) * 1000
@staticmethod
def find_player_available_moves(board, mandatory_jumping):
available_moves = []
available_jumps = []
for m in range(8):
for n in range(8):
if board[m][n][0] == "b":
if Checkers.check_player_moves(board, m, n, m - 1, n - 1):
available_moves.append([m, n, m - 1, n - 1])
if Checkers.check_player_moves(board, m, n, m - 1, n + 1):
available_moves.append([m, n, m - 1, n + 1])
if Checkers.check_player_jumps(board, m, n, m - 1, n - 1, m - 2, n - 2):
available_jumps.append([m, n, m - 2, n - 2])
if Checkers.check_player_jumps(board, m, n, m - 1, n + 1, m - 2, n + 2):
available_jumps.append([m, n, m - 2, n + 2])
elif board[m][n][0] == "B":
if Checkers.check_player_moves(board, m, n, m - 1, n - 1):
available_moves.append([m, n, m - 1, n - 1])
if Checkers.check_player_moves(board, m, n, m - 1, n + 1):
available_moves.append([m, n, m - 1, n + 1])
if Checkers.check_player_jumps(board, m, n, m - 1, n - 1, m - 2, n - 2):
available_jumps.append([m, n, m - 2, n - 2])
if Checkers.check_player_jumps(board, m, n, m - 1, n + 1, m - 2, n + 2):
available_jumps.append([m, n, m - 2, n + 2])
if Checkers.check_player_moves(board, m, n, m + 1, n - 1):
available_moves.append([m, n, m + 1, n - 1])
if Checkers.check_player_jumps(board, m, n, m + 1, n - 1, m + 2, n - 2):
available_jumps.append([m, n, m + 2, n - 2])
if Checkers.check_player_moves(board, m, n, m + 1, n + 1):
available_moves.append([m, n, m + 1, n + 1])
if Checkers.check_player_jumps(board, m, n, m + 1, n + 1, m + 2, n + 2):
available_jumps.append([m, n, m + 2, n + 2])
if mandatory_jumping is False:
available_jumps.extend(available_moves)
return available_jumps
elif mandatory_jumping is True:
if len(available_jumps) == 0:
return available_moves
else:
return available_jumps
@staticmethod
def check_player_moves(board, old_i, old_j, new_i, new_j):
if new_i > 7 or new_i < 0:
return False
if new_j > 7 or new_j < 0:
return False
if board[old_i][old_j] == "---":
return False
if board[new_i][new_j] != "---":
return False
if board[old_i][old_j][0] == "c" or board[old_i][old_j][0] == "C":
return False
if board[new_i][new_j] == "---":
return True
@staticmethod
def check_player_jumps(board, old_i, old_j, via_i, via_j, new_i, new_j):
if new_i > 7 or new_i < 0:
return False
if new_j > 7 or new_j < 0:
return False
if board[via_i][via_j] == "---":
return False
if board[via_i][via_j][0] == "B" or board[via_i][via_j][0] == "b":
return False
if board[new_i][new_j] != "---":
return False
if board[old_i][old_j] == "---":
return False
if board[old_i][old_j][0] == "c" or board[old_i][old_j][0] == "C":
return False
return True
def evaluate_states(self):
t1 = time.time()
current_state = Node(deepcopy(self.matrix))
first_computer_moves = current_state.get_children(True, self.mandatory_jumping)
if len(first_computer_moves) == 0:
if self.player_pieces > self.computer_pieces:
print(
ansi_yellow + "Computer has no available moves left, and you have more pieces left.\nYOU WIN!" + ansi_reset)
exit()
else:
print(ansi_yellow + "Computer has no available moves left.\nGAME ENDED!" + ansi_reset)
exit()
dict = {}
for i in range(len(first_computer_moves)):
child = first_computer_moves[i]
value = Checkers.minimax(child.get_board(), 4, -math.inf, math.inf, False, self.mandatory_jumping)
dict[value] = child
if len(dict.keys()) == 0:
print(ansi_green + "Computer has cornered itself.\nYOU WIN!" + ansi_reset)
exit()
new_board = dict[max(dict)].get_board()
move = dict[max(dict)].move
self.matrix = new_board
t2 = time.time()
diff = t2 - t1
print("Computer has moved (" + str(move[0]) + "," + str(move[1]) + ") to (" + str(move[2]) + "," + str(
move[3]) + ").")
print("It took him " + str(diff) + " seconds.")
@staticmethod
def minimax(board, depth, alpha, beta, maximizing_player, mandatory_jumping):
if depth == 0:
return Checkers.calculate_heuristics(board)
current_state = Node(deepcopy(board))
if maximizing_player is True:
max_eval = -math.inf
for child in current_state.get_children(True, mandatory_jumping):
ev = Checkers.minimax(child.get_board(), depth - 1, alpha, beta, False, mandatory_jumping)
max_eval = max(max_eval, ev)
alpha = max(alpha, ev)
if beta <= alpha:
break
current_state.set_value(max_eval)
return max_eval
else:
min_eval = math.inf
for child in current_state.get_children(False, mandatory_jumping):
ev = Checkers.minimax(child.get_board(), depth - 1, alpha, beta, True, mandatory_jumping)
min_eval = min(min_eval, ev)
beta = min(beta, ev)
if beta <= alpha:
break
current_state.set_value(min_eval)
return min_eval
@staticmethod
def make_a_move(board, old_i, old_j, new_i, new_j, big_letter, queen_row):
letter = board[old_i][old_j][0]
i_difference = old_i - new_i
j_difference = old_j - new_j
if i_difference == -2 and j_difference == 2:
board[old_i + 1][old_j - 1] = "---"
elif i_difference == 2 and j_difference == 2:
board[old_i - 1][old_j - 1] = "---"
elif i_difference == 2 and j_difference == -2:
board[old_i - 1][old_j + 1] = "---"
elif i_difference == -2 and j_difference == -2:
board[old_i + 1][old_j + 1] = "---"
if new_i == queen_row:
letter = big_letter
board[old_i][old_j] = "---"
board[new_i][new_j] = letter + str(new_i) + str(new_j)
def play(self):
print(ansi_cyan + "##### WELCOME TO CHECKERS ####" + ansi_reset)
print("\nSome basic rules:")
print("1.You enter the coordinates in the form i,j.")
print("2.You can quit the game at any time by pressing enter.")
print("3.You can surrender at any time by pressing 's'.")
print("Now that you've familiarized yourself with the rules, enjoy!")
while True:
answer = input("\nFirst, we need to know, is jumping mandatory?[Y/n]: ")
if answer == "Y" or answer == "y":
self.mandatory_jumping = True
break
elif answer == "N" or answer == "n":
self.mandatory_jumping = False
break
elif answer == "":
print(ansi_cyan + "Game ended!" + ansi_reset)
exit()
elif answer == "s":
print(ansi_cyan + "You've surrendered before the game even started.\nPathetic." + ansi_reset)
exit()
else:
print(ansi_red + "Illegal input!" + ansi_reset)
while True:
self.print_matrix()
if self.player_turn is True:
print(ansi_cyan + "\nPlayer's turn." + ansi_reset)
self.get_player_input()
else:
print(ansi_cyan + "Computer's turn." + ansi_reset)
print("Thinking...")
self.evaluate_states()
if self.player_pieces == 0:
self.print_matrix()
print(ansi_red + "You have no pieces left.\nYOU LOSE!" + ansi_reset)
exit()
elif self.computer_pieces == 0:
self.print_matrix()
print(ansi_green + "Computer has no pieces left.\nYOU WIN!" + ansi_reset)
exit()
elif self.computer_pieces - self.player_pieces == 7:
wish = input("You have 7 pieces fewer than your opponent.Do you want to surrender?")
if wish == "" or wish == "yes":
print(ansi_cyan + "Coward." + ansi_reset)
exit()
self.player_turn = not self.player_turn
if __name__ == '__main__':
checkers = Checkers()
checkers.play()