def getNextMove(self, current_unit, current_layout): """ Run the chess engine with UCI communication to find the next move to draw for the user """ print('Next move for ' + current_unit) if ( not self.board.is_checkmate() ): #TODO add a you already won message and hooray ceremony if winning try: engine = chess.engine.SimpleEngine.popen_uci(get_engine_path()) # current_turn = self.board.epd().split(' ')[1] self.changeTurns(current_unit, current_layout) user_time_limit = int( SettingsManager().settings["Engine Time Limit"]) #TODO check if game finished , as it crashes the engine result = engine.play(self.board, chess.engine.Limit(time=user_time_limit)) print(result) self.board.push(result.move) self.last_move_image = show_move(str(result.move), self.out_board) self.window.updateBoard(self.board) engine.close() self.window.close() except OSError: print("Couldn't find your chess player") show_no_engine_msgbox()
def getEngineEval(): if token.validate_token(request.args.get('token', False)): __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) __filename__ = 'stockfish-prod' if os.environ.get( "Production", False) else 'stockfish-dev' # Assign game Position with chess.engine.SimpleEngine.popen_uci( os.path.join(__location__, __filename__)) as engine: try: fen_notation = request.args.get('fen_notation', "") board = chess.Board(fen_notation) except ValueError: return jsonify({ "fen_notation_error": "Please supply a valid fen notation", }) strength = request.args.get('strength', 1) time = min(1, 0.01 * 10**int(strength)) res = engine.play(board, chess.engine.Limit(time=time, depth=20)) info = engine.analyse(board, chess.engine.Limit(time=time, depth=20)) engine.close() return jsonify({ "best_move": str(res.move), "ponder": str(res.ponder), "evaluation": str(info["score"].white()), }) return jsonify({ "access_token_error": "There seems to be a problem with your access token", })
def coach_opinion(board, curr_move): engine = chess.engine.SimpleEngine.popen_uci("stockfish_20011801_x64.exe") curr_analyse = engine.analyse(board, chess.engine.Limit(depth=20)) curr_score = int(str(curr_analyse.score)) / 100 board.pop() prev_analyse = engine.analyse(board, chess.engine.Limit(depth=20), multipv=3) prev_score = int(str(prev_analyse[0].score)) / 100 best_move = prev_analyse[0]['pv'][0] very_good_move = prev_analyse[1]['pv'][0] good_move = prev_analyse[2]['pv'][0] result = "" final_result = "" if str(curr_move) == str(best_move): result = "Best Move!" elif str(curr_move) == str(very_good_move): result = "Very Good Move!" elif str(curr_move) == str(good_move): result = "Good Move!" else: if board.turn: if prev_score >= 0: if 0 < curr_score < prev_score: result = "Bad Move!" elif curr_score == 0: result = "Very Bad Move!" else: result = "Losing Move!" elif curr_score - prev_score >= -1.00: result = "Bad Move!" elif curr_score - prev_score >= -3.00: result = "Very Bad Move!" else: result = "Losing Move!" else: if prev_score < 0: if 0 > curr_score > prev_score: result = "Bad Move!" elif curr_score == 0: result = "Very Bad Move!" else: result = "Losing Move!" elif curr_score - prev_score <= 1.00: result = "Bad Move!" elif curr_score - prev_score <= 3.00: result = "Very Bad Move!" else: result = "Losing Move!" result += "(" + str(curr_score) + ")" final_result = result + " (The Best Move was " + str( best_move) + ", " + str( int(str(prev_analyse[0]['score'])) / 100) + " )" engine.close() board.push_uci(curr_move) return final_result
def main() -> None: sys.setrecursionlimit(10000) # else node.deepcopy() sometimes fails? args = parse_args() if args.verbose == 2: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) engine = make_engine(args.engine, args.threads) server = Server(logger, args.url, args.token, version) games = 0 site = "?" skip = int(args.skip) logger.info("Skipping first {} games".format(skip)) print(f'v{version} {args.file}') try: with open_file(args.file) as pgn: skip_next = False for line in pgn: if line.startswith("[Site "): site = line games = games + 1 elif games < skip: continue elif util.exclude_time_control(line) or util.exclude_rating( line): skip_next = True elif line.startswith("1. ") and skip_next: logger.debug("Skip {}".format(site)) skip_next = False elif "%eval" in line: game = chess.pgn.read_game( StringIO("{}\n{}".format(site, line))) assert (game) game_id = game.headers.get("Site", "?")[20:] if server.is_seen(game_id): logger.info( "Game was already seen before, skipping a bunch") skip = games + 1000 continue try: puzzle = analyze_game(server, engine, game) if puzzle is not None: logger.info( f'v{version} {args.file} {util.avg_knps()} knps, Game {games}' ) server.post(game_id, puzzle) except Exception as e: logger.error("Exception on {}: {}".format(game_id, e)) except KeyboardInterrupt: print(f'v{version} {args.file} Game {games}') sys.exit(1) engine.close()
def cruncher(thread_id: int): db = pymongo.MongoClient()['puzzler'] round_coll = db['puzzle2_round'] play_coll = db['puzzle2_puzzle'] engine = SimpleEngine.popen_uci('./stockfish') engine.configure({'Threads': 2}) for doc in round_coll.aggregate([{ "$match": { "_id": { "$regex": "^lichess:" }, "t": { "$nin": ['+zugzwang', '-zugzwang'] } } }, { '$lookup': { 'from': 'puzzle2_puzzle', 'as': 'puzzle', 'localField': 'p', 'foreignField': '_id' } }, { '$unwind': '$puzzle' }, { '$replaceRoot': { 'newRoot': '$puzzle' } }]): try: if ord(doc["_id"][4]) % threads != thread_id: continue puzzle = read(doc) round_id = f'lichess:{puzzle.id}' zug = zugzwang(engine, puzzle) if zug: cook.log(puzzle) round_coll.update_one({"_id": round_id}, { "$addToSet": { "t": "+zugzwang" if zug else "-zugzwang" } }) play_coll.update_one({"_id": puzzle.id}, {"$set": { "dirty": True }}) except Exception as e: print(doc) logger.error(e) engine.close() exit(1) engine.close()
def main(): driver = buka_selenium() pengguna, kata_sandi = Kredensial() masuk(driver, pengguna, kata_sandi) engine = chess.engine.SimpleEngine.popen_uci(lokasi_stockfish) main_lagi = 1 depth, otomatis_main = buka_pengaturan() while main_lagi: main_game(driver, engine, otomatis_main, depth) masukan = input("Ketik 'start' untuk lanjut suggest (ketika pertandingan sudah dimulai), atau ketik 'no' untuk keluar: ") if masukan == 'no': main_lagi = 0 driver.close() engine.close()
def main(): driver = startdriver() username, password = getCred() login(driver, username, password) #initialize engine engine = chess.engine.SimpleEngine.popen_uci(stockfish_loc) play_more = 1 depth, auto_start = read_options() while play_more: play_game(driver, engine, auto_start, depth) answer = input( "type 'start' when your next match starts, or type no to quit: ") if answer != 'start': play_more = 0 #auto_start = 1 driver.close() engine.close()
def main(): # initialize webdriver, game engine and login driver = startdriver() username, password = get_credentials() login(driver, username, password) engine = chess.engine.SimpleEngine.popen_uci(stockfish_loc) while True: # ask user if ready to play, if not, exit ready = input("Are you ready to play? (y/n): ") if ready == 'n': print("Goodbye!") driver.close() engine.close() return # play game play_game(driver, engine)
def main(): engine = chess.engine.SimpleEngine.popen_uci("/usr/games/stockfish") num_trials_per_pt = 2000 # extract parameters for pretrain chess, finetune chess, pretrain english, finetune commentary base_path = './ckpts/ckpts-through-time' parameter_paths = ['pretrain_chess.pt', 'finetune_chess.pt', 'pretrain_english.pt', 'finetune_commentary.pt'] for path in parameter_paths: print(f"Analysing {path}") ckpt_path = os.path.join(base_path, path) gpt_model, stoi, itos = initialise_model(ckpt_path) results = [] for _ in mdqt(range(num_trials_per_pt)): results.append(bot_vs_stockfish(gpt_model, itos, stoi, engine=engine)) # perform analytics on the results... print("Now computing seriously advanced analytics") analytics = analyse(results, engine) with open(f'./analytics/anal_{path}.anal', 'wb') as f: pickel.dump(analytics, f, pickel.HIGHEST_PROTOCOL) engine.close()
def main() -> None: sys.setrecursionlimit(10000) # else node.deepcopy() sometimes fails? args = parse_args() if args.verbose == 2: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) engine = make_engine(args.engine, args.threads) server = Server(logger, args.url, args.token, version) games = 0 site = "?" has_master = False tier = 0 skip = int(args.skip) logger.info("Skipping first {} games".format(skip)) parts = int(args.parts) part = int(args.part) print(f'v{version} {args.file} {part}/{parts}') try: with open_file(args.file) as pgn: skip_next = False for line in pgn: if line.startswith("[Site "): site = line games = games + 1 has_master = False tier = 4 elif games < skip: continue elif games % parts != part - 1: continue if tier == 0: skip_next = True elif line.startswith("[Variant ") and not line.startswith("[Variant \"Standard\"]"): skip_next = True elif ( (line.startswith("[WhiteTitle ") or line.startswith("[BlackTitle ")) and "BOT" not in line ): has_master = True else: r_tier = util.rating_tier(line) t_tier = util.time_control_tier(line) if r_tier is not None: tier = min(tier, r_tier) elif t_tier is not None: tier = min(tier, t_tier) elif line.startswith("1. ") and skip_next: logger.debug("Skip {}".format(site)) skip_next = False elif "%eval" in line: tier = tier + 1 if has_master else tier game = chess.pgn.read_game(StringIO("{}\n{}".format(site, line))) assert(game) game_id = game.headers.get("Site", "?")[20:] if server.is_seen(game_id): to_skip = 0 logger.info(f'Game was already seen before, skipping {to_skip} - {games}') skip = games + to_skip continue # logger.info(f'https://lichess.org/{game_id} tier {tier}') try: puzzle = analyze_game(server, engine, game, tier) if puzzle is not None: logger.info(f'v{version} {args.file} {part}/{parts} {util.avg_knps()} knps, tier {tier}, game {games}') server.post(game_id, puzzle) except Exception as e: logger.error("Exception on {}: {}".format(game_id, e)) except KeyboardInterrupt: print(f'v{version} {args.file} Game {games}') sys.exit(1) engine.close()
import os import sys import chess import chess.engine from brobot.train.dataset import build_serialized_data, parse_fen_row, parse_tuner, parse_fen_row_move, parse_tuner_move, build_serialized_data_from_bin, parse_fen_row_bin from brobot.train.utils import get_pos_rep, get_move_rep STOCKFISH_PATH = os.getenv('STOCKFISH_PATH', 'stockfish') engine = chess.engine.SimpleEngine.popen_uci(STOCKFISH_PATH) #build_serialized_data(sys.argv[1], sys.argv[2], parse_tuner(get_pos_rep, engine=engine, depth=0), verbose=True) #build_serialized_data(sys.argv[1], sys.argv[2], parse_fen_row(get_pos_rep), verbose=True) #build_serialized_data(sys.argv[1], sys.argv[2], parse_fen_row_move(get_pos_rep, get_move_rep), verbose=True) #build_serialized_data(sys.argv[1], sys.argv[2], parse_tuner_move(get_pos_rep, get_move_rep, engine=engine, depth=0), verbose=True) build_serialized_data_from_bin(sys.argv[1], sys.argv[2], parse_fen_row_bin(get_pos_rep), verbose=True, limit=1e6) engine.close()
def coach_opinion(board, curr_move): if board.is_game_over(): res = str(board.result()) if res == "1-0": return "White is Victorious! " + "(" + str(board.result()) + ")" elif res == "0-1": return "Black is Victorious!" + "(" + str(board.result()) + ")" else: return "The game has resulted in a Draw." + "(" + str(board.result()) + ")" engine = chess.engine.SimpleEngine.popen_uci("stockfish_20011801_x64.exe") curr_analyse = engine.analyse(board, chess.engine.Limit(depth=20)) curr_an_score = curr_analyse.score.pov(chess.WHITE) curr_val = str(curr_an_score) if not curr_an_score.is_mate(): curr_int = int(curr_val) curr_score = curr_int / 100 else: result = "" temp = board.pop() prev_analyse2 = engine.analyse(board, chess.engine.Limit(depth=20)) best_move2 = prev_analyse2['pv'][0] board.push(temp) chars = [] for i, char in enumerate(curr_val): chars.append(char) if chars[1] == '+': if not board.turn: result = "You can deliver Checkmate in " + chars[2] + " Moves!" else: result = "Opponent can force Checkmate in " + chars[2] + " moves!" elif chars[1] == '-': if board.turn: result = "Opponent can force Checkmate in " + chars[2] + " moves!" else: result = "You can deliver Checkmate in " + chars[2] + " Moves!" if not prev_analyse2.score.is_mate(): best_string = str(int(str(prev_analyse2.score.pov(chess.WHITE))) / 100) else: best_string = str(prev_analyse2.score.pov(chess.WHITE)) final_result = result + " (" + curr_val + ")" + " (The Best Move was " + str( best_move2) + ", " + best_string + ")." return final_result # print("debug: curr_score:"+str(curr_score)) temp = board.pop() prev_analyse = engine.analyse(board, chess.engine.Limit(depth=20)) good_moves = engine.analyse(board, chess.engine.Limit(depth=20), multipv=3) prev_an_score = prev_analyse.score.pov(chess.WHITE) prev_val = str(prev_an_score) board.push(temp) if not prev_an_score.is_mate(): prev_int = int(prev_val) prev_score = prev_int / 100 else: chars = [] for i, char in enumerate(prev_val): chars.append(char) result = "" if chars[1] == '+': if not board.turn: result = "You can deliver Checkmate in " + chars[2] + " Moves!" else: result = "Opponent can force Checkmate in " + chars[2] + " moves!" elif chars[1] == '-': if board.turn: result = "Opponent can force Checkmate in " + chars[2] + " moves!" else: result = "You can deliver Checkmate in " + chars[2] + " Moves!" if not prev_analyse.score.is_mate(): best_string = str(int(str(prev_analyse.score)) / 100) else: best_string = str(prev_analyse.score) try: best_move = str(prev_analyse.pv[0]) except IndexError: best_move = None final_result = result + " (" + curr_val + ")" + " (The Best Move was " + str( best_move) + ", " + best_string + ")." return final_result # print("debug: prev_score:"+str(prev_score)) # good_moves = engine.analyse(board, chess.engine.Limit(depth=20), multipv=3) # print("debug: "+str(prev_analyse[0].pv)) best_score = "" try: best_move = good_moves[0]['pv'][0] if not good_moves[0].score.is_mate(): best_score = str(int(str(good_moves[0].score.pov(chess.WHITE)))/100) else: best_score = str(good_moves[0].score.pov(chess.WHITE)) except IndexError: best_move = None try: very_good_move = good_moves[1]['pv'][0] except IndexError: very_good_move = None try: good_move = good_moves[2]['pv'][0] except IndexError: good_move = None if str(curr_move) == str(best_move): result = "Best Move!" elif str(curr_move) == str(very_good_move): result = "Very Good Move!" elif str(curr_move) == str(good_move): result = "Good Move!" else: if board.turn: if prev_score >= 0: if 0 < curr_score < prev_score: result = "Bad Move!" elif curr_score == 0: result = "Very Bad Move!" else: result = "Losing Move!" elif curr_score - prev_score >= -1.00: result = "Bad Move!" elif curr_score - prev_score >= -3.00: result = "Very Bad Move!" else: result = "Losing Move!" else: if prev_score < 0: if 0 > curr_score > prev_score: result = "Bad Move!" elif curr_score == 0: result = "Very Bad Move!" else: result = "Losing Move!" elif curr_score - prev_score <= 1.00: result = "Bad Move!" elif curr_score - prev_score <= 3.00: result = "Very Bad Move!" else: result = "Losing Move!" result += " (" + str(curr_score) + ")" final_result = result + " (The Best Move was " + str(best_move) + ", " + best_score + " )" engine.close() return final_result
def stock_eval(board): engine = chess.engine.SimpleEngine.popen_uci("stockfish.exe") info = engine.analyse(board, chess.engine.Limit(depth=3)) evaluation = int(info["score"].white().__str__()) engine.close() return evaluation
def main() -> None: sys.setrecursionlimit(10000) # else node.deepcopy() sometimes fails? args = parse_args() args.master = args.master or args.bullet if args.verbose == 2: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) engine = make_engine(args.engine, args.threads) server = Server(logger, args.url, args.token, version) games = 0 site = "?" has_master = False skip = int(args.skip) logger.info("Skipping first {} games".format(skip)) print(f'v{version} {args.file}') try: with open_file(args.file) as pgn: skip_next = False for line in pgn: if line.startswith("[Site "): site = line games = games + 1 has_master = False elif games < skip: continue elif ((line.startswith("[WhiteTitle ") or line.startswith("[BlackTitle ")) and "BOT" not in line): has_master = True elif util.reject_by_time_control(line, has_master=has_master, master_only=args.master, bullet=args.bullet, mates=args.mates): skip_next = True elif util.exclude_rating(line, args.mates): skip_next = True elif line.startswith("[Variant ") and not line.startswith( "[Variant \"Standard\"]"): skip_next = True elif line.startswith("1. ") and (skip_next or (args.master and not has_master)): logger.debug("Skip {}".format(site)) skip_next = False elif "%eval" in line: game = chess.pgn.read_game( StringIO("{}\n{}".format(site, line))) assert (game) game_id = game.headers.get("Site", "?")[20:] if server.is_seen(game_id): to_skip = 1000 logger.info( f'Game was already seen before, skipping {to_skip} - {games}' ) skip = games + to_skip continue try: puzzle = analyze_game(server, engine, game, args) if puzzle is not None: logger.info( f'v{version} {args.file} {util.avg_knps()} knps, Game {games}' ) server.post(game_id, puzzle) except Exception as e: logger.error("Exception on {}: {}".format(game_id, e)) except KeyboardInterrupt: print(f'v{version} {args.file} Game {games}') sys.exit(1) engine.close()