Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(explorer): support several Polyglot opening books

public

feat(explorer): support several Polyglot opening books

Books come from the preferences (add/remove), from a book folder in the
user data dir and from PyChess' book if installed; duplicates via
symlinks count once. The sidebar shows one collapsible section per book
with its own shares, since weights of different books don't compare.
For opening training a move counts as a book move if any book has it.

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

modified README.md +6 −1

@@ -50,7 +50,12 @@ Schlichtes GNOME-Schachprogramm (Python,
5050
   spielbarer Buchzug (mit Namen, z. B. „Spanische Partie“), kein Buchzug aber in Ordnung,
5151
   oder Fehler. Zugumstellungen zählen (Vergleich nach Stellung, nicht nach Zugfolge).
5252
   Hinweis zeigt den Kurszug. Am Ende: „Nächste Linie“ oder „Gegen Maia weiterspielen“.
53
-  Eröffnungsbuch und -namen stammen von PyChess (`pychess_book.bin`, `eco.db`).
53
+  Eröffnungsnamen stammen von PyChess (`eco.db`). Als Buchzug zählt, was in irgendeinem
54
+  Eröffnungsbuch steht.
55
+- **Eröffnungsbücher** (Einstellungen → Allgemein): beliebig viele Polyglot-Bücher (`.bin`) –
56
+  per „+“ wählen oder in den Bücherordner legen (`~/.local/share/schach/buecher/`); PyChess'
57
+  `pychess_book.bin` wird mitbenutzt, wenn installiert. In der Seitenleiste unter „Buch“ hat
58
+  jedes Buch eine eigene Sektion zum Auf- und Zuklappen, mit eigenen Anteilen.
5459
 - **Zwei Spieler** (Pfeil neben `+`): abwechselnd am selben Rechner. Handicap pro Farbe:
5560
   Anzahl Hinweise (Hinweis und Drohung kosten je einen) und welche Zugzeichen man sieht
5661
   (keine / eigene Züge / alle – nur solange diese Farbe am Zug ist; Standard: keine).

modified schach/app.py +7 −2

@@ -23,7 +23,7 @@ from .engines import MAIA_CMD, STOCKFISH
2323
 from .threat import null_board, threat_job  # noqa: E402
2424
 from .online import OnlineMixin  # noqa: E402
2525
 from .puzzles import PuzzleMixin  # noqa: E402
26
-from .training import OpeningMixin  # noqa: E402
26
+from .training import OpeningMixin, set_book_paths  # noqa: E402
2727
 from .duo import DuoMixin  # noqa: E402
2828
 from .setup import SetupMixin  # noqa: E402
2929
 from .explorer import ExplorerMixin  # noqa: E402
@@ -78,7 +78,7 @@ DEFAULTS = {
7878
     "elo": 1200, "color": "white", "theme": "cburnett", "puzzle_difficulty": "normal",
7979
     "temperature": OPPONENT_TEMPERATURE, "scheme": "holz", "hint_helper": DEFAULT_HELPER,
8080
     "threat_source": "opponent", "notation": notation.DEFAULT, "time_control": "Ohne Uhr",
81
-    "live_glyphs": True, "human_time": True,
81
+    "live_glyphs": True, "human_time": True, "books": [],
8282
 }
8383
 
8484
 
@@ -1467,6 +1467,8 @@ class Window(OnlineMixin, PuzzleMixin, O
14671467
             self._refresh()
14681468
         elif key == "live_glyphs":
14691469
             self._refresh()
1470
+        elif key == "books":
1471
+            self._explorer_refresh()
14701472
 
14711473
     def _preferences_dialog(self, *_, page=None):
14721474
         if self.prefs_dialog is not None:
@@ -1802,6 +1804,7 @@ class SchachApp(Adw.Application):
18021804
 
18031805
     def do_startup(self):
18041806
         Adw.Application.do_startup(self)
1807
+        set_book_paths(load_settings().get("books", []))
18051808
         # eigene Symbole (z. B. das Schwert für Drohungen), eingefärbt wie die GNOME-Symbole
18061809
         Gtk.IconTheme.get_for_display(Gdk.Display.get_default()).add_search_path(ICON_DIR)
18071810
         self.maia = EngineWorker(MAIA_CMD, on_ready=self._on_maia_ready)
@@ -1895,6 +1898,8 @@ class SchachApp(Adw.Application):
18951898
         settings = load_settings()
18961899
         settings[key] = value
18971900
         save_settings(settings)
1901
+        if key == "books":
1902
+            set_book_paths(value)  # einmal für alle Fenster, vor deren Auffrischen
18981903
         for win in self._windows():
18991904
             win.apply_setting(key, value)
19001905
 

modified schach/explorer.py +45 −11

@@ -1,7 +1,7 @@
11
 """Eröffnungsexplorer in der Seitenleiste: lokales Buch und Lichess Opening Explorer.
22
 
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
3
+Buch: alle Polyglot-Eröffnungsbücher, jedes in einer eigenen aufklappbaren Sektion;
4
+zeigt wie oft ein Zug im Buch steht (Polyglot kennt keine Ergebnisse). Lichess: was Spieler ähnlicher Wertung tatsächlich ziehen, mit
55
 Balken Weiß/Remis/Schwarz – braucht eine Lichess-Anmeldung.
66
 
77
 Während Lichess-Partien und ungelöster Rätsel bleibt der Explorer leer (Fair Play).
@@ -96,11 +96,11 @@ class ExplorerList(Gtk.Box):
9696
         self.name_label = Gtk.Label(xalign=0, wrap=True, css_classes=["dim-label", "caption"],
9797
                                     margin_start=12, margin_end=12, margin_top=8, margin_bottom=4)
9898
         self.append(self.name_label)
99
-        self.listbox = Gtk.ListBox(selection_mode=Gtk.SelectionMode.NONE, css_classes=["navigation-sidebar"])
100
-        self.listbox.connect("row-activated", self._on_activated)
99
+        self.content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
100
+        self.expanded = {}  # Buchname -> aufgeklappt? (bleibt beim Weiterziehen)
101101
         self.status = Adw.StatusPage(css_classes=["compact"], vexpand=True)
102102
         self.stack = Gtk.Stack(vexpand=True)
103
-        scroller = Gtk.ScrolledWindow(vexpand=True, hscrollbar_policy=Gtk.PolicyType.NEVER, child=self.listbox)
103
+        scroller = Gtk.ScrolledWindow(vexpand=True, hscrollbar_policy=Gtk.PolicyType.NEVER, child=self.content)
104104
         self.stack.add_named(scroller, "list")
105105
         self.stack.add_named(self.status, "status")
106106
         self.append(self.stack)
@@ -115,21 +115,46 @@ class ExplorerList(Gtk.Box):
115115
         self.stack.set_visible_child_name("status")
116116
 
117117
     def show_lines(self, board, lines, name=None, playable=False):
118
-        key = (board.fen(), tuple((l.move, l.games) for l in lines), name, playable, self.notation)
118
+        self.show_sections(board, [(None, lines)], name, playable)
119
+
120
+    def show_sections(self, board, sections, name=None, playable=False):
121
+        """sections: [(Titel oder None, [Line])]. Eine Sektion ohne Titel ist eine schlichte Liste;
122
+        mehrere (ein Buch je Sektion) lassen sich einzeln auf- und zuklappen."""
123
+        key = (board.fen(), tuple((title, tuple((l.move, l.games) for l in lines)) for title, lines in sections),
124
+               name, playable, self.notation)
119125
         if key == self._key:
120126
             return
121127
         self._key = key
122128
         self.name_label.set_label(name or "")
123129
         self.name_label.set_visible(bool(name))
124
-        if not lines:
130
+        if not any(lines for _title, lines in sections):
125131
             self.show_message("Keine Partien", "Diese Stellung kommt hier nicht vor.", "edit-find-symbolic")
126132
             self._key = key
127133
             return
128134
         if self.on_preview:
129135
             self.on_preview(None)  # Liste neu: alte Vorschau weg
130
-        self.listbox.remove_all()
131
-        for line in lines:
132
-            self.listbox.append(self._row(board, line, playable))
136
+        while (child := self.content.get_first_child()) is not None:
137
+            self.content.remove(child)
138
+        for title, lines in sections:
139
+            listbox = Gtk.ListBox(selection_mode=Gtk.SelectionMode.NONE, css_classes=["navigation-sidebar"])
140
+            listbox.connect("row-activated", self._on_activated)
141
+            for line in lines:
142
+                listbox.append(self._row(board, line, playable))
143
+            if title is None:
144
+                self.content.append(listbox)
145
+                continue
146
+            header = Gtk.Box(spacing=6)
147
+            header.append(Gtk.Label(label=title, xalign=0, hexpand=True, ellipsize=3, css_classes=["heading"]))
148
+            header.append(Gtk.Label(label=f"{len(lines)} Züge" if lines else "kennt die Stellung nicht",
149
+                                    css_classes=["dim-label", "caption"]))
150
+            expander = Gtk.Expander(label_widget=header, expanded=self.expanded.get(title, True),
151
+                                    margin_start=12, margin_end=6, margin_top=6)
152
+            expander.connect("notify::expanded", lambda e, _p, t=title: self.expanded.__setitem__(t, e.get_expanded()))
153
+            if lines:
154
+                expander.set_child(listbox)
155
+            else:
156
+                expander.set_sensitive(False)
157
+            self.content.append(expander)
133158
         self.stack.set_visible_child_name("list")
134159
 
135160
     def _row(self, board, line, playable):
@@ -284,7 +309,16 @@ class ExplorerMixin:
284309
         name = self._explorer_name(board)
285310
         if source == "book":
286311
             from .training import _book
287
-            view.show_lines(board, self._explorer_named(board, book_lines(_book(), board), name), name, playable)
312
+            books = _book().books
313
+            if not books:
314
+                view.show_message("Kein Eröffnungsbuch", "Polyglot-Bücher (.bin) in den Einstellungen hinzufügen.",
315
+                                  "accessories-dictionary-symbolic")
316
+                return
317
+            if len(books) == 1:
318
+                view.show_lines(board, self._explorer_named(board, book_lines(books[0], board), name), name, playable)
319
+                return
320
+            view.show_sections(board, [(b.name, self._explorer_named(board, book_lines(b, board), name))
321
+                                       for b in books], name, playable)
288322
             return
289323
         ratings = ratings_near(self.elo or int(self.settings["elo"]))
290324
         key = (board.fen(), tuple(ratings))

modified schach/opening.py +71 −4

@@ -18,6 +18,7 @@ import sqlite3
1818
 import chess
1919
 import chess.pgn
2020
 import chess.polyglot
21
+from gi.repository import GLib
2122
 
2223
 COURSE_DIR = os.path.join(os.path.dirname(__file__), "kurse")
2324
 BOOK_PATH = "/usr/share/pychess/pychess_book.bin"
@@ -153,9 +154,11 @@ def load_courses(directory=COURSE_DIR):
153154
 
154155
 
155156
 class Book:
156
-    """Polyglot-Eröffnungsbuch; ohne Datei einfach leer."""
157
+    """Ein Polyglot-Eröffnungsbuch; ohne (lesbare) Datei einfach leer."""
157158
 
158
-    def __init__(self, path=BOOK_PATH):
159
+    def __init__(self, path=BOOK_PATH, name=None):
160
+        self.path = path
161
+        self.name = name or _book_name(path)
159162
         self._reader = None
160163
         if os.path.exists(path):
161164
             try:
@@ -163,19 +166,83 @@ class Book:
163166
             except OSError:
164167
                 self._reader = None
165168
 
169
+    @property
170
+    def available(self):
171
+        return self._reader is not None
172
+
166173
     def moves(self, board):
167174
         """[(Zug, Gewicht)], häufigster zuerst."""
168175
         if self._reader is None:
169176
             return []
170177
         entries = {}
171
-        for entry in self._reader.find_all(board):
172
-            entries[entry.move] = entries.get(entry.move, 0) + entry.weight
178
+        try:
179
+            for entry in self._reader.find_all(board):
180
+                entries[entry.move] = entries.get(entry.move, 0) + entry.weight
181
+        except (OSError, ValueError):  # kaputte oder abgeschnittene Datei
182
+            return []
173183
         return sorted(entries.items(), key=lambda item: item[1], reverse=True)
174184
 
175185
     def contains(self, board, move):
176186
         return any(m == move for m, _w in self.moves(board))
177187
 
178188
 
189
+def _book_name(path):
190
+    stem = os.path.splitext(os.path.basename(path))[0]
191
+    return {"pychess_book": "PyChess"}.get(stem, stem.replace("_", " "))
192
+
193
+
194
+# Wie die Spielstände: unter Linux ~/.local/share, unter Windows %LOCALAPPDATA%, unter macOS ~/Library/…
195
+BOOK_DIR = os.path.join(GLib.get_user_data_dir(), "schach", "buecher")
196
+
197
+
198
+def book_paths(extra=(), book_dir=None, legacy=BOOK_PATH):
199
+    """Alle Polyglot-Bücher: ausdrücklich gewählte, dann ``*.bin`` im Bücherordner, dann
200
+    PyChess' Buch, falls installiert. Ohne Doppelte (gleiche Datei über zwei Wege)."""
201
+    book_dir = BOOK_DIR if book_dir is None else book_dir
202
+    found = list(extra)
203
+    if os.path.isdir(book_dir):
204
+        found += sorted(glob.glob(os.path.join(book_dir, "*.bin")))
205
+    if legacy:
206
+        found.append(legacy)
207
+    seen, result = set(), []
208
+    for path in found:
209
+        if not os.path.isfile(path):
210
+            continue
211
+        real = os.path.realpath(path)
212
+        if real not in seen:
213
+            seen.add(real)
214
+            result.append(path)
215
+    return result
216
+
217
+
218
+class Books:
219
+    """Mehrere Bücher. Für das Training zählt ein Zug, wenn er in irgendeinem steht;
220
+    die Seitenleiste zeigt jedes Buch einzeln (``books``)."""
221
+
222
+    def __init__(self, paths=None):
223
+        paths = book_paths() if paths is None else paths
224
+        self.books = [b for b in (Book(p) for p in paths) if b.available]
225
+
226
+    def moves(self, board):
227
+        """Alle Buchzüge, nach Anteil gemittelt über die Bücher, die die Stellung kennen."""
228
+        shares = {}
229
+        known = 0
230
+        for book in self.books:
231
+            moves = book.moves(board)
232
+            total = sum(w for _m, w in moves)
233
+            if not total:
234
+                continue
235
+            known += 1
236
+            for move, weight in moves:
237
+                shares[move] = shares.get(move, 0) + weight / total
238
+        if not known:
239
+            return []
240
+        return sorted(((m, s / known) for m, s in shares.items()), key=lambda item: item[1], reverse=True)
241
+
242
+    def contains(self, board, move):
243
+        return any(book.contains(board, move) for book in self.books)
244
+
245
+
179246
 class Names:
180247
     """Eröffnungsnamen aus PyChess' eco.db, bevorzugt auf Deutsch."""
181248
 

modified schach/prefs.py +74 −2

@@ -1,12 +1,14 @@
11
 """Einstellungen (Adw.PreferencesDialog): gilt sofort, ohne Speichern-Knopf."""
22
 
3
+import os
4
+
35
 import gi
46
 
57
 gi.require_version("Gtk", "4.0")
68
 gi.require_version("Adw", "1")
7
-from gi.repository import Adw, Gtk  # noqa: E402
9
+from gi.repository import Adw, Gio, GLib, Gtk  # noqa: E402
810
 
9
-from . import notation  # noqa: E402
11
+from . import notation, opening  # noqa: E402
1012
 from .board import DEFAULT_SCHEME, SCHEMES, scheme_colors  # noqa: E402
1113
 
1214
 COLORS = [("white", "Weiß"), ("black", "Schwarz"), ("random", "Zufällig")]
@@ -82,8 +84,78 @@ class Preferences(Adw.PreferencesDialog)
8284
         think.connect("notify::active", lambda row, _p: self._set("human_time", row.get_active()))
8385
         opponent.add(think)
8486
         page.add(feedback)
87
+        self.books_group = None
88
+        self._books_page = page
89
+        self._build_books()
8590
         return page
8691
 
92
+    def _build_books(self):
93
+        """Gruppe „Eröffnungsbücher“: gewählte Dateien (entfernbar) und gefundene (Bücherordner, PyChess)."""
94
+        if self.books_group is not None:
95
+            self._books_page.remove(self.books_group)
96
+        chosen = list(self.win.settings.get("books", []))
97
+        add = Gtk.Button(icon_name="list-add-symbolic", tooltip_text="Buch hinzufügen …",
98
+                         valign=Gtk.Align.CENTER, css_classes=["flat"])
99
+        add.connect("clicked", self._on_add_book)
100
+        group = self.books_group = Adw.PreferencesGroup(
101
+            title="Eröffnungsbücher", header_suffix=add,
102
+            description="Polyglot-Bücher (.bin). Jedes erscheint in der Seitenleiste unter „Buch“ als eigene "
103
+                        "Sektion; für „Eröffnung üben“ zählt ein Zug, der in irgendeinem steht.",
104
+        )
105
+        paths = opening.book_paths(extra=chosen)
106
+        for path in paths:
107
+            row = Adw.ActionRow(title=GLib.markup_escape_text(opening._book_name(path)),
108
+                                subtitle=GLib.markup_escape_text(path))
109
+            if path in chosen:
110
+                remove = Gtk.Button(icon_name="user-trash-symbolic", tooltip_text="Entfernen",
111
+                                    valign=Gtk.Align.CENTER, css_classes=["flat"])
112
+                remove.connect("clicked", lambda _b, p=path: self._set_books([c for c in chosen if c != p]))
113
+                row.add_suffix(remove)
114
+            elif path == opening.BOOK_PATH:
115
+                row.set_subtitle("von PyChess installiert")
116
+            else:
117
+                row.set_subtitle("aus dem Bücherordner")
118
+            group.add(row)
119
+        folder = Adw.ActionRow(title="Bücherordner", subtitle=GLib.markup_escape_text(opening.BOOK_DIR),
120
+                               activatable=True, tooltip_text=".bin-Dateien hier hineinlegen genügt")
121
+        folder.add_suffix(Gtk.Image(icon_name="folder-open-symbolic"))
122
+        folder.connect("activated", self._on_open_book_dir)
123
+        group.add(folder)
124
+        self._books_page.add(group)
125
+
126
+    def _set_books(self, paths):
127
+        self._set("books", paths)
128
+        self._build_books()
129
+
130
+    def _on_add_book(self, _button):
131
+        dialog = Gtk.FileDialog(title="Eröffnungsbuch hinzufügen")
132
+        books = Gtk.FileFilter(name="Polyglot-Bücher (.bin)")
133
+        books.add_pattern("*.bin")
134
+        books.add_pattern("*.BIN")
135
+        filters = Gio.ListStore.new(Gtk.FileFilter)
136
+        filters.append(books)
137
+        dialog.set_filters(filters)
138
+        dialog.open(self.win, None, self._on_book_chosen)
139
+
140
+    def _on_book_chosen(self, dialog, result):
141
+        try:
142
+            file = dialog.open_finish(result)
143
+        except GLib.Error:
144
+            return  # abgebrochen
145
+        path = file.get_path() if file else None
146
+        if not path:
147
+            return
148
+        if not opening.Book(path).available:
149
+            self.add_toast(Adw.Toast(title="Kein lesbares Polyglot-Buch"))
150
+            return
151
+        chosen = list(self.win.settings.get("books", []))
152
+        if path not in chosen:
153
+            self._set_books(chosen + [path])
154
+
155
+    def _on_open_book_dir(self, _row):
156
+        os.makedirs(opening.BOOK_DIR, exist_ok=True)
157
+        Gtk.FileLauncher.new(Gio.File.new_for_path(opening.BOOK_DIR)).launch(self.win, None, None, None)
158
+
87159
     # --- Darstellung -------------------------------------------------------
88160
 
89161
     def _appearance_page(self):

modified schach/training.py +10 −1

@@ -25,9 +25,18 @@ TAKE_BACK_MS = 1600
2525
 _resources = {}
2626
 
2727
 
28
+_book_extra = []  # in den Einstellungen gewählte Buchdateien
29
+
30
+
31
+def set_book_paths(paths):
32
+    """Gewählte Bücher übernehmen; das nächste ``_book()`` liest neu."""
33
+    _book_extra[:] = list(paths or [])
34
+    _resources.pop("book", None)
35
+
36
+
2837
 def _book():
2938
     if "book" not in _resources:
30
-        _resources["book"] = opening.Book()
39
+        _resources["book"] = opening.Books(opening.book_paths(extra=_book_extra))
3140
     return _resources["book"]
3241
 
3342
 

modified tests/test_opening.py +52 −0

@@ -124,3 +124,55 @@ class BookTest(unittest.TestCase):
124124
 
125125
 if __name__ == "__main__":
126126
     unittest.main()
127
+
128
+
129
+class BooksTest(unittest.TestCase):
130
+    """Mehrere Polyglot-Bücher: Fundorte, Doppelte, Vereinigung."""
131
+
132
+    @staticmethod
133
+    def _write_book(path, entries):
134
+        import struct
135
+        data = b"".join(struct.pack(">QHHI", key, raw, weight, 0) for key, raw, weight in sorted(entries))
136
+        with open(path, "wb") as fh:
137
+            fh.write(data)
138
+
139
+    @staticmethod
140
+    def _raw(move):
141
+        promo = {None: 0, chess.KNIGHT: 1, chess.BISHOP: 2, chess.ROOK: 3, chess.QUEEN: 4}[move.promotion]
142
+        return (chess.square_file(move.to_square) | chess.square_rank(move.to_square) << 3
143
+                | chess.square_file(move.from_square) << 6 | chess.square_rank(move.from_square) << 9 | promo << 12)
144
+
145
+    def setUp(self):
146
+        import tempfile
147
+        self.dir = tempfile.TemporaryDirectory()
148
+        self.addCleanup(self.dir.cleanup)
149
+        start = chess.polyglot.zobrist_hash(chess.Board())
150
+        e4, d4, c4 = (chess.Move.from_uci(u) for u in ("e2e4", "d2d4", "c2c4"))
151
+        self.a = os.path.join(self.dir.name, "a.bin")
152
+        self.b = os.path.join(self.dir.name, "b_buch.bin")
153
+        self._write_book(self.a, [(start, self._raw(e4), 3), (start, self._raw(d4), 1)])
154
+        self._write_book(self.b, [(start, self._raw(c4), 10)])
155
+        self.e4, self.d4, self.c4 = e4, d4, c4
156
+
157
+    def test_paths_without_duplicates(self):
158
+        link = os.path.join(self.dir.name, "link.bin")
159
+        os.symlink(self.a, link)
160
+        paths = opening.book_paths(extra=[link, "/gibt/es/nicht.bin"], book_dir=self.dir.name, legacy=None)
161
+        self.assertEqual(paths, [link, self.b])  # a.bin ist dieselbe Datei wie link.bin
162
+
163
+    def test_union(self):
164
+        books = opening.Books([self.a, self.b])
165
+        self.assertEqual([b.name for b in books.books], ["a", "b buch"])
166
+        board = chess.Board()
167
+        self.assertTrue(books.contains(board, self.c4))
168
+        self.assertTrue(books.contains(board, self.e4))
169
+        shares = dict(books.moves(board))
170
+        self.assertAlmostEqual(shares[self.c4], 0.5)  # je Buch normiert, dann gemittelt
171
+        self.assertAlmostEqual(shares[self.e4], 0.375)
172
+        self.assertAlmostEqual(sum(shares.values()), 1)
173
+
174
+    def test_missing_and_empty(self):
175
+        books = opening.Books([os.path.join(self.dir.name, "fehlt.bin")])
176
+        self.assertEqual(books.books, [])
177
+        self.assertEqual(books.moves(chess.Board()), [])
178
+        self.assertFalse(books.contains(chess.Board(), self.e4))