-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathboard.py
More file actions
634 lines (567 loc) · 25.3 KB
/
Copy pathboard.py
File metadata and controls
634 lines (567 loc) · 25.3 KB
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
import random
# ! next week goals :
# 1) duck piece
evalcount = 0
class Board:
"""
Represents the configuration of a chess board.
"""
def __init__(self):
# This board isn't in it's initial state it's like this for testing purposes
self.board = [
'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
'X', 'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R', 'X',
'X', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'X',
'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X',
'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X',
'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X',
'X', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'X',
'X', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'X',
'X', 'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r', 'X',
'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
]
def notation_to_index(self, notation):
"""
Helper function for move_piece
"""
col = ord(notation[0]) - ord('a') + 1
row = int(notation[1])
index = (10 - row) * 10 + col
return index
def index_to_notation(self, position):
"""
Helper function for move_piece
"""
row, col = position
notation = chr(col + ord('a') - 1) + str(10 - row)
return notation
def get_piece(self, position):
"""
Gets the piece at the given position.
"""
row, col = position
index = row * 10 + col # Using *10 to match your board representation
return self.board[index]
def set_piece(self, position, piece):
"""
Sets the piece at the given position.
"""
row, col = position
index = row * 10 + col # Using *10 to match your board representation
self.board[index] = piece
def move_piece(self, start_notation, end_notation):
"""
Moves the piece from the start position to the end position.
"""
start = self.notation_to_index(start_notation)
end = self.notation_to_index(end_notation)
piece = self.get_piece((start // 10, start % 10))
self.set_piece((start // 10, start % 10), " ")
self.set_piece((end // 10, end % 10), piece)
def print_board(self):
"""
Prints the board in the terminal
"""
for i in range(2, 10):
# for i in range(9, 1, -1):
row = " "
for j in range(1, 9):
row = row+self.board[i*10+j]
print(row)
def findWhiteMoves(self, pos):
"""
Finds all the available moves for some white piece defined by it's position
"""
res = []
# Taking function :
def can_take_w(target_pos):
return self.board[target_pos] != "X" and self.board[target_pos].isupper() and self.board[target_pos] != "D"
# KING:
if self.board[pos] == 'k':
k_moves = [-1, +1, -10, +10, -9, -11, +11, +9]
for m in k_moves:
if self.board[pos+m] != "X" and self.board[pos+m] == " " or can_take_w(pos+m):
res.append(('k', pos, pos+m))
# KNIGHT:
elif self.board[pos] == 'n':
n_moves = [-21, +21, -19, +19, -12, +12, -8, +8]
for m in n_moves:
if self.board[pos+m] != "X" and self.board[pos+m] == " " or can_take_w(pos+m):
res.append(('n', pos, pos+m))
# ROOK:
elif self.board[pos] == 'r':
r_moves = [-10, +10, -1, +1]
for m in r_moves:
for i in range(1, 8):
new_pos = pos + m * i
# ! If i delete this it gives me error :
if not (21 <= new_pos <= 98):
break
if self.board[new_pos] != 'X':
if self.board[new_pos] == " ":
res.append(('r', pos, new_pos))
elif self.board[new_pos].isupper() and self.board[new_pos] != "D":
res.append(('r', pos, new_pos))
break
elif self.board[new_pos].islower():
break
# BISHOP :
# ! make it better bc errors
elif self.board[pos] == 'b':
b_moves = [-11, +11, -9, +9]
for m in b_moves:
for i in range(1, 8):
new_pos = pos + m * i
new_row = new_pos // 10
new_col = new_pos % 10
if not (2 <= new_row <= 9) or not (1 <= new_col <= 8):
break
if self.board[new_pos] != 'X':
if self.board[new_pos] == " ":
res.append(('b', pos, new_pos))
elif self.board[new_pos].isupper() and self.board[new_pos] != "D":
res.append(('b', pos, new_pos))
break
elif self.board[new_pos].islower():
break
# QUEEN :
elif self.board[pos] == 'q':
# Combines rook and bishop moves
q_moves = [-10, +10, -1, +1, -11, +11, -9, +9]
for m in q_moves:
for i in range(1, 8):
# new_pos = pos + m * i
# # ! If i delete this it gives me error :
# if not (21 <= new_pos <= 98):
# break
# if self.board[new_pos] != 'X':
# if self.board[new_pos] == " ":
# res.append(('q', pos, new_pos))
# elif self.board[new_pos].isupper():
# res.append(('q', pos, new_pos))
# break
# elif self.board[new_pos].islower():
# break
# for i in range(1, 8):
new_pos = pos + m * i
# ! If i delete this it gives me error :
# if not (21 <= new_pos <= 98):
if self.board[new_pos] == 'X':
break
if self.board[new_pos] == " ":
res.append(('q', pos, new_pos))
elif self.board[new_pos].isupper() and self.board[new_pos] != "D":
res.append(('q', pos, new_pos))
break
elif self.board[new_pos].islower():
break
# PAWN:
elif self.board[pos] == 'p':
p_moves = [-10, -20]
for m in p_moves:
new_pos = pos + m
# Double move forward from starting position
# checks if pawn is at its starting position + if there's a piece blocking the move
if m == -20 and 81 <= pos <= 88:
if self.board[new_pos] == " " and self.board[new_pos + 10] == " ":
res.append(('p', pos, new_pos))
# Single move forward
if m == -10 and 31 <= pos <= 89 and self.board[new_pos] == " ":
res.append(('p', pos, new_pos))
# Diagonal captures
diagonal_moves = [-9, -11]
for m in diagonal_moves:
new_pos = pos + m
if can_take_w(new_pos):
res.append(('p', pos, new_pos))
return res
def findAllWhiteMoves(self):
"""
Using the function findWhiteMoves this function goes through all of the white pieces and finds all the available moves for the white pieces
"""
def chess_notation(pos):
"""Translate the pos to chess coordinations"""
# Convert the column number to its corresponding letter
col = chr((pos % 10) + 96)
# Convert the row number to a string
row = str(10 - (pos // 10))
return col + row
res = []
for i in range(2, 10):
for j in range(1, 9):
moves = self.findWhiteMoves(i * 10 + j)
for move in moves:
piece, start, end = move
start_notation = chess_notation(start)
end_notation = chess_notation(end)
res.append((piece, start_notation, end_notation))
return res
def findBlackMoves(self, pos):
"""
Finds all the available moves for some black piece defined by it's position
"""
res = []
# Taking function :
def can_take_b(target_pos):
return self.board[target_pos] != "X" and self.board[target_pos].islower()
# KING:
if self.board[pos] == 'K':
k_moves = [-1, +1, -10, +10, -9, -11, +11, +9]
for m in k_moves:
if self.board[pos+m] != "X" and self.board[pos+m] == " " or can_take_b(pos+m):
res.append(('K', pos, pos+m))
# KNIGHT:
elif self.board[pos] == 'N':
n_moves = [-21, +21, -19, +19, -12, +12, -8, +8]
for m in n_moves:
if self.board[pos+m] != "X" and self.board[pos+m] == " " or can_take_b(pos+m):
res.append(('N', pos, pos+m))
# ROOK:
elif self.board[pos] == 'R':
r_moves = [-10, +10, -1, +1]
for m in r_moves:
for i in range(1, 8):
new_pos = pos + m * i
# ! If i delete this it gives me error
if not (21 <= new_pos <= 98):
break
if self.board[new_pos] != 'X':
if self.board[new_pos] == " ":
res.append(('R', pos, new_pos))
elif self.board[new_pos].islower():
res.append(('R', pos, new_pos))
break
elif self.board[new_pos].isupper():
break
# BISHOP :
elif self.board[pos] == 'B':
b_moves = [-11, +11, -9, +9]
for m in b_moves:
for i in range(1, 8):
new_pos = pos + m * i
# ! If i delete this it gives me error
if not (21 <= new_pos <= 98):
break
if self.board[new_pos] != 'X':
if self.board[new_pos] == " ":
res.append(('B', pos, new_pos))
elif self.board[new_pos].islower():
res.append(('B', pos, new_pos))
break
elif self.board[new_pos].isupper():
break
# QUEEN :
elif self.board[pos] == 'Q':
# Combines rook and bishop moves
q_moves = [-10, +10, -1, +1, -11, +11, -9, +9]
for m in q_moves:
for i in range(1, 8):
new_pos = pos + m * i
# ! If i delete this i get error
if not (21 <= new_pos <= 98):
break
if self.board[new_pos] != 'X':
if self.board[new_pos] == " ":
res.append(('Q', pos, new_pos))
elif self.board[new_pos].islower():
res.append(('Q', pos, new_pos))
break
elif self.board[new_pos].isupper():
break
# PAWN:
elif self.board[pos] == 'P':
p_moves = [+10, +20]
for m in p_moves:
new_pos = pos + m
# Double move forward from starting position :
# checks if pawn is at its starting position + if there's a piece blocking the move
if m == 20 and 31 <= pos <= 38:
if self.board[new_pos] == " " and self.board[new_pos - 10] == " ":
res.append(('P', pos, new_pos))
# Single move forward :
if m == 10 and 31 <= pos <= 98 and self.board[new_pos] == " ":
res.append(('P', pos, new_pos))
# Diagonal captures
diagonal_moves = [9, 11]
for m in diagonal_moves:
new_pos = pos + m
if can_take_b(new_pos):
res.append(('P', pos, new_pos))
return res
def findAllBlackMoves(self):
"""
Using the function findBlackMoves this function goes through all of the white pieces and finds all the available moves for the white pieces
"""
def chess_notation(pos):
"""Translate the pos to chess coordinations"""
# Convert the column number to its corresponding letter
col = chr((pos % 10) + 96)
# Convert the row number to a string
row = str(10 - (pos // 10))
return col + row
res = []
for i in range(2, 10):
for j in range(1, 9):
moves = self.findBlackMoves(i * 10 + j)
for move in moves:
piece, start, end = move
start_notation = chess_notation(start)
end_notation = chess_notation(end)
res.append((piece, start_notation, end_notation))
return res
def evaluate_score(board):
"""
This function evaluates the position of the pieces on the chess board and returns a value, if the value is positive then white is wining, if the value is negative then black is winning. (some pieces hold more value than others)
"""
global evalcount
evalcount += 1
piece_values = {'D': 0, ' ': 0, 'P': -1, 'N': -3, 'B': -3.5, 'R': -5, 'Q': -10, 'K': -100,
'p': 1, 'n': 3, 'b': 3.5, 'r': 5, 'q': 10, 'k': 100}
result = 0
for i in range(2, 10):
for j in range(1, 9):
piece = board.get_piece((i, j))
result += piece_values[piece]
return result
def remove_duck_piece(self):
for index, piece in enumerate(self.board):
if piece == "D":
self.board[index] = " "
break
def place_duck_piece(self, move):
piece, start_notation, end_notation = move
index = self.notation_to_index(end_notation)
if self.board[index] == " ":
self.remove_duck_piece()
self.board[index] = "D"
else:
return "Can't make that move"
# def captured_pieces(self):
# white_pieces = 'rnbqkp'
# black_pieces = 'RNBQKP'
# total_white_pieces = 16
# total_black_pieces = 16
# current_white_pieces = 0
# current_black_pieces = 0
# current_piece_count = {'R': 0, 'N': 0, 'B': 0, 'Q': 0, 'K': 0,
# 'P': 0, 'r': 0, 'n': 0, 'b': 0, 'q': 0, 'k': 0, 'p': 0}
# for row in range(2, 10): # Only iterate over the 8x8 chess board
# for col in range(1, 9):
# cell = self.board[row * 10 + col]
# if cell in white_pieces:
# current_white_pieces += 1
# current_piece_count[cell] += 1
# elif cell in black_pieces:
# current_black_pieces += 1
# current_piece_count[cell] += 1
# captured_white_pieces = total_white_pieces - current_white_pieces
# captured_black_pieces = total_black_pieces - current_black_pieces
# initial_piece_count = {'R': 2, 'N': 2, 'B': 2, 'Q': 1, 'K': 1, 'P': 8,
# 'r': 2, 'n': 2, 'b': 2, 'q': 1, 'k': 1, 'p': 8}
# captured_pieces = {}
# for piece, count in current_piece_count.items():
# captured_count = initial_piece_count[piece] - count
# if captured_count > 0:
# captured_pieces[piece] = captured_count
# return captured_white_pieces, captured_black_pieces, captured_pieces
# Alpha-beta Algorithm :
def generate_moves(self, is_white_turn):
if is_white_turn:
return self.findAllWhiteMoves()
else:
return self.findAllBlackMoves()
def make_move(self, move):
piece, start_notation, end_notation = move
start_index = self.notation_to_index(start_notation)
end_index = self.notation_to_index(end_notation)
start_position = (start_index // 10, start_index % 10)
end_position = (end_index // 10, end_index % 10)
captured_piece = self.get_piece(end_position)
if captured_piece != " ":
self.remove_piece(end_position)
self.move_piece(start_notation, end_notation)
return captured_piece
# ! not sure
def undo_move(self, move, captured_piece):
piece, start_notation, end_notation = move
end_index = self.notation_to_index(end_notation)
end_position = (end_index // 10, end_index % 10)
self.move_piece(end_notation, start_notation)
self.set_piece(end_position, captured_piece)
# Helper function
def remove_piece(self, position):
row, col = position
index = row * 10 + col
self.board[index] = " "
def alpha_beta(self, board, depth, alpha, beta, maximizing_player):
if depth == 0: # ! needs to also check if the game is over here
return self.evaluate_score()
if maximizing_player:
max_eval = float('-inf')
for move in board.findAllBlackMoves():
captured_piece = board.make_move(move)
eval = self.alpha_beta(board, depth - 1, alpha, beta, False)
board.undo_move(move, captured_piece) # Undo the move
max_eval = max(max_eval, eval)
alpha = max(alpha, eval)
if beta <= alpha:
break
return max_eval
else:
min_eval = float('inf')
for move in board.findAllWhiteMoves():
captured_piece = board.make_move(move)
eval = self.alpha_beta(board, depth - 1, alpha, beta, True)
board.undo_move(move, captured_piece) # Undo the move
min_eval = min(min_eval, eval)
beta = min(beta, eval)
if beta <= alpha:
break
return min_eval
def find_best_moves(self, depth, is_white_turn, num_moves=2):
moves = self.generate_moves(is_white_turn)
best_moves = []
for move in moves:
captured_piece = self.make_move(move)
eval = self.alpha_beta(
self, depth - 1, float('-inf'), float('inf'), is_white_turn)
self.undo_move(move, captured_piece)
best_moves.append((move, eval))
best_moves.sort(key=lambda x: x[1], reverse=is_white_turn)
return best_moves[:num_moves]
# Testing
my_board = Board()
my_board.print_board()
print("Black moves : ", my_board.findAllBlackMoves())
print("White moves : ", my_board.findAllWhiteMoves())
print(my_board.evaluate_score())
for i in range(6):
best_move = my_board.find_best_moves(depth=3, is_white_turn=True)[0][0]
print("Move : ", best_move)
my_board.make_move(best_move)
opposition_best_moves = my_board.find_best_moves(
depth=3, is_white_turn=False)
opposition_best_move_index = 0
while True:
opposition_best_move = opposition_best_moves[opposition_best_move_index][0]
print("Opposition move : ", opposition_best_move)
result = my_board.place_duck_piece(opposition_best_move)
if result == "Can't make that move":
opposition_best_move_index += 1
else:
break
if opposition_best_move_index >= len(opposition_best_moves):
print("No valid moves left for the duck piece")
while True:
random_row = random.randint(2, 9)
random_col = random.randint(1, 8)
random_position = (random_row, random_col)
random_notation = my_board.index_to_notation(random_position)
if my_board.get_piece(random_position) == " ":
my_board.place_duck_piece(("D", None, random_notation))
print(
f"Placing the duck piece at a random square: {random_notation}")
break
break
my_board.print_board()
print("evalcount", evalcount)
evalcount = 0
best_move = my_board.find_best_moves(depth=3, is_white_turn=False)[0][0]
print("Move : ", best_move)
my_board.make_move(best_move)
opposition_best_moves = my_board.find_best_moves(
depth=3, is_white_turn=True)
opposition_best_move_index = 0
while True:
opposition_best_move = opposition_best_moves[opposition_best_move_index][0]
print("Opposition move : ", opposition_best_move)
result = my_board.place_duck_piece(opposition_best_move)
if result == "Can't make that move":
opposition_best_move_index += 1
else:
break
if opposition_best_move_index >= len(opposition_best_moves):
print("No moves left for the duck piece to block")
while True:
random_row = random.randint(2, 9)
random_col = random.randint(1, 8)
random_position = (random_row, random_col)
random_notation = my_board.index_to_notation(random_position)
if my_board.get_piece(random_position) == " ":
my_board.place_duck_piece(("D", None, random_notation))
print(
f"Placing the duck piece at a random square: {random_notation}")
break
break
my_board.print_board()
print("evalcount", evalcount)
evalcount = 0
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=True)
# print("Move : ", best_move)
# my_board.make_move(best_move)
# best_move = my_board.find_best_move(depth=3, is_white_turn=False)
# print("Move : ", best_move)
# my_board.make_move(best_move)
print(my_board.evaluate_score())