"""Local browser board for Arkon Engine 0.1.""" import argparse import atexit import json import os import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from threading import Lock, Timer import webbrowser from arkon import NAME, RANDOM_NAME, ROOT, TEACHER, WEIGHTS, Player, RandomPlayer, chess HOST = "127.0.0.1:8793" PLAYER = None PLAYER_NAME = NAME PLAYER_WEIGHTS = WEIGHTS STOCKFISH = None PONDER_TIMER = None PONDER_GAME = None PONDER_EXPECTED = None DEEP_PLAYER = None BASE_PLAYER = None LOCK = Lock() MAX_SECONDS = 5 def stop_pondering(game=None): global PONDER_TIMER, PONDER_GAME, PONDER_EXPECTED if game is not None and game != PONDER_GAME: return if PONDER_TIMER is not None: PONDER_TIMER.cancel() if PONDER_GAME is not None and STOCKFISH is not None: STOCKFISH.ping() PONDER_TIMER = PONDER_GAME = PONDER_EXPECTED = None def expire_pondering(game, expected): with LOCK: if PONDER_GAME == game and PONDER_EXPECTED == expected: stop_pondering(game) def stockfish_move(board, strong=False, ponder_game=None): global STOCKFISH, PONDER_TIMER, PONDER_GAME, PONDER_EXPECTED if STOCKFISH is None: if not TEACHER.is_file(): raise RuntimeError("Stockfish fehlt im lokalen Engine-Ordner.") engine = chess.engine.SimpleEngine.popen_uci(str(TEACHER)) atexit.register(engine.close) STOCKFISH = engine options = {"Threads": os.cpu_count() or 1, "Hash": 512} if strong else {"Threads": 1, "Hash": 32} previous = PONDER_EXPECTED if ponder_game is not None and PONDER_GAME == ponder_game else None if PONDER_TIMER is not None: PONDER_TIMER.cancel() PONDER_TIMER = PONDER_GAME = PONDER_EXPECTED = None result = STOCKFISH.play(board, chess.engine.Limit(time=MAX_SECONDS if strong else 0.25), game=ponder_game, ponder=ponder_game is not None, options=options, info=chess.engine.INFO_BASIC) stats = {"engine": "Stockfish", **{key: result.info[key] for key in ("depth", "nodes") if key in result.info}} if previous is not None: stats["ponder_hit"] = tuple(board.move_stack) == previous if ponder_game is not None and result.move and result.ponder: PONDER_GAME = ponder_game PONDER_EXPECTED = (*board.move_stack, result.move, result.ponder) PONDER_TIMER = Timer(15, expire_pondering, args=(ponder_game, PONDER_EXPECTED)) PONDER_TIMER.daemon = True PONDER_TIMER.start() stats["prediction"] = result.ponder.uci() return result.move, stats def position(moves, reply=False, match=False, strong=False, ponder_game=None, pro_color=None): global DEEP_PLAYER, BASE_PLAYER board = chess.Board() for move in moves: board.push_uci(move) search_info = None if (match or (reply and board.turn == chess.BLACK)) and not board.is_game_over(claim_draw=True): with LOCK: if pro_color is not None: if BASE_PLAYER is None: BASE_PLAYER = Player("cpu", WEIGHTS) move = (PLAYER if board.turn == pro_color else BASE_PLAYER).choose(board) elif match and board.turn == (ponder_game is not None): move, search_info = stockfish_move(board, strong, ponder_game) elif strong and PLAYER_WEIGHTS is not None: if DEEP_PLAYER is None: from deep_search import DeepPlayer DEEP_PLAYER = DeepPlayer("cuda", PLAYER_WEIGHTS) move, search_info = DEEP_PLAYER.choose_timed(board, MAX_SECONDS) search_info["engine"] = PLAYER_NAME else: move = PLAYER.choose(board) if move not in board.legal_moves: raise RuntimeError("Die Engine hat keinen legalen Zug geliefert.") board.push(move) if ponder_game is not None and board.is_game_over(claim_draw=True): stop_pondering(ponder_game) outcome = board.outcome(claim_draw=True) move_sounds = [] recent = board.copy() for _ in range(min(2, len(recent.move_stack))): check = recent.is_check() move = recent.pop() move_sounds.append("check" if check else "capture" if recent.is_capture(move) else "move") return { "engine_name": PLAYER_NAME, "search_seconds": MAX_SECONDS, "pieces": {chess.square_name(square): piece.symbol() for square, piece in board.piece_map().items()}, "moves": [move.uci() for move in board.move_stack], "san": chess.Board().variation_san(board.move_stack) if board.move_stack else "", "legal": [] if outcome or not board.turn else [move.uci() for move in board.legal_moves], "result": outcome.result() if outcome else None, "check": board.is_check(), "sounds": list(reversed(move_sounds)), "search": search_info, } class Handler(BaseHTTPRequestHandler): def send_body(self, status, body, content_type): self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(body) def send_json(self, status, data): self.send_body(status, json.dumps(data).encode(), "application/json") def do_GET(self): if self.headers.get("Host") != HOST: return self.send_error(403) if self.path in ("/", "/?match=1", "/?match=max", "/?match=ponder", "/?match=pro", "/?match=pro-black"): return self.send_body(200, (ROOT / "play.html").read_bytes(), "text/html; charset=utf-8") if self.path == "/game": return self.send_json(200, position([])) if self.path.startswith("/pieces/"): name = self.path.removeprefix("/pieces/") if name in {f"{color}{piece}.svg" for color in "wb" for piece in "KQRBNP"}: return self.send_body(200, (ROOT / "pieces" / name).read_bytes(), "image/svg+xml") self.send_error(404) def do_POST(self): if (self.path not in ("/game", "/match", "/match-max", "/match-ponder", "/match-pro", "/match-pro-black", "/ponder-stop") or self.headers.get("Host") != HOST or self.headers.get("Origin", f"http://{HOST}") != f"http://{HOST}" or self.headers.get_content_type() != "application/json"): return self.send_error(403) try: length = int(self.headers.get("Content-Length", "0")) if not 0 < length <= 8192: raise ValueError("Ungültige Anfrage.") moves = json.loads(self.rfile.read(length)) ponder_game = None if self.path in ("/match-ponder", "/ponder-stop"): if not isinstance(moves, dict): raise ValueError("Ungültige Partie.") ponder_game = str(uuid.UUID(moves.get("game", ""))) if self.path == "/ponder-stop": with LOCK: stop_pondering(ponder_game) return self.send_json(200, {}) moves = moves.get("moves") match = self.path != "/game" pro_color = {"/match-pro": chess.WHITE, "/match-pro-black": chess.BLACK}.get(self.path) if pro_color is not None and PLAYER_NAME != "Arkon Engine 0.1 Pro": raise RuntimeError("Dieses Duell benötigt die Pro-Gewichte.") if (not isinstance(moves, list) or (not match and len(moves) % 2 != 1) or len(moves) > 600 or any(not isinstance(move, str) or len(move) not in (4, 5) for move in moves)): raise ValueError("Ungültige Zugliste.") self.send_json(200, position(moves, reply=True, match=match, strong=self.path in ("/match-max", "/match-ponder"), ponder_game=ponder_game, pro_color=pro_color)) except (ValueError, TypeError, AttributeError) as error: self.send_json(400, {"error": str(error)}) except (RuntimeError, OSError, chess.engine.EngineError) as error: self.send_json(503, {"error": str(error)}) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--port", type=int, default=8793) parser.add_argument("--open", action="store_true", help="Open the board in your browser.") parser.add_argument("--weights", type=type(WEIGHTS), default=WEIGHTS) parser.add_argument("--name") parser.add_argument("--random", action="store_true", help="Play uniformly random legal moves.") parser.add_argument("--search-seconds", type=int, default=MAX_SECONDS) args = parser.parse_args() if not 1 <= args.port <= 65535: parser.error("Port must be between 1 and 65535.") if args.search_seconds < 1: parser.error("Search time must be positive.") HOST = f"127.0.0.1:{args.port}" PLAYER_NAME = args.name or (RANDOM_NAME if args.random else NAME) PLAYER_WEIGHTS = None if args.random else args.weights MAX_SECONDS = args.search_seconds PLAYER = RandomPlayer() if args.random else Player("cpu", args.weights) with ThreadingHTTPServer(("127.0.0.1", args.port), Handler) as server: print(f"{PLAYER_NAME}: http://{HOST}/", flush=True) if args.open: webbrowser.open(f"http://{HOST}/") server.serve_forever()