| @@ -0,0 +1,320 @@ |
| 1 | +"""Eröffnungsexplorer in der Seitenleiste: lokales Buch und Lichess Opening Explorer. |
| 2 | + |
| 3 | +Buch: PyChess-Eröffnungsbuch, zeigt wie oft ein Zug im Buch steht (Polyglot kennt |
| 4 | +keine Ergebnisse). Lichess: was Spieler ähnlicher Wertung tatsächlich ziehen, mit |
| 5 | +Balken Weiß/Remis/Schwarz – braucht eine Lichess-Anmeldung. |
| 6 | + |
| 7 | +Während Lichess-Partien und ungelöster Rätsel bleibt der Explorer leer (Fair Play). |
| 8 | +""" |
| 9 | + |
| 10 | +import dataclasses |
| 11 | + |
| 12 | +import chess |
| 13 | +import gi |
| 14 | + |
| 15 | +gi.require_version("Gtk", "4.0") |
| 16 | +gi.require_version("Adw", "1") |
| 17 | +from gi.repository import Adw, GLib, Gtk # noqa: E402 |
| 18 | + |
| 19 | +from . import lichess, notation # noqa: E402 |
| 20 | + |
| 21 | +EXPLORER_URL = "https://explorer.lichess.ovh/lichess" |
| 22 | +RATING_BUCKETS = [0, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2500] |
| 23 | +SPEEDS = "blitz,rapid,classical" |
| 24 | +MAX_ROWS = 12 |
| 25 | +FETCH_DELAY_MS = 350 # erst abfragen, wenn man beim Blättern kurz stehen bleibt |
| 26 | + |
| 27 | +WHITE_RGB = (0.96, 0.96, 0.95) |
| 28 | +DRAW_RGB = (0.62, 0.62, 0.64) |
| 29 | +BLACK_RGB = (0.24, 0.22, 0.27) |
| 30 | + |
| 31 | + |
| 32 | +@dataclasses.dataclass |
| 33 | +class Line: |
| 34 | + move: chess.Move |
| 35 | + games: int |
| 36 | + white: int = 0 |
| 37 | + draws: int = 0 |
| 38 | + black: int = 0 |
| 39 | + share: float = 0.0 # Anteil an allen Partien bzw. am Buchgewicht, 0–1 |
| 40 | + |
| 41 | + |
| 42 | +# --- Logik (ohne GTK, getestet) --------------------------------------------- |
| 43 | + |
| 44 | +def book_lines(book, board): |
| 45 | + moves = book.moves(board) |
| 46 | + total = sum(w for _m, w in moves) or 1 |
| 47 | + return [Line(m, w, share=w / total) for m, w in moves[:MAX_ROWS]] |
| 48 | + |
| 49 | + |
| 50 | +def lichess_lines(data, board): |
| 51 | + rows = [] |
| 52 | + entries = [e for e in data.get("moves", []) if e.get("uci")] |
| 53 | + total = sum(e.get("white", 0) + e.get("draws", 0) + e.get("black", 0) for e in entries) or 1 |
| 54 | + for entry in entries[:MAX_ROWS]: |
| 55 | + try: |
| 56 | + move = board.parse_uci(entry["uci"]) # wandelt Lichess' König-schlägt-Turm (e1h1) in e1g1 |
| 57 | + except ValueError: |
| 58 | + continue |
| 59 | + games = entry.get("white", 0) + entry.get("draws", 0) + entry.get("black", 0) |
| 60 | + rows.append(Line(move, games, entry.get("white", 0), entry.get("draws", 0), entry.get("black", 0), |
| 61 | + share=games / total)) |
| 62 | + return rows |
| 63 | + |
| 64 | + |
| 65 | +def ratings_near(elo): |
| 66 | + """Zwei Lichess-Wertungsstufen um ``elo`` – „Spieler ähnlicher Stärke“.""" |
| 67 | + below = max(b for b in RATING_BUCKETS if b <= max(elo, 0)) |
| 68 | + index = RATING_BUCKETS.index(below) |
| 69 | + return RATING_BUCKETS[index:index + 2] if index + 1 < len(RATING_BUCKETS) else RATING_BUCKETS[-2:] |
| 70 | + |
| 71 | + |
| 72 | +def games_text(n): |
| 73 | + if n >= 1_000_000: |
| 74 | + return f"{n / 1_000_000:.1f} Mio.".replace(".", ",", 1) |
| 75 | + if n >= 10_000: |
| 76 | + return f"{n // 1000} Tsd." |
| 77 | + return f"{n:,}".replace(",", ".") |
| 78 | + |
| 79 | + |
| 80 | +def percent(part, whole): |
| 81 | + return round(100 * part / whole) if whole else 0 |
| 82 | + |
| 83 | + |
| 84 | +# --- Oberfläche -------------------------------------------------------------- |
| 85 | + |
| 86 | +class ExplorerList(Gtk.Box): |
| 87 | + """Eine Liste: Zug, Balken, Anzahl. Klick auf eine Zeile spielt den Zug (wenn erlaubt).""" |
| 88 | + |
| 89 | + def __init__(self, with_results): |
| 90 | + super().__init__(orientation=Gtk.Orientation.VERTICAL) |
| 91 | + self.with_results = with_results |
| 92 | + self.on_play = None # callback(Zug) |
| 93 | + self.notation = "de" |
| 94 | + self.name_label = Gtk.Label(xalign=0, wrap=True, css_classes=["dim-label", "caption"], |
| 95 | + margin_start=12, margin_end=12, margin_bottom=6) |
| 96 | + self.append(self.name_label) |
| 97 | + self.listbox = Gtk.ListBox(selection_mode=Gtk.SelectionMode.NONE, css_classes=["navigation-sidebar"]) |
| 98 | + self.listbox.connect("row-activated", self._on_activated) |
| 99 | + self.status = Adw.StatusPage(css_classes=["compact"], vexpand=True) |
| 100 | + self.stack = Gtk.Stack(vexpand=True) |
| 101 | + scroller = Gtk.ScrolledWindow(vexpand=True, hscrollbar_policy=Gtk.PolicyType.NEVER, child=self.listbox) |
| 102 | + self.stack.add_named(scroller, "list") |
| 103 | + self.stack.add_named(self.status, "status") |
| 104 | + self.append(self.stack) |
| 105 | + self._key = None |
| 106 | + |
| 107 | + def show_message(self, title, description="", icon="dialog-information-symbolic"): |
| 108 | + self._key = None |
| 109 | + self.name_label.set_visible(False) |
| 110 | + self.status.set_icon_name(icon) |
| 111 | + self.status.set_title(title) |
| 112 | + self.status.set_description(description) |
| 113 | + self.stack.set_visible_child_name("status") |
| 114 | + |
| 115 | + def show_lines(self, board, lines, name=None, playable=False): |
| 116 | + key = (board.fen(), tuple((l.move, l.games) for l in lines), name, playable, self.notation) |
| 117 | + if key == self._key: |
| 118 | + return |
| 119 | + self._key = key |
| 120 | + self.name_label.set_label(name or "") |
| 121 | + self.name_label.set_visible(bool(name)) |
| 122 | + if not lines: |
| 123 | + self.show_message("Keine Partien", "Diese Stellung kommt hier nicht vor.", "edit-find-symbolic") |
| 124 | + self._key = key |
| 125 | + return |
| 126 | + self.listbox.remove_all() |
| 127 | + for line in lines: |
| 128 | + self.listbox.append(self._row(board, line, playable)) |
| 129 | + self.stack.set_visible_child_name("list") |
| 130 | + |
| 131 | + def _row(self, board, line, playable): |
| 132 | + row = Gtk.ListBoxRow(activatable=playable) |
| 133 | + row.move = line.move |
| 134 | + box = Gtk.Box(spacing=8, margin_top=4, margin_bottom=4) |
| 135 | + san = Gtk.Label(label=notation.move(board, line.move, self.notation), xalign=0, width_chars=6, |
| 136 | + css_classes=["heading"]) |
| 137 | + box.append(san) |
| 138 | + bar = Gtk.DrawingArea(hexpand=True, content_height=14, valign=Gtk.Align.CENTER) |
| 139 | + bar.set_draw_func(self._draw_bar, line) |
| 140 | + box.append(bar) |
| 141 | + if self.with_results: |
| 142 | + count = games_text(line.games) |
| 143 | + total = line.games |
| 144 | + row.set_tooltip_text( |
| 145 | + f"{line.games:,} Partien · Weiß {percent(line.white, total)} % · " |
| 146 | + f"Remis {percent(line.draws, total)} % · Schwarz {percent(line.black, total)} %".replace(",", ".") |
| 147 | + ) |
| 148 | + else: |
| 149 | + count = f"{round(line.share * 100)} %" if line.share >= 0.005 else "<1 %" |
| 150 | + row.set_tooltip_text(f"In {round(line.share * 100)} % der Buchpartien") |
| 151 | + box.append(Gtk.Label(label=count, xalign=1, width_chars=8, css_classes=["dim-label", "numeric"])) |
| 152 | + row.set_child(box) |
| 153 | + return row |
| 154 | + |
| 155 | + def _draw_bar(self, area, cr, width, height, line): |
| 156 | + radius = 3 |
| 157 | + def rounded(x, y, w, h): |
| 158 | + cr.new_sub_path() |
| 159 | + cr.arc(x + w - radius, y + radius, radius, -1.5708, 0) |
| 160 | + cr.arc(x + w - radius, y + h - radius, radius, 0, 1.5708) |
| 161 | + cr.arc(x + radius, y + h - radius, radius, 1.5708, 3.1416) |
| 162 | + cr.arc(x + radius, y + radius, radius, 3.1416, 4.7124) |
| 163 | + cr.close_path() |
| 164 | + |
| 165 | + if not self.with_results: |
| 166 | + fg = area.get_color() |
| 167 | + rounded(0, 0, width, height) |
| 168 | + cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.12) |
| 169 | + cr.fill() |
| 170 | + accent = Adw.StyleManager.get_default().get_accent_color_rgba() |
| 171 | + rounded(0, 0, max(2 * radius, width * line.share), height) |
| 172 | + cr.set_source_rgba(accent.red, accent.green, accent.blue, 1) |
| 173 | + cr.fill() |
| 174 | + return |
| 175 | + total = line.games or 1 |
| 176 | + rounded(0, 0, width, height) |
| 177 | + cr.save() |
| 178 | + cr.clip() |
| 179 | + x = 0.0 |
| 180 | + for part, rgb in ((line.white, WHITE_RGB), (line.draws, DRAW_RGB), (line.black, BLACK_RGB)): |
| 181 | + w = width * part / total |
| 182 | + cr.set_source_rgb(*rgb) |
| 183 | + cr.rectangle(x, 0, w + 0.5, height) |
| 184 | + cr.fill() |
| 185 | + x += w |
| 186 | + cr.restore() |
| 187 | + rounded(0.5, 0.5, width - 1, height - 1) |
| 188 | + cr.set_source_rgba(0, 0, 0, 0.25) |
| 189 | + cr.set_line_width(1) |
| 190 | + cr.stroke() |
| 191 | + |
| 192 | + def _on_activated(self, _listbox, row): |
| 193 | + if self.on_play and getattr(row, "move", None) is not None: |
| 194 | + self.on_play(row.move) |
| 195 | + |
| 196 | + |
| 197 | +class ExplorerMixin: |
| 198 | + """Seitenleiste mit Reitern „Partie | Buch | Lichess“ und die Abfragen dazu.""" |
| 199 | + |
| 200 | + def _explorer_init(self): |
| 201 | + self.explorer_cache = {} # (fen, ratings) -> Antwort von Lichess |
| 202 | + self.explorer_pending = None |
| 203 | + self.explorer_source = 0 |
| 204 | + |
| 205 | + def _build_sidebar(self, movelist): |
| 206 | + self.book_list = ExplorerList(with_results=False) |
| 207 | + self.lichess_list = ExplorerList(with_results=True) |
| 208 | + for view in (self.book_list, self.lichess_list): |
| 209 | + view.on_play = self._explorer_play |
| 210 | + self.side_stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.CROSSFADE, vexpand=True) |
| 211 | + self.side_stack.add_named(movelist, "moves") |
| 212 | + self.side_stack.add_named(self.book_list, "book") |
| 213 | + self.side_stack.add_named(self.lichess_list, "lichess") |
| 214 | + self.side_switch = Adw.ToggleGroup(margin_start=12, margin_end=12, margin_top=6, margin_bottom=6, |
| 215 | + css_classes=["round"]) |
| 216 | + for name, label, tip in (("moves", "Partie", "Züge und Bewertung"), |
| 217 | + ("book", "Buch", "Eröffnungsbuch"), |
| 218 | + ("lichess", "Lichess", "Was Spieler deiner Stärke auf Lichess ziehen")): |
| 219 | + self.side_switch.add(Adw.Toggle(name=name, label=label, tooltip=tip)) |
| 220 | + self.side_switch.set_active_name("moves") |
| 221 | + self.side_switch.connect("notify::active-name", self._explorer_switched) |
| 222 | + box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) |
| 223 | + box.append(self.side_switch) |
| 224 | + box.append(self.side_stack) |
| 225 | + self._explorer_logged_in_changed() |
| 226 | + return box |
| 227 | + |
| 228 | + def _explorer_switched(self, *_): |
| 229 | + self.side_stack.set_visible_child_name(self.side_switch.get_active_name() or "moves") |
| 230 | + self._explorer_refresh() |
| 231 | + |
| 232 | + def _explorer_logged_in_changed(self): |
| 233 | + if getattr(self, "side_switch", None) is None: |
| 234 | + return # Titelleiste wird vor der Seitenleiste gebaut |
| 235 | + logged_in = self.get_application().lichess_user is not None |
| 236 | + toggle = self.side_switch.get_toggle_by_name("lichess") |
| 237 | + toggle.set_enabled(logged_in) |
| 238 | + toggle.set_tooltip("Was Spieler deiner Stärke auf Lichess ziehen" if logged_in |
| 239 | + else "Nur mit Lichess-Anmeldung") |
| 240 | + if not logged_in and self.side_switch.get_active_name() == "lichess": |
| 241 | + self.side_switch.set_active_name("book") |
| 242 | + |
| 243 | + def _explorer_blocked(self): |
| 244 | + """Grund, warum der Explorer gerade nichts zeigen darf – oder None.""" |
| 245 | + if self.mode == "online" and self._online_running(): |
| 246 | + return "Während einer Lichess-Partie ausgeblendet (Fair Play)." |
| 247 | + if self.mode == "puzzle" and not self._over() and not (self.puzzle and self.puzzle.get("done")): |
| 248 | + return "Während des Rätsels ausgeblendet – sonst wäre es zu leicht." |
| 249 | + if self.mode == "setup": |
| 250 | + return "Erst die Stellung fertig aufbauen." |
| 251 | + return None |
| 252 | + |
| 253 | + def _explorer_board(self): |
| 254 | + return self._board_at(self.browse_ply) if self._browsing() else self.board |
| 255 | + |
| 256 | + def _explorer_refresh(self): |
| 257 | + if not self.split.get_show_sidebar(): |
| 258 | + return |
| 259 | + source = self.side_switch.get_active_name() |
| 260 | + if source not in ("book", "lichess"): |
| 261 | + return |
| 262 | + view = self.book_list if source == "book" else self.lichess_list |
| 263 | + view.notation = self._notation() |
| 264 | + blocked = self._explorer_blocked() |
| 265 | + if blocked: |
| 266 | + view.show_message("Gerade nicht", blocked, "action-unavailable-symbolic") |
| 267 | + return |
| 268 | + board = self._explorer_board() |
| 269 | + playable = self._human_to_move() and not self._browsing() |
| 270 | + name = self._explorer_name(board) |
| 271 | + if source == "book": |
| 272 | + from .training import _book |
| 273 | + view.show_lines(board, book_lines(_book(), board), name, playable) |
| 274 | + return |
| 275 | + ratings = ratings_near(self.elo or int(self.settings["elo"])) |
| 276 | + key = (board.fen(), tuple(ratings)) |
| 277 | + if key in self.explorer_cache: |
| 278 | + view.show_lines(board, lichess_lines(self.explorer_cache[key], board), name, playable) |
| 279 | + return |
| 280 | + view.show_message("Lädt …", f"Partien mit Wertung {ratings[0]}–{ratings[-1] + 199}", "content-loading-symbolic") |
| 281 | + if self.explorer_pending: |
| 282 | + GLib.source_remove(self.explorer_pending) |
| 283 | + self.explorer_pending = GLib.timeout_add(FETCH_DELAY_MS, self._explorer_fetch, key) |
| 284 | + |
| 285 | + def _explorer_fetch(self, key): |
| 286 | + self.explorer_pending = None |
| 287 | + client = self.get_application().lichess_client |
| 288 | + if client is None: |
| 289 | + self.lichess_list.show_message("Nicht angemeldet", "Der Lichess-Explorer braucht eine Anmeldung.") |
| 290 | + return False |
| 291 | + fen, ratings = key |
| 292 | + params = {"variant": "standard", "fen": fen, "ratings": ",".join(map(str, ratings)), |
| 293 | + "speeds": SPEEDS, "moves": MAX_ROWS, "topGames": 0, "recentGames": 0} |
| 294 | + |
| 295 | + def work(): |
| 296 | + resp = client.session.get(EXPLORER_URL, params=params, timeout=20) |
| 297 | + resp.raise_for_status() |
| 298 | + return resp.json() |
| 299 | + |
| 300 | + def done(data, error): |
| 301 | + if error: |
| 302 | + self.lichess_list.show_message("Lichess antwortet nicht", error, "network-error-symbolic") |
| 303 | + return |
| 304 | + self.explorer_cache[key] = data |
| 305 | + self._explorer_refresh() |
| 306 | + |
| 307 | + lichess._background(work, done) |
| 308 | + return False |
| 309 | + |
| 310 | + def _explorer_name(self, board): |
| 311 | + from .training import _names |
| 312 | + key = board.fen() |
| 313 | + if key not in self._name_cache: |
| 314 | + self._name_cache[key] = _names().name(board) |
| 315 | + name = self._name_cache[key] |
| 316 | + return notation.text(name, self._notation()) if name else None |
| 317 | + |
| 318 | + def _explorer_play(self, move): |
| 319 | + if self._human_to_move() and not self._browsing() and move in self.board.legal_moves: |
| 320 | + self._on_board_move(move.from_square, move.to_square) if not move.promotion else self._play_human(move) |