Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(explorer): book and Lichess opening explorer in sidebar

public

feat(explorer): book and Lichess opening explorer in sidebar

Tabs Partie | Buch | Lichess. Lichess rows filtered to rating
buckets around the Maia level, with white/draw/black bars; tab
disabled without login (API answers 401). Hidden during Lichess
games and unsolved puzzles. Click a row to play the move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Changeseta48cbb43036155a3a9eb39879590ed3916b98026
Author (claimed)Timo Stolz <timo.stolz@nullachtvierzehn.de>,
Parents03f259291faf
Children2ef09b306316
Pushlog
by timo via ssh
by timo via ssh

modified ROADMAP.md +8 −7

@@ -388,13 +388,14 @@ Erklärung:
388388
 - **Eröffnung in eigenen Partien:** Nach einer Partie gegen Maia steht in der
389389
   Zugliste „Buch bis Zug 6, dann Abweichung: Kurs empfiehlt …“. So merkt Florian
390390
   in echten Partien, wo er den Plan verlassen hat.
391
-- **Eröffnungsbuch in der Seitenleiste, zwei Reiter:** „Buch“ (lokal, PyChess-Buch)
392
-  und „Lichess“ (Opening Explorer, was Spieler mit ähnlicher Wertung tatsächlich
393
-  ziehen; online, möglicherweise nur mit Anmeldung). Jede Zeile hat einen Zug,
394
-  die Anzahl Partien und einen Balken Weiß/Remis/Schwarz wie in PyChess. Mit
395
-  `Adw.ViewSwitcher` oder einem `Adw.ToggleGroup` über der Liste, neben der
396
-  Zugliste als weiterer Bereich. Während Lichess-Partien bleibt der Bereich
397
-  ausgeblendet (Fair Play).
391
+- **Eröffnungsexplorer in der Seitenleiste** (umgesetzt 20.11.2026, `schach/explorer.py`):
392
+  Reiter „Partie | Buch | Lichess“ (`Adw.ToggleGroup`). Buch: PyChess-Buch, Anteil
393
+  jedes Zugs (Polyglot kennt keine Ergebnisse). Lichess: Opening Explorer mit
394
+  Partienzahl und Balken Weiß/Remis/Schwarz, gefiltert auf die zwei Wertungsstufen
395
+  um die eingestellte Maia-Stärke (Blitz, Schnell, Klassisch). Der Reiter braucht
396
+  eine Lichess-Anmeldung und ist sonst ausgegraut. Klick auf eine Zeile spielt den
397
+  Zug, wenn man am Zug ist. Während Lichess-Partien und ungelöster Rätsel bleibt
398
+  der Explorer leer (Fair Play).
398399
 
399400
 ## 7. Zwei Spieler an einem Rechner
400401
 

modified schach/app.py +6 −2

@@ -26,6 +26,7 @@ from .puzzles import PuzzleMixin # noqa
2626
 from .training import OpeningMixin  # noqa: E402
2727
 from .duo import DuoMixin  # noqa: E402
2828
 from .setup import SetupMixin  # noqa: E402
29
+from .explorer import ExplorerMixin  # noqa: E402
2930
 from .clock import TIME_CONTROLS, GameClock, time_control  # noqa: E402
3031
 
3132
 APP_ID = "app.schach.Schach"
@@ -118,7 +119,7 @@ def outcome_text(board, human, opponent=
118119
     }.get(outcome.termination, "Remis.")
119120
 
120121
 
121
-class Window(OnlineMixin, PuzzleMixin, OpeningMixin, DuoMixin, SetupMixin, Adw.ApplicationWindow):
122
+class Window(OnlineMixin, PuzzleMixin, OpeningMixin, DuoMixin, SetupMixin, ExplorerMixin, Adw.ApplicationWindow):
122123
     """Ein Brett. ``mode``: "maia" (Partie gegen Maia), "online" (Lichess-Partie, ohne Engine-Hilfe),
123124
     "puzzle" (Lichess-Rätsel), "opening" (Eröffnungstraining), "duo" (zwei Spieler an diesem Rechner),
124125
     "review" (fertige Partie ansehen und analysieren)."""
@@ -165,6 +166,7 @@ class Window(OnlineMixin, PuzzleMixin, O
165166
         self._opening_init()
166167
         self._duo_init()
167168
         self._setup_init()
169
+        self._explorer_init()
168170
         self.clock = None  # Schachuhr lokaler Partien (clock.GameClock)
169171
         self.clock_tick = 0
170172
 
@@ -321,7 +323,7 @@ class Window(OnlineMixin, PuzzleMixin, O
321323
         self.movelist.on_continue = self._continue_from
322324
 
323325
         self.split = Adw.OverlaySplitView(
324
-            content=box, sidebar=self.movelist, sidebar_position=Gtk.PackType.END,
326
+            content=box, sidebar=self._build_sidebar(self.movelist), sidebar_position=Gtk.PackType.END,
325327
             show_sidebar=False, max_sidebar_width=320, min_sidebar_width=220,
326328
         )
327329
         self.list_btn.bind_property(
@@ -458,6 +460,7 @@ class Window(OnlineMixin, PuzzleMixin, O
458460
         self.primary_menu.insert_section(1, label, self.lichess_section)
459461
         if self.prefs_dialog is not None:
460462
             self.prefs_dialog.refresh_lichess()
463
+        self._explorer_logged_in_changed()
461464
 
462465
     # --- Zustand → Anzeige -------------------------------------------------
463466
 
@@ -717,6 +720,7 @@ class Window(OnlineMixin, PuzzleMixin, O
717720
         if self.split.get_show_sidebar():
718721
             self.movelist.update(self.board, self.evals, self.symbols, self.browse_ply)
719722
             self._request_missing_evals()
723
+            self._explorer_refresh()
720724
 
721725
     def _refresh_players(self):
722726
         """Spieler-Zeilen über und unter dem Brett: wer spielt hier gegen wen?"""

added schach/explorer.py +320 −0

@@ -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)

added tests/test_explorer.py +53 −0

@@ -0,0 +1,53 @@
1
+import unittest
2
+
3
+import chess
4
+
5
+from schach import explorer, opening
6
+
7
+
8
+class LichessLinesTest(unittest.TestCase):
9
+    def test_parse_and_castling(self):
10
+        board = chess.Board("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1")
11
+        data = {"moves": [
12
+            {"uci": "e1h1", "san": "O-O", "white": 6, "draws": 2, "black": 2},
13
+            {"uci": "a1a8", "san": "Rxa8+", "white": 1, "draws": 0, "black": 1},
14
+            {"uci": "zz", "white": 1},
15
+        ]}
16
+        lines = explorer.lichess_lines(data, board)
17
+        self.assertEqual([l.move.uci() for l in lines], ["e1g1", "a1a8"])
18
+        self.assertEqual(lines[0].games, 10)
19
+        self.assertAlmostEqual(lines[0].share, 10 / 13)  # Anteil an allen Partien der Stellung
20
+
21
+    def test_illegal_moves_skipped(self):
22
+        data = {"moves": [{"uci": "e2e5", "white": 1, "draws": 0, "black": 0}]}
23
+        self.assertEqual(explorer.lichess_lines(data, chess.Board()), [])
24
+
25
+
26
+class BookLinesTest(unittest.TestCase):
27
+    def test_book_share(self):
28
+        class FakeBook:
29
+            def moves(self, board):
30
+                return [(chess.Move.from_uci("e2e4"), 3), (chess.Move.from_uci("d2d4"), 1)]
31
+        lines = explorer.book_lines(FakeBook(), chess.Board())
32
+        self.assertEqual([round(l.share, 2) for l in lines], [0.75, 0.25])
33
+
34
+    def test_real_book_if_present(self):
35
+        lines = explorer.book_lines(opening.Book(), chess.Board())
36
+        if lines:
37
+            self.assertAlmostEqual(sum(l.share for l in explorer.book_lines(opening.Book(), chess.Board())), 1, 1)
38
+
39
+
40
+class HelpersTest(unittest.TestCase):
41
+    def test_ratings_near(self):
42
+        self.assertEqual(explorer.ratings_near(1250), [1200, 1400])
43
+        self.assertEqual(explorer.ratings_near(700), [0, 1000])
44
+        self.assertEqual(explorer.ratings_near(2700), [2200, 2500])
45
+
46
+    def test_games_text(self):
47
+        self.assertEqual(explorer.games_text(1234), "1.234")
48
+        self.assertEqual(explorer.games_text(45678), "45 Tsd.")
49
+        self.assertEqual(explorer.games_text(2_345_678), "2,3 Mio.")
50
+
51
+
52
+if __name__ == "__main__":
53
+    unittest.main()