I have a small python script that uses the chess library. It simply iterates all possible games from the starting set of legal moves. It ends a branch when the maximum plies is hit, or when a check mate is found. Additionally, it will log the game if it was a checkmate.
import chess
import chess.pgn
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(message)s',
filename='chess_game_exploration.log', # Log to this file
filemode='w' # Overwrite the log file every time the script runs
)
logger = logging.getLogger()
checkmate_count = 0
total_games_count = 0
def save_game(board, current_moves):
with open("checkmates.pgn", "a") as pgn_file:
game = chess.pgn.Game.from_board(board)
game.headers["Event"] = "Checkmate Search"
game.headers["PlyCount"] = str(len(current_moves))
pgn_file.write(str(game) + "nn")
def explore_games(board, current_moves, max_plies=5):
global checkmate_count, total_games_count
# Check if we hit checkmate
if board.is_checkmate():
checkmate_count += 1
total_games_count += 1
print("Check Mate Found")
save_game(board, current_moves)
return
total_games_count += 1
if total_games_count % 100000 == 0:
logger.info(f"Total games: {total_games_count} Total checkmates: {checkmate_count}")
# Stop if the maximum plies (moves) are reached
if len(current_moves) >= max_plies:
return
# Recursively explore each legal move
for move in board.legal_moves:
board.push(move)
explore_games(board.copy(), current_moves + [move], max_plies)
board.pop() # Undo the move for backtracking
logger.info("Starting chess game exploration.")
board = chess.Board()
explore_games(board, [], max_plies=5) # Set a reasonable number of plies (maximum moves)
logger.info(f"Total checkmates found: {checkmate_count}")
logger.info(f"Total full games computed: {total_games_count}")
My question is, how can I save out some kind of state, that can later be reloaded. This would be a long running process. As such, its likely the machine will be rebooted, or the script may need to be moved or modified and restarted. In those cases, I would want to begin the search again where it left off, without starting over.
1