import chess import chess.engine from mytoken import apikey import json from simpleaichat import AIChat from pydantic import BaseModel, Field
BASE_PROMPT = """ Imagine you are a renowned chess master with decades of experience. A critical moment arises in a high-stakes tournament game. It's your turn to move, and you have multiple promising options on the board. How do you approach this situation? What factors do you consider when deciding which move to play? Share your expert analysis, evaluating the strengths and weaknesses of each candidate move and explaining the reasoning behind your final choice. Your insights and strategic guidance will be highly valued by aspiring chess players worldwide. Show us the brilliance of a true chess master! Make sure to anticipate how your adversary may react and plan at least five steps ahead of your opponent. Take into account the opening principles, positional considerations, coordination of pieces, threat assessment, and endgame strategies. Provide a comprehensive analysis that encompasses all stages of the game and showcases your expertise. Inspire chess enthusiasts around the globe with your strategic prowess and demonstrate how you would triumph in this critical moment." """
classget_move(BaseModel): """UCI move information""" move: str = Field(description="UCI move recommended") Strategy: str = Field(description="Explanation of the UCI move recommended")
# Initialize a chess board and the chess engine engine = chess.engine.SimpleEngine.popen_uci("/opt/homebrew/Cellar/stockfish/16/bin/stockfish")
defplay_game(): white_moves = [] # Variable to store the list of White's moves black_moves = [] # Variable to store the list of Black's moves board = chess.Board()
defget_gpt4_move(board): feedback = "" whileTrue: prompt = f"Current board: {board} White's move history: {white_moves}\nBlack's move history: {black_moves}\n\nChoose the next move for black in UCI format. The available legal moves are {list(board.legal_moves)}. {feedback}"
try: move = chess.Move.from_uci(next_move) if move in board.legal_moves: return move else: feedback = f"AI agent's generated move {move} is not valid currently." print(feedback) except: feedback = "Failed to parse AI agent's generated move. Retrying..." print(feedback)
whilenot 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) white_moves.append(result.move.uci()) # Store UCI move in the list else: move = get_gpt4_move(board) board.push(move) black_moves.append(move.uci()) # Store UCI move in the list print(board) print("\n\n")
# Check the result of the game if board.is_checkmate(): if board.turn: return"AI Agent wins by checkmate" else: return"Stockfish wins by checkmate" elif board.is_stalemate() or board.is_insufficient_material() or board.is_seventyfive_moves() or board.is_fivefold_repetition() or board.is_variant_draw(): return"The game is a draw" else: return"The game is not over"
engine.quit()
# Run the game 10 times and store results results = {"AI agent wins by checkmate": 0, "Stockfish wins by checkmate": 0, "The game is a draw": 0, "The game is not over": 0}
for i inrange(5): result = play_game() results[result] += 1