Repository navigation
Expand file tree
/
Copy pathloopyfish.py
More file actions
638 lines (518 loc) · 28.3 KB
/
Copy pathloopyfish.py
File metadata and controls
638 lines (518 loc) · 28.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
635
import chess.engine
import random
from reconchess import *
import os
import math
from collections import Counter, defaultdict
class Logger:
"""
Verbosity controller for print statements using a loggin class
"""
def __init__(self, verbosity : bool):
self.verbosity = verbosity
def log(self, message: str):
if self.verbosity:
print("[LOG]", message)
def error(self, message: str):
if self.verbosity:
print("[ERROR]", message)
STOCKFISH_ENV_VAR = 'STOCKFISH_EXECUTABLE'
MAX_BOARD_COUNT = 10000
SUBMISSION = False # Change to False if you want to test locally
logger = Logger(True) # Change to True if you want to see the logs
NULL_MOVE = chess.Move.null()
class BoardUtils:
"""
Class to store utility functions for the bot.
"""
@staticmethod
def is_valid_board_given_sense(board: chess.Board, sense_result: List[Tuple[Square, Optional[chess.Piece]]]) -> bool:
"""
Check if the board is valid given the sense result.
"""
for square, piece in sense_result:
if board.piece_at(square) != piece:
return False
return True
@staticmethod
def get_3x3_window(center: Square) -> List[Square]:
file = chess.square_file(center)
rank = chess.square_rank(center)
return [chess.square(f, r) for r in range(rank - 1, rank + 2) for f in range(file - 1, file + 2)
if 0 <= f < 8 and 0 <= r < 8]
@staticmethod
def generate_valid_moves(board: chess.Board) -> List[chess.Move]:
"""
Generate all valid moves for the given board and color.
"""
possible_moves = {NULL_MOVE}
for move in board.pseudo_legal_moves:
possible_moves.add(move)
for move in utilities.without_opponent_pieces(board).generate_castling_moves():
if not utilities.is_illegal_castle(board, move):
possible_moves.add(move)
return possible_moves
# THE BELOW CODE IS USED FROM THE strangefish2 bot - as indicated by them board.copy() is ineffecient and here is a more effecient implementation (https://github.com/ginoperrotta/reconchess-strangefish2/tree/master)
@staticmethod
def fast_copy_board(board: chess.Board) -> chess.Board:
new_board = object.__new__(chess.Board)
new_board.pawns = board.pawns
new_board.knights = board.knights
new_board.bishops = board.bishops
new_board.rooks = board.rooks
new_board.queens = board.queens
new_board.kings = board.kings
new_board.occupied_co = [*board.occupied_co]
new_board.occupied = board.occupied
new_board.promoted = board.promoted
new_board.chess960 = board.chess960
new_board.ep_square = board.ep_square
new_board.castling_rights = board.castling_rights
new_board.turn = board.turn
new_board.fullmove_number = board.fullmove_number
new_board.halfmove_clock = board.halfmove_clock
new_board.move_stack = []
new_board._stack = []
return new_board
@staticmethod
def check_own_pieces_consistency(self, boards) -> bool:
if len(boards) == 0:
return True
ref_board = self.boards[0]
own_squares = [sq for sq in chess.SQUARES if ref_board.piece_at(sq) and ref_board.piece_at(sq).color == self.color]
for board in self.boards:
for sq in own_squares:
ref_piece = ref_board.piece_at(sq)
other_piece = board.piece_at(sq)
if other_piece != ref_piece:
logger.error(f"[ERROR] Inconsistent own piece at {chess.square_name(sq)}: expected {ref_piece}, found {other_piece}")
logger.error(ref_board.fen())
logger.error(board.fen())
return False
return True
@staticmethod
def check_for_king_capture(board: chess.Board, color: Color) -> Optional[chess.Move]:
"""
Check if the king can be captured on the given board.
"""
# if we might be able to take the king, try to
enemy_king_square = board.king(not color)
if enemy_king_square:
# if there are any ally pieces that can take king, execute one of those moves
enemy_king_attackers = board.attackers(color, enemy_king_square)
if enemy_king_attackers:
attacker_square = enemy_king_attackers.pop()
king_capture_move = chess.Move(attacker_square, enemy_king_square)
return king_capture_move
return None
@staticmethod
def check_mate_move(board: chess.Board, color: Color) -> Optional[chess.Move]:
"""
Check if we are in checkmate, generate king moves and use one of them
"""
if board.is_checkmate():
possible_moves = utilities.moves_without_opponent_pieces(board)
king_square = board.king(color)
king_moves = []
for move in possible_moves:
if move.from_square == king_square:
king_moves.append(move)
if king_moves:
logger.log(f"We are in checkmate, suggesting king move")
return random.choice(king_moves)
return None
@staticmethod
def is_not_edge_square(square: Square) -> bool:
file = chess.square_file(square)
rank = chess.square_rank(square)
return 0 < file < 7 and 0 < rank < 7
@staticmethod
def move_heuristic_value(board: chess.Board, move: chess.Move) -> float:
"""
Heuristic scoring function for move selection in recon chess.
Incorporates tactical, strategic, and recon-specific elements.
"""
if move == chess.Move.null():
return -2.0
score = 1.0
piece = board.piece_at(move.from_square)
if board.is_capture(move):
score += 0.5
if board.gives_check(move):
score += 0.8
if piece and piece.piece_type in {chess.BISHOP}:
score += 0.1 * chess.square_distance(move.from_square, move.to_square)
return score
class loopyfish(Player):
def __init__(self):
self.boards : UniqueBoardList[chess.Board] = UniqueBoardList()
self.color : Color = None
self.move = 0
self.our_turn_debug = True
self.no_boards_debug = True
self.fail_safe_board : chess.Board = None
self.opponent_name : str = None
# make sure stockfish environment variable exists
if not SUBMISSION:
if STOCKFISH_ENV_VAR not in os.environ:
raise KeyError(
'TroutBot requires an environment variable called "{}" pointing to the Stockfish executable'.format(
STOCKFISH_ENV_VAR))
# make sure there is actually a file
stockfish_path = os.environ[STOCKFISH_ENV_VAR]
if not os.path.exists(stockfish_path):
raise ValueError('No stockfish executable found at "{}"'.format(stockfish_path))
# initialize the stockfish engine
self.engine = chess.engine.SimpleEngine.popen_uci(stockfish_path, setpgrp=True)
else:
self.engine = chess.engine.SimpleEngine.popen_uci('/opt/stockfish/stockfish', setpgrp=True)
# Code for submission
def handle_game_start(self, color: Color, board: chess.Board, opponent_name: str):
self.boards.add(board)
self.fail_safe_board = board
self.color = color
self.opponent_name = opponent_name
def handle_opponent_move_result(self, captured_my_piece: bool, capture_square: Optional[Square]):
"""
Handles the result of the opponent's move. Generate all possible moves for the current known board state. Refine this list if a capture was made.
"""
# FIRST UPDATE FAILSAFE BOARD
if captured_my_piece:
self.fail_safe_board.remove_piece_at(capture_square)
self.move += 1
# Don't need to do anything if we are the first move and we are white
if self.move == 1 and self.color == chess.WHITE:
return
new_potential_boards = UniqueBoardList()
for board in self.boards:
# make sure its our opponent's turn
if board.turn == self.color:
if self.our_turn_debug:
logger.error(f"IT SHOULD BE OUR OPPONENT'S TURN BUT IT IS OURS ON BOARD {board.fen()}")
logger.error(f"Current move is {self.move} and color is {self.color}")
logger.error(f"Opponent's turn is {board.turn} and our turn is {self.color}")
self.our_turn_debug = False
continue
possible_moves = BoardUtils.generate_valid_moves(board)
for move in possible_moves:
# if a piece has been captured, only consider moves that capture the piece else consider all possible moves
if captured_my_piece and move.to_square != capture_square:
continue
# if a piece has not been captured, only consider moves that do not capture the piece
if not captured_my_piece and board.is_capture(move):
continue
try:
board_copy = BoardUtils.fast_copy_board(board)
board_copy.push(move)
new_potential_boards.add(board_copy)
except Exception as e:
logger.error(f"Error pushing move {move} on board {board.fen()}: {e}")
continue
if not len(self.boards) == 0 and len(new_potential_boards) == 0:
logger.error("No boards available after handle_opponent_move_result")
self.boards = new_potential_boards
# if not BoardUtils.check_own_pieces_consistency(self, self.boards):
# logger.error(f"[ERROR] Boards became inconsistent after function call handle_opponent_move_result")
def choose_sense(self, sense_actions: List[Square], move_actions: List[chess.Move], seconds_left: float) -> Optional[Square]:
"""
strangefissh2-inspired strategy: for each sensing square calculate expected number of boards eliminated.
"""
# Something probably isnt optimal here but it works so just leave it.
if self.color == chess.WHITE:
if self.move >= 3 and self.move <= 5:
sense_c5 = chess.C5
sense_d4 = chess.D4
sense_e4 = chess.E4
if self.move == 3:
return sense_c5 # checks for 4 move mate + queenside attack
if self.move == 4:
return sense_d4 # confirms queenside attack
if self.move == 5:
return sense_e4 # confirms kingside attack
elif self.color == chess.BLACK:
sense_e5 = chess.E5
if self.move == 3 or self.move == 4: # checks for both kingside and kingside attacks
return sense_e5
def get_3x3_window(center: Square) -> List[Square]:
file = chess.square_file(center)
rank = chess.square_rank(center)
return [chess.square(f, r) for r in range(rank - 1, rank + 2) for f in range(file - 1, file + 2)
if 0 <= f < 8 and 0 <= r < 8]
best_square = None
max_expected_eliminations = -1 #we want to find sensing that gets rid of as many boards as possible. doesnt garuntee sensing corresponds to the exact move of opponent but improves overall performance
for square in filter(BoardUtils.is_not_edge_square, sense_actions):#makes use of helper function to filter out edge squares
window = get_3x3_window(square)
sense_results_counter = defaultdict(int)
#map each board to its sense result
for board in self.boards:
result = tuple((sq, board.piece_at(sq)) for sq in window)
sense_results_counter[result] += 1
total_boards = len(self.boards)
expected_eliminations = 0
# Estimate eliminations nb
for result, count in sense_results_counter.items():
eliminations = total_boards - count #if this sense result occurs in `count` boards, then (total - count) boards would be eliminated
probability = count / total_boards
expected_eliminations += probability * eliminations
if expected_eliminations > max_expected_eliminations: #tracking square w highest expected eliminations
max_expected_eliminations = expected_eliminations
best_square = square
if best_square is None: #failed, fallback on random strat :( (possibly change this back to entropy decision?)
best_square = random.choice(sense_actions)
print(f"Best square to sense is {best_square} with expected eliminations {max_expected_eliminations}")
return best_square
def handle_sense_result(self, sense_result: List[Tuple[Square, Optional[chess.Piece]]]):
"""
Handles the result of the sense action. If the observed piece is not consistent with the current board state, we remove that board from our list of possible boards.
Params:
sense_result (List[Tuple[Square, Optional[chess.Piece]]]): The result of the sense action.
- Each tuple contains a square and the piece (if any) on that square.
- i.e. [(59, Piece.from_symbol('q')), (60, Piece.from_symbol('k')), (61, Piece.from_symbol('b')), (51, Piece.from_symbol('p')), (52, None), (53, Piece.from_symbol('p')), (43, None), (44, None), (45, None)]
"""
# FIRST UPDATE FAILSAFE BOARD
for square, piece in sense_result:
self.fail_safe_board.set_piece_at(square, piece)
updated_boards = UniqueBoardList()
for board in self.boards:
if BoardUtils.is_valid_board_given_sense(board, sense_result):
updated_boards.add(board)
if not len(self.boards) == 0 and len(updated_boards) == 0:
logger.error("No boards available after handle_sense_result")
self.boards = updated_boards
# if not BoardUtils.check_own_pieces_consistency(self, self.boards):
# logger.error(f"[ERROR] Boards became inconsistent after function call handle_sense_result")
logger.log("We finished handling the sense result")
def fail_safe_move(self, move_actions: List[chess.Move] = None) -> Optional[chess.Move]:
"""
Backup incase we for some reason run out of boards
"""
print(self.fail_safe_board)
enemy_king_square = self.fail_safe_board.king(not self.color)
if enemy_king_square:
# if there are any ally pieces that can take king, execute one of those moves
enemy_king_attackers = self.fail_safe_board.attackers(self.color, enemy_king_square)
if enemy_king_attackers:
attacker_square = enemy_king_attackers.pop()
return chess.Move(attacker_square, enemy_king_square)
# otherwise, try to move with the stockfish chess engine
try:
self.fail_safe_board.turn = self.color
self.fail_safe_board.clear_stack()
result = self.engine.play(self.fail_safe_board, chess.engine.Limit(time=0.5))
return result.move
except chess.engine.EngineTerminatedError:
print('Stockfish Engine died')
except chess.engine.EngineError:
print('Stockfish Engine bad state at "{}"'.format(self.fail_safe_board.fen()))
return random.choice(move_actions)
def choose_move(self, move_actions: List[chess.Move] = None, seconds_left : float = None) -> Optional[chess.Move]:
"""
Chooses a move using the Stockfish engine or by checking if the king can be captured.
If the king can be captured, it will choose that move. Otherwise, it will use the Stockfish engine to choose a move.
"""
# idek if we need the below 2 statements but better safe than sorry
if not move_actions:
logger.error("No move actions provided")
return None
if len(self.boards) == 0:
logger.error("No boards available, switching to fail safe board")
return self.fail_safe_move(move_actions)
# This will either return self.boards or a random sample of self.boards, importantly it does not modify self.boards whatsoever
boards = self.boards.random_sample_if_needed(MAX_BOARD_COUNT)
valid_moves = set(move_actions) # optimization for checking if the move is valid
move_counter = Counter()
king_capture_counter = Counter()
check_mate_counter = Counter()
board : chess.Board
for board in boards:
check_mate_move = BoardUtils.check_mate_move(board, self.color)
if check_mate_move is not None:
if check_mate_move in valid_moves:
logger.log(f"In checkmate move {check_mate_move} found")
check_mate_counter[check_mate_move] += 1
continue
king_capture_move = BoardUtils.check_for_king_capture(board, self.color)
if king_capture_move is not None:
if king_capture_move in valid_moves:
king_capture_counter[king_capture_move] += 1
continue
# otherwise, try to move with the stockfish chess engine
try:
board.turn = self.color
board.clear_stack()
# Result is the best move for the current board state (IT DOES NOT PLAY THE MOVE)
result = self.engine.play(board, chess.engine.Limit(time=min(1, 10/len(boards))))
move = result.move
if move is None or move not in valid_moves:
logger.error(f"Stockfish returned None or invalid move {move} for board {board.fen()}")
continue
move_counter[move] += BoardUtils.move_heuristic_value(board, move)
except Exception as e:
logger.error(f"Error in stockfish engine: {e}")
continue
if king_capture_counter:
"""
Tree of reasoning:
Given x number of boards agree that king_capture_move is the best, in order for the move to be played the following must hold:
1. Out of all the possible king capture moves, more than 50% of those boards must have voted for king_capture_move
2. At least 35% of all boards agree that there is a king capture (not 50%+ since king captures way significantly)
"""
number_of_king_capture_votes = king_capture_counter.total()
king_capture_move, votes = king_capture_counter.most_common(1)[0]
local_king_capture_uncertainty = votes / number_of_king_capture_votes
global_king_capture_uncertainty = number_of_king_capture_votes / len(boards)
# universal_board_count = len(self.boards)
# I've solved the math for below, at < 10 000 boards threshhold = 0.5, at 100 000 boards threshhold = 0.8 but we cap at 0.8
# i.e. in very uncertain situations we need to be 80% sure that the move is a king capture
# local_uncertainty_threshold = min(max(0.5, -0.7 + 0.3 * math.log10(universal_board_count)), 0.8)
# ^^^ still need to test above
local_uncertainty_threshold = 0.5
global_uncertainty_threshold = 0.35
if (local_king_capture_uncertainty > local_uncertainty_threshold and global_king_capture_uncertainty > global_uncertainty_threshold):
logger.log("We 've met the conditions for a king capture move")
return king_capture_move
else:
logger.log(f"King capture move {king_capture_move} did not meet the conditions for a king capture move")
logger.log(f"King capture uncertainty: {local_king_capture_uncertainty}, global uncertainty: {global_king_capture_uncertainty}")
if check_mate_counter:
number_of_check_mate_votes = check_mate_counter.total()
local_check_mate_uncertainty = number_of_check_mate_votes / len(boards)
if local_check_mate_uncertainty > 0.5:
logger.log("We 've met the conditions for an anti check mate move")
check_mate_move, _ = check_mate_counter.most_common(1)[0][0]
return check_mate_move
if not move_counter:
logger.error(f"No valid moves found after evaluating all boards at move {self.move}")
return random.choice(move_actions)
most_common = sorted(move_counter.items(), key=lambda x: (-x[1], x[0].uci()))
best_move = most_common[0][0]
if best_move not in valid_moves:
logger.error(f"Most common move {best_move} not in valid move actions at move {self.move}")
return random.choice(move_actions)
logger.log(f"Best move at move {self.move} is {best_move} with {move_counter[best_move]} votes and {len(boards)} boards")
return best_move
def handle_move_result(self, requested_move: Optional[chess.Move], taken_move: Optional[chess.Move],
captured_opponent_piece: bool, capture_square: Optional[Square]):
"""
This is actually a super powerful part of the game, it can help us refine what our board may look like.
For e.g. right now some boards think it would be possible to capture the king, but if we know that the king was not captured, we can remove those boards from our list of possible boards.
All refinements need to be done in here.
"""
# FIRST UPDATE FAILSAFE BOARD
if taken_move is not None:
# REALLY WEIRD BUG: if you dont copy the board it breaks the code below and eliminates all boards. IDK man. I guess it connects with all chess.BOARDS or something weird.
copy_board = BoardUtils.fast_copy_board(self.fail_safe_board)
copy_board.clear_stack()
copy_board.push(taken_move)
self.fail_safe_board = copy_board
if requested_move is None:
requested_move = NULL_MOVE
if taken_move is None:
taken_move = NULL_MOVE
logger.log(f"Handling move result at move {self.move} with requested move {requested_move} and taken move {taken_move} with captured opponent piece {captured_opponent_piece} and capture square {capture_square}")
new_boards = UniqueBoardList()
for board in self.boards:
# CASE I: we requested a move but it was illegal given the current board state, therefore we can remove all boards which think the requested move would be legal
if requested_move is not NULL_MOVE and taken_move is NULL_MOVE:
if board.is_legal(requested_move):
continue
# CASE II: if the taken move was not legal on our board state but clearly is on the actual board state, discard it
# THIS CURRENTLY HAS AN ERROR: CASTLING IN CHECK RETURNS is_legal = False but it should be true.
if taken_move != NULL_MOVE and not board.is_legal(taken_move):
continue
# CASE III: we made a capture but on the current board that move would have not been a capture
if captured_opponent_piece:
if not board.is_capture(taken_move):
continue
# SPECIAL III CASE I: we made a capture on boath boards but on the current board we thought that capture would be a king capture (the game is still going on therefore this is impossible)
piece_captured = board.piece_at(capture_square)
if piece_captured and piece_captured.piece_type == chess.KING:
continue
# SPEICAL III CASE II: en passant results in different taken_move.moveto vs capture_square (as illustrated here) rnbqkb1r/ppp2ppp/5n2/8/3pp2P/Q1K5/PPP2PP1/R1BN1BNR b kq - 15 13 --> We tried to take the king but actually ended up en-passanting the c-file pawn (on the current board - not the actual one)... lol
if capture_square != utilities.capture_square_of_move(board, taken_move):
continue
# CASE IV: we did not make a capture but on the current board that would have been a capture (inverse of III)
if not captured_opponent_piece:
if board.is_capture(taken_move):
continue
try:
board_copy = BoardUtils.fast_copy_board(board)
board_copy.push(taken_move)
kings = list(board_copy.pieces(chess.KING, self.color))
if len(kings) != 1:
logger.error(f"[ERROR] Duplicate king after move {taken_move} on board {board_copy.fen()}")
continue
new_boards.add(board_copy)
except Exception as e:
logger.error(f"Error pushing move {taken_move} on board {board.fen()}: {e}")
continue
if not len(self.boards) == 0 and len(new_boards) == 0:
logger.error("No boards available after handle_move_result")
self.boards = new_boards
# if not BoardUtils.check_own_pieces_consistency(self, self.boards):
# logger.error(f"[ERROR] Boards became inconsistent after function call handle_move_result")
def handle_game_end(self, winner_color: Optional[chess.Color], win_reason: Optional[WinReason],
game_history: GameHistory):
import csv
import os
from datetime import datetime
RESULTS_CSV_PATH = 'results_log.csv'
try:
self.engine.quit()
except chess.engine.EngineTerminatedError:
pass
try:
# Determine bot's color
played_as = 'white' if self.color == chess.WHITE else 'black'
won = (winner_color == self.color)
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
win_reason_str = str(win_reason).split('.')[-1] if win_reason else "unknown"
log_row = [timestamp, played_as, str(won), win_reason_str, self.opponent_name]
# Append result to CSV
file_exists = os.path.isfile(RESULTS_CSV_PATH)
with open(RESULTS_CSV_PATH, 'a', newline='') as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(['timestamp', 'played_as', 'won', 'win_reason', 'opponent_name'])
writer.writerow(log_row)
print(f"[LOG] Game ended at {timestamp} | Played as {played_as} | Won: {won} | Reason: {win_reason_str}")
except Exception as e:
print(f"[ERROR] Failed to log game result: {e}")
class UniqueBoardList:
"""
Class to store unique chess boards. It uses a set to keep track of seen FEN strings to ensure uniqueness.
This is useful for storing boards that have been generated during the game, ensuring that we don't have duplicates.
It's essentially just a List of chess.Board objects, but with a uniqueness constraint based on their FEN strings.
"""
def __init__(self, boards: List[chess.Board] = None):
self._boards = []
self._seen_fens = set()
if boards is not None:
for board in boards:
self.add(board)
def add(self, board: chess.Board):
fen = board.fen()
if fen not in self._seen_fens:
self._boards.append(board)
self._seen_fens.add(fen)
def extend(self, boards: List[chess.Board]):
for board in boards:
self.add(board)
def __iter__(self):
return iter(self._boards)
def __len__(self):
return len(self._boards)
def __getitem__(self, index):
return self._boards[index]
def random_sample_if_needed(self, sample_size: int):
"""
Return a random subset of boards sampled from the total list of boards if needed
"""
if len(self._boards) <= sample_size:
return self
logger.log(f"Sampling {sample_size} boards from {len(self._boards)} boards")
sampled_boards = UniqueBoardList(random.sample(self._boards, sample_size))
return sampled_boards
def clear(self):
self._boards.clear()
self._seen_fens.clear()