def __initial_game(self): # self.parent.withdraw() self.parent.destroy() self.tabuleiro = ChessMatch.ChessMatch(self.bot_color) self.stockfish = Stockfish("./src/cpu/stockfish_20090216_x64") self.stockfish.set_skill_level(0) self.game_gui = Game(self.tabuleiro, self.stockfish)
def __init__(self, controller="random", customFunction=None): # "random", "gp", "alphazero", "*anyother we're planning to implement" self.controller = controller self.customFunction = customFunction # add any other variables as needed self.stockfish = Stockfish( './stockfish-10-win/Windows/stockfish_10_x64.exe')
def evaluation_from_board(board: chess.Board, evaluation_depth: int = 22) -> Dict: board_fen = board.fen() stockfish = Stockfish("/opt/homebrew/Cellar/stockfish/13/bin/stockfish") stockfish.set_depth(evaluation_depth) # set engine depth stockfish.set_fen_position(board_fen) return stockfish.get_evaluation()
def Score(fen): stockfish = Stockfish("./stockfish_20090216_x64.exe", parameters={ "Write Debug Log": "false", "Contempt": 0, "Min Split Depth": 30, "Threads": 1, "Ponder": "false", "Hash": 16, "MultiPV": 1, "Skill Level": 20, "Move Overhead": 30, "Minimum Thinking Time": 20, "Slow Mover": 84, "UCI_Chess960": "false",} ) stockfish.set_fen_position(fen) score = stockfish.get_evaluation() print(score) # fen = "2N5/8/2Q5/4k2p/1R6/7P/6P1/7K b - - 4 66" # engine = init_stockfish_engine() # print(StockfishScore(fen, engine)) # Score(fen) # engine.quit()
def stockFish_init(request): stockfish = Stockfish(parameters={ "Threads": 2, "Minimum Thinking Time": 30 }) stockfish.set_position(["e2e4", "e7e6"]) #posición de Forsyth–Edwards Notation (FEN) stockfish.set_fen_position( "rnbqkbnr/pppp1ppp/4p3/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2") #coge el mejor movimiento stockfish.get_best_move( ) #stockfish.get_best_move_time(1000) en base al tiempo #nivel del motor stockfish.set_skill_level(15) #parámetros por defecto stockfish.get_parameters() #coge la posición FEN stockfish.get_fen_position() #coge el tablero por defecto del usuario stockfish.get_board_visual() #evalua jugada stockfish.get_evaluation() p = subprocess.Popen('stockfish-x64.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) p.stdin.write("position startpos moves e2e4 e7e5\n") p.stdin.write("go infinite\n") p.stdin.flush() time.sleep(1) print(p.communicate())
def __init__(self, game, level): self.game = game self.engine = Stockfish('engines/stockfish', parameters={ "Threads": 4, "Skill Level": level })
def __init__(self): self.best_move = '' self.stockfish = Stockfish( "stockfish_14_linux_x64_avx2/stockfish_14_x64_avx2") self.positions2 = "" self.pos_temp = 0 self.curr_position = (Fen().start_position_list()).copy()
def __init__(self, first: bool, host: str, port: int, skill_level: Optional[int], depth: Optional[int], stockfish: Optional[str]): """ Initialize a player. Args: first: Is the player going first. host: The host of the game. port: The port in the host of the game. skill_level: Still level for stockfish. depth: Depth to search for best move for stockfish. stockfish: Path to the stockfish executable to use. """ self.player_turn = first self.host = host self.port = port self.skill_level = skill_level self.depth = depth self.moves = [] self.socket = None self.stockfish = Stockfish(stockfish or "./stockfish") if self.skill_level is not None: self.stockfish.set_skill_level(self.skill_level) if self.depth is not None: self.stockfish.set_depth(self.depth)
def test_get_best_move_wrong_position(self): wrong_fen = "3kk3/8/8/8/8/8/8/3KK3 w - - 0 0" s = Stockfish() s.set_fen_position(wrong_fen) assert s.get_best_move() in ( "d1e2", "d1c1", )
def __init__(self): self.stockfish = Stockfish("./stockfish") self.knn_clf = joblib.load("train/model.pkl") #The board size. Should be 320 because thats what the model has been trained on self.board_size = 320 self.checking = False self.bot_turn = True
def __init__(self) -> None: self.path = "stockfish.exe" if sys.platform == "win32" else "stockfish" try: Stockfish(self.path) except FileNotFoundError: print( f"cannot find stockfish executable. try putting one as `{self.path}` in the path" ) exit(-1)
def initEngine(self): self.moves = [] self.stockfish = Stockfish(None, 10, { 'Skill Level': 2500, 'Threads': 4 }) self.stockfish.set_position([]) self.fetchBoard() self.printBoard()
def bot_move(self): stfish = Stockfish('stockfish') stfish.set_fen_position(self.fen()) if self.board.turn: stfish.depth = self.white_bot_power else: stfish.depth = self.black_bot_power move = stfish.get_best_move() return self.make_move(move)
def get_best_move(board): stockfish = Stockfish() move_list = [] for move in board.moves: move_list.append(move.to_long_algebraic()) stockfish.set_position(move_list) return long_algebraic_to_coordinate(stockfish.get_best_move())
def start_game(self, uid: UUID, opts: GameOptions) -> ChessGame: if opts.ai_is_white is None: raise NotImplementedError( "not using stockfish is not currently implimented") self.games[uid] = ChessGame( stockfish=Stockfish(self.path), timer=asyncio.get_event_loop().create_task( delete_match_in(self, uid)), ) return self.games[uid]
def test_stockfish_easy_mate(self): # Test that it finds mate in 2 stockfish_engine = Stockfish("/usr/games/stockfish") position_mate_in_two = "r2qb1rk/ppb2p1p/2n1pPp1/B3N3/2B1P2Q/2P2R2/1P4PP/7K w - - 0 1" stockfish_engine.set_fen_position(position_mate_in_two) proposed_moves = stockfish_engine.get_top_moves() self.assertEqual({ 'Move': 'h4h7', 'Centipawn': None, 'Mate': 2 }, proposed_moves[0])
def generate_random_advantage_position(evaluation_depth: int): stockfish = Stockfish("/opt/homebrew/Cellar/stockfish/13/bin/stockfish") stockfish.set_depth(evaluation_depth) # set engine depth while True: board = chess.Board() end_game = False for i in range(random.randint(10, 200)): move = random.choice(list(board.legal_moves)) board.push(move) if board.is_game_over(): end_game = True print("Final position") break if not end_game: board_fen = board.fen() stockfish.set_fen_position(board_fen) position_evaluation = stockfish.get_evaluation() print( f"Position_evaluation: {position_evaluation}, fen = {board_fen}" ) if position_evaluation['type'] == 'cp' and abs( position_evaluation["value"]) < 300 and abs( position_evaluation["value"] ) > 1000: # rule out when no big advantage print( f"position_evaluation: {position_evaluation}. Passing: rule out when no big advantage" ) pass elif position_evaluation['type'] == 'mate' and position_evaluation[ 'value'] <= 1: # rule out mate in 1 print( f"position_evaluation: {position_evaluation}. Passing: rule out mate in 1" ) pass else: if board.turn == chess.WHITE and position_evaluation[ "value"] <= 0: # not an advantage white print(f"Turn: {board.turn}") print( f"position_evaluation: {position_evaluation}. Passing: not an advantage for white" ) pass elif board.turn == chess.BLACK and position_evaluation[ "value"] >= 0: # not an advantage black print(f"Turn: {board.turn}") print( f"position_evaluation: {position_evaluation}. Passing: not an advantage for black" ) pass else: yield board, board_fen, position_evaluation
def _get_engine(engine_type, engine_params=None): if engine_type == c.EngineType.stockfish: from stockfish import Stockfish # TODO: Added parameter for the engine here if engine_params is not None: pass return Stockfish() elif engine_type == c.EngineType.leela: raise NotImplementedError('Leela chess engine is not implelemented') else: error_msg = f"Unsupported engine {engine_type}" raise RuntimeError(error_msg)
def play(self): dirname = os.path.dirname(__file__) filename = os.path.join(dirname, 'stockfish-9-win\Windows\stockfish_9_x64') stockfish = Stockfish(filename) stockfish.set_skill_level(15) if not self.chessboard.is_game_over() and not self.chessboard.is_stalemate(): board = self.chessboard.fen() stockfish.set_fen_position(board) ai_move = stockfish.get_best_move() move = chess.Move.from_uci(ai_move) print(move) self.chessboard.push(move) self.update()
def gen_examples(randomness: float = 0.7, randomness_decline: float = 0.95, max_moves: int = 80, table: str = c.DEFAULT_TABLE) -> None: """ Generates training examples using Stockfish and stores them in a database in algebraic notation. Set up a MySQL database first and set the connection in constants.py. Also make sure that Stockfish is installed correctly. :param table: Table the data is stored in. :param randomness: Starting Probability for proceeding with are random move instead of the best move. This is necessary to not simulate the same game each time. :param randomness_decline: Factor applied to the randomness with each move. Should be less than 1 to have less randomness later in the game. :param max_moves: Stops the simulated game early to prevent too long end games. """ game = Game() stockfish = Stockfish(c.STOCKFISH_PATH) examples = [] moves = [] for _ in range(max_moves): stockfish.set_position(moves) best_move = stockfish.get_best_move() value = _value(stockfish.get_evaluation()) if best_move: examples.append((_truncate_fen(stockfish.get_fen_position()), (best_move[:4], value))) if best_move and random.random() > randomness: move_alg = best_move move_tuple = _from_algebraic(move_alg) else: move_tuple = random.sample(game.game_legal_moves(), 1)[0] move_alg = _to_algebraic(move_tuple) if len(move_alg) == 5: print('pawn promotion') try: game.make_move(move_tuple[0], move_tuple[1]) moves.append(move_alg) except ValueError: moves[-1] = moves[-1] + 'q' print(examples) randomness *= randomness_decline if game.game_winner(): break db = Connector() db.insert_examples(examples, table)
def main(): #Deteremine start random.seed(datetime.now()) white = random.randint(0, 1) #initialize board and stockfish board = chess.Board() fishy = Stockfish( '/Users/vishalaiely/Downloads/stockfish-11-mac/Mac/stockfish-11-64') if white: #playsound.playsound('audio/WhiteStart.mp3') speak('Hello, you have the white pieces') else: #playsound.playsound('audio/BlackStart.mp3') speak('Hello, you have the black pieces') #Game executes and breaks when over while not board.is_game_over(): if white: board.push_uci(playermove(board)) fishy.set_fen_position(board.fen()) compMove = fishy.get_best_move() board.push_uci(compMove) speak(compMove) else: fishy.set_fen_position(board.fen()) compMove = fishy.get_best_move() board.push_uci(compMove) speak(compMove) board.push_uci(playermove(board)) #Determines end state of game if board.result() is '1-0': #playsound.playsound('audio/WhiteWin.mp3') speak('White wins') elif board.reset() is '0-1': #playsound.playsound('audio/BlackWin.mp3') speak('Black wins') elif board.is_stalemate(): speak('Stalemate') else: speak('Draw') speak('Thank you for playing!')
def create_app(args={}): config = {} # There is also config file loading that comes with json from flask's library # especially if you don't like this hacky code data = {} if CONFIG_PATH_DEST in args: print(f"Loading config file from {args[CONFIG_PATH_DEST]}") with open(args[CONFIG_PATH_DEST], "r") as configFile: data = json.load(configFile) # From Config File utils.safe_dict_copy(config, ["host"], data, ["api", "host"], "0.0.0.0") utils.safe_dict_copy(config, ["port"], data, ["api", "port"], 8000) utils.safe_dict_copy( config, ["stockfish-path"], data, ["api", "stockfish", "path"], "/usr/games/stockfish", ) utils.safe_dict_copy(config, ["stockfish-depth"], data, ["api", "stockfish", "depth"], 15) utils.safe_dict_copy(config, ["stockfish-params"], data, ["api", "stockfish"], {}) utils.safe_dict_copy(config, ["flask"], data, ["api", "flask"], {}) utils.safe_dict_copy(config, ["log-query"], data, ["api", "log-query"], True) utils.safe_dict_copy(config, ["db"], data, ["api", "db_uri"]) # From CLI Args utils.safe_dict_copy(config, ["db"], args, ["db"], "sqlite:///storage.db") query.init(config["db"], config["log-query"]) global stockfish_app stockfish_app = Stockfish( path=config["stockfish-path"], depth=config["stockfish-depth"], parameters=config["stockfish-params"], ) app = Flask(__name__) app.config.update(config["flask"]) app.register_blueprint(root) global logger logger = app.logger logger.setLevel(logging.DEBUG) return app
def insertFEN(self, fen): """Is inserting FEN into sqlite :param fen: chess position in Forsyth-Edwards-Notation (FEN), e.g. r4rnk/1pp4p/3p4/3P1b2/1PPbpBPq/8/2QNB1KP/1R3R2 w KQkq - 0 25 """ self.cursor.execute("select count(*) from FEN where fen = ?;", [fen]) data = self.cursor.fetchone()[0] if data == 0: stockfish = Stockfish('/usr/games/stockfish') stockfish.set_fen_position(fen) bestmove = stockfish.get_best_move() try: self.cursor.execute("insert into FEN(fen, bestmove) values(?,?);", (str([fen]), bestmove)) except sqlite3.IntegrityError: pass
def __init__(self): abs_path = os.path.dirname(__file__) # local path rel_path = 'stockfish-10-win/stockfish-10-win/stockfish_x86-64-modern.exe' self.sf = Stockfish(os.path.join( abs_path, rel_path)) # pull the engine from compiled file self.m_skill_level = 0 # skill level of engine self.m_cur_turn = 0 # 0 for player turn, 1 for computer turn self.m_in_game = False # see if we're still in game self.m_move_his = [] # move history to update position in stockfish self.num_moves = 0 # number of moves (extraneous, may remove) self.set_skill_level( self.request_skill_level()) # request a skill level for engine self.choose_side(self.request_side()) # request a starting side self.m_starting_side = 0 self.m_board = Board(self.m_cur_turn)
def find_forced_mate_positions(library, mate_in=2, limit=100): """Finds up to limit forced mates and returns the FEN position + description.""" stockfish_engine = Stockfish("/usr/games/stockfish") forced_mate_boards = [] for i, game in enumerate(library.df.Game.values): # For everygame... if len(forced_mate_boards) == limit: break forced_mate_tuple = find_forced_mate( game, stockfish_engine, extra_description= f"[{library.df.iloc[i]['opening_chesscom_general']}]") if forced_mate_tuple[0] is not None: forced_mate_boards.append(forced_mate_tuple) return forced_mate_boards
def test_stockfish_constructor_with_custom_params(self): stockfish = Stockfish(parameters={"Skill Level": 1}) assert stockfish.get_parameters() == { "Write Debug Log": "false", "Contempt": 0, "Min Split Depth": 0, "Threads": 1, "Ponder": "false", "Hash": 16, "MultiPV": 1, "Skill Level": 1, "Move Overhead": 30, "Minimum Thinking Time": 20, "Slow Mover": 80, "UCI_Chess960": "false", }
def __init__(self, stockfishpath): conf = { "Write Debug Log": "false", "Contempt": 0, "Min Split Depth": 0, "Threads": 1, "Ponder": "false", "Hash": 16, "MultiPV": 1, "Skill Level": 20, "Move Overhead": 30, "Minimum Thinking Time": 20, "Slow Mover": 80, "UCI_Chess960": "false", } self.stockfish = Stockfish(stockfishpath, parameters=conf)
def play_engine(self, level=1, depth=3, number_games=10): """ This function will evaluate our agent against Stockfish :param number_games: The number of games to be played against Stockfish :param level: Level of Stockfish :return: """ stockfish = Stockfish('engines/stockfish.exe', parameters={ "Threads": 4, "Skill Level": level }) for i in range(number_games): game = chess.pgn.Game() game.headers["Event"] = "Evalutation DeepYed vs Stockfish" game.headers["Site"] = "My PC" game.headers["Date"] = str(datetime.datetime.now().date()) game.headers["Round"] = str(i + 1) game.headers["White"] = "DeepYed" game.headers["Black"] = 'Stockfish' while not self.board.is_game_over(): if self.board.turn: print("DeepYed's Turn") move = self.select_move(depth=depth) self.history.append(move) self.board.push(move) print(move) else: print("Stockfish's Turn") move = chess.Move.from_uci(self.play_stockfish(stockfish)) self.history.append(move) self.board.push(move) print(move) game.add_line(self.history) game.headers["Result"] = str(self.board.result()) print(game) print(game, file=open(f"Heuristic/level_{level}_round_{i+1}.pgn", "w"), end="\n\n") self.show_board()
def __init__(self, skill_level): parameters = { "Write Debug Log": "false", "Contempt": 0, "Min Split Depth": 0, "Threads": 1, "Ponder": "false", "Hash": 16, "MultiPV": 1, "Skill Level": skill_level, "Move Overhead": 30, "Minimum Thinking Time": 20, "Slow Mover": 80, "UCI_Chess960": "false", } self.engine = Stockfish("resources/stockfish.exe", parameters=parameters) self.engine.set_depth(ENGINE_DEPTH)
def __init__(self, stockfish, player_color=Game.WHITE, board=None, date=None, stockfish_depth=10): super().__init__(board=board, player_color=player_color, date=date) if stockfish is None: raise ValueError('A Stockfish object or a path is needed.') self.stockfish = stockfish stockfish_color = not self.player_color if type(stockfish) == str: self.stockfish = Stockfish(stockfish_color, stockfish, search_depth=stockfish_depth) elif type(stockfish) == Stockfish: self.stockfish = stockfish