Created
March 11, 2024 20:42
-
-
Save fsndzomga/713bc868d53dbc17f5575535f2f4272d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Initialize a chess board and the chess engine | |
engine = chess.engine.SimpleEngine.popen_uci("/opt/homebrew/Cellar/stockfish/16/bin/stockfish") | |
# Configure Stockfish to a specific skill level, e.g., 10 | |
engine.configure({"Skill Level": 0}) | |
with open('learning_chess.txt', 'r') as file: | |
past_game_performance = file.read() | |
def play_game(): | |
moves = [] # Variable to store the list of moves | |
board = chess.Board() | |
def get_agent_move(board): | |
feedback = "" | |
while True: | |
prompt = f"""Current board: {board}\nMove history: {moves} | |
Choose the next move for black in UCI format. The available legal moves are {list(board.legal_moves)}. | |
The move you select should be among the legal moves in UCI format like this:'Move.from_uci('g7g5')' {feedback} Only reply with the move and nothing else. | |
Take into your past performance against stockfish: {past_game_performance}""" | |
# No streaming | |
response = chess_agent.invoke(prompt) | |
next_move = response.move | |
try: | |
move = chess.Move.from_uci(next_move) | |
if move in board.legal_moves: | |
return move | |
else: | |
feedback = f"Agent's generated move {move} is not valid currently." | |
except: | |
feedback = "Failed to parse the Agent's generated move. Retrying..." | |
while not board.is_game_over(): | |
if board.turn: # True for white's turn, False for black's turn | |
result = engine.play(board, chess.engine.Limit(time=2.0)) | |
board.push(result.move) | |
moves.append(result.move.uci()) # Store UCI move in the list | |
else: | |
move = get_agent_move(board) | |
board.push(move) | |
moves.append(move.uci()) # Store UCI move in the list | |
print(board) | |
print("\n\n") | |
# Check the result of the game | |
winner = "" | |
if board.is_checkmate(): | |
if board.turn: | |
winner = "Black" | |
else: | |
winner = "White" | |
elif board.is_stalemate() or board.is_insufficient_material() or board.is_seventyfive_moves() or board.is_fivefold_repetition() or board.is_variant_draw(): | |
winner = "Draw" | |
# Write the result in the short term memory | |
with open('learning_chess.txt', 'a') as file: | |
file.write(f"\n{' '.join(moves)} => Winner: {'AI Agent' if winner == 'Black' else 'Stockfish'}") | |
if winner == "Black": | |
return "Agent wins by checkmate." | |
elif winner == "White": | |
return "Stockfish wins by checkmate." | |
else: | |
return "The game is a draw." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment