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>
| Changeset | 6458a91ca1fcefe30671f3d74ebf01eb83e15d81 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | c6bd6dda71cf |
| Children | d50f901fa346 |
| Pushlog | by timo via ssh by timo via ssh |
modified README.md +6 −1
| @@ -50,7 +50,12 @@ Schlichtes GNOME-Schachprogramm (Python, | ||
| 50 | 50 | spielbarer Buchzug (mit Namen, z. B. „Spanische Partie“), kein Buchzug aber in Ordnung, |
| 51 | 51 | oder Fehler. Zugumstellungen zählen (Vergleich nach Stellung, nicht nach Zugfolge). |
| 52 | 52 | 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. | |
| 54 | 59 | - **Zwei Spieler** (Pfeil neben `+`): abwechselnd am selben Rechner. Handicap pro Farbe: |
| 55 | 60 | Anzahl Hinweise (Hinweis und Drohung kosten je einen) und welche Zugzeichen man sieht |
| 56 | 61 | (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 | ||
| 23 | 23 | from .threat import null_board, threat_job # noqa: E402 |
| 24 | 24 | from .online import OnlineMixin # noqa: E402 |
| 25 | 25 | from .puzzles import PuzzleMixin # noqa: E402 |
| 26 | -from .training import OpeningMixin # noqa: E402 | |
| 26 | +from .training import OpeningMixin, set_book_paths # noqa: E402 | |
| 27 | 27 | from .duo import DuoMixin # noqa: E402 |
| 28 | 28 | from .setup import SetupMixin # noqa: E402 |
| 29 | 29 | from .explorer import ExplorerMixin # noqa: E402 |
| @@ -78,7 +78,7 @@ DEFAULTS = { | ||
| 78 | 78 | "elo": 1200, "color": "white", "theme": "cburnett", "puzzle_difficulty": "normal", |
| 79 | 79 | "temperature": OPPONENT_TEMPERATURE, "scheme": "holz", "hint_helper": DEFAULT_HELPER, |
| 80 | 80 | "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": [], | |
| 82 | 82 | } |
| 83 | 83 | |
| 84 | 84 | |
| @@ -1467,6 +1467,8 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 1467 | 1467 | self._refresh() |
| 1468 | 1468 | elif key == "live_glyphs": |
| 1469 | 1469 | self._refresh() |
| 1470 | + elif key == "books": | |
| 1471 | + self._explorer_refresh() | |
| 1470 | 1472 | |
| 1471 | 1473 | def _preferences_dialog(self, *_, page=None): |
| 1472 | 1474 | if self.prefs_dialog is not None: |
| @@ -1802,6 +1804,7 @@ class SchachApp(Adw.Application): | ||
| 1802 | 1804 | |
| 1803 | 1805 | def do_startup(self): |
| 1804 | 1806 | Adw.Application.do_startup(self) |
| 1807 | + set_book_paths(load_settings().get("books", [])) | |
| 1805 | 1808 | # eigene Symbole (z. B. das Schwert für Drohungen), eingefärbt wie die GNOME-Symbole |
| 1806 | 1809 | Gtk.IconTheme.get_for_display(Gdk.Display.get_default()).add_search_path(ICON_DIR) |
| 1807 | 1810 | self.maia = EngineWorker(MAIA_CMD, on_ready=self._on_maia_ready) |
| @@ -1895,6 +1898,8 @@ class SchachApp(Adw.Application): | ||
| 1895 | 1898 | settings = load_settings() |
| 1896 | 1899 | settings[key] = value |
| 1897 | 1900 | save_settings(settings) |
| 1901 | + if key == "books": | |
| 1902 | + set_book_paths(value) # einmal für alle Fenster, vor deren Auffrischen | |
| 1898 | 1903 | for win in self._windows(): |
| 1899 | 1904 | win.apply_setting(key, value) |
| 1900 | 1905 | |
modified schach/explorer.py +45 −11
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | """Eröffnungsexplorer in der Seitenleiste: lokales Buch und Lichess Opening Explorer. |
| 2 | 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 | |
| 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 | |
| 5 | 5 | Balken Weiß/Remis/Schwarz – braucht eine Lichess-Anmeldung. |
| 6 | 6 | |
| 7 | 7 | Während Lichess-Partien und ungelöster Rätsel bleibt der Explorer leer (Fair Play). |
| @@ -96,11 +96,11 @@ class ExplorerList(Gtk.Box): | ||
| 96 | 96 | self.name_label = Gtk.Label(xalign=0, wrap=True, css_classes=["dim-label", "caption"], |
| 97 | 97 | margin_start=12, margin_end=12, margin_top=8, margin_bottom=4) |
| 98 | 98 | 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) | |
| 101 | 101 | self.status = Adw.StatusPage(css_classes=["compact"], vexpand=True) |
| 102 | 102 | 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) | |
| 104 | 104 | self.stack.add_named(scroller, "list") |
| 105 | 105 | self.stack.add_named(self.status, "status") |
| 106 | 106 | self.append(self.stack) |
| @@ -115,21 +115,46 @@ class ExplorerList(Gtk.Box): | ||
| 115 | 115 | self.stack.set_visible_child_name("status") |
| 116 | 116 | |
| 117 | 117 | 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) | |
| 119 | 125 | if key == self._key: |
| 120 | 126 | return |
| 121 | 127 | self._key = key |
| 122 | 128 | self.name_label.set_label(name or "") |
| 123 | 129 | self.name_label.set_visible(bool(name)) |
| 124 | - if not lines: | |
| 130 | + if not any(lines for _title, lines in sections): | |
| 125 | 131 | self.show_message("Keine Partien", "Diese Stellung kommt hier nicht vor.", "edit-find-symbolic") |
| 126 | 132 | self._key = key |
| 127 | 133 | return |
| 128 | 134 | if self.on_preview: |
| 129 | 135 | 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) | |
| 133 | 158 | self.stack.set_visible_child_name("list") |
| 134 | 159 | |
| 135 | 160 | def _row(self, board, line, playable): |
| @@ -284,7 +309,16 @@ class ExplorerMixin: | ||
| 284 | 309 | name = self._explorer_name(board) |
| 285 | 310 | if source == "book": |
| 286 | 311 | 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) | |
| 288 | 322 | return |
| 289 | 323 | ratings = ratings_near(self.elo or int(self.settings["elo"])) |
| 290 | 324 | key = (board.fen(), tuple(ratings)) |
modified schach/opening.py +71 −4
| @@ -18,6 +18,7 @@ import sqlite3 | ||
| 18 | 18 | import chess |
| 19 | 19 | import chess.pgn |
| 20 | 20 | import chess.polyglot |
| 21 | +from gi.repository import GLib | |
| 21 | 22 | |
| 22 | 23 | COURSE_DIR = os.path.join(os.path.dirname(__file__), "kurse") |
| 23 | 24 | BOOK_PATH = "/usr/share/pychess/pychess_book.bin" |
| @@ -153,9 +154,11 @@ def load_courses(directory=COURSE_DIR): | ||
| 153 | 154 | |
| 154 | 155 | |
| 155 | 156 | class Book: |
| 156 | - """Polyglot-Eröffnungsbuch; ohne Datei einfach leer.""" | |
| 157 | + """Ein Polyglot-Eröffnungsbuch; ohne (lesbare) Datei einfach leer.""" | |
| 157 | 158 | |
| 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) | |
| 159 | 162 | self._reader = None |
| 160 | 163 | if os.path.exists(path): |
| 161 | 164 | try: |
| @@ -163,19 +166,83 @@ class Book: | ||
| 163 | 166 | except OSError: |
| 164 | 167 | self._reader = None |
| 165 | 168 | |
| 169 | + @property | |
| 170 | + def available(self): | |
| 171 | + return self._reader is not None | |
| 172 | + | |
| 166 | 173 | def moves(self, board): |
| 167 | 174 | """[(Zug, Gewicht)], häufigster zuerst.""" |
| 168 | 175 | if self._reader is None: |
| 169 | 176 | return [] |
| 170 | 177 | 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 [] | |
| 173 | 183 | return sorted(entries.items(), key=lambda item: item[1], reverse=True) |
| 174 | 184 | |
| 175 | 185 | def contains(self, board, move): |
| 176 | 186 | return any(m == move for m, _w in self.moves(board)) |
| 177 | 187 | |
| 178 | 188 | |
| 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 | + | |
| 179 | 246 | class Names: |
| 180 | 247 | """Eröffnungsnamen aus PyChess' eco.db, bevorzugt auf Deutsch.""" |
| 181 | 248 | |
modified schach/prefs.py +74 −2
| @@ -1,12 +1,14 @@ | ||
| 1 | 1 | """Einstellungen (Adw.PreferencesDialog): gilt sofort, ohne Speichern-Knopf.""" |
| 2 | 2 | |
| 3 | +import os | |
| 4 | + | |
| 3 | 5 | import gi |
| 4 | 6 | |
| 5 | 7 | gi.require_version("Gtk", "4.0") |
| 6 | 8 | 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 | |
| 8 | 10 | |
| 9 | -from . import notation # noqa: E402 | |
| 11 | +from . import notation, opening # noqa: E402 | |
| 10 | 12 | from .board import DEFAULT_SCHEME, SCHEMES, scheme_colors # noqa: E402 |
| 11 | 13 | |
| 12 | 14 | COLORS = [("white", "Weiß"), ("black", "Schwarz"), ("random", "Zufällig")] |
| @@ -82,8 +84,78 @@ class Preferences(Adw.PreferencesDialog) | ||
| 82 | 84 | think.connect("notify::active", lambda row, _p: self._set("human_time", row.get_active())) |
| 83 | 85 | opponent.add(think) |
| 84 | 86 | page.add(feedback) |
| 87 | + self.books_group = None | |
| 88 | + self._books_page = page | |
| 89 | + self._build_books() | |
| 85 | 90 | return page |
| 86 | 91 | |
| 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 | + | |
| 87 | 159 | # --- Darstellung ------------------------------------------------------- |
| 88 | 160 | |
| 89 | 161 | def _appearance_page(self): |
modified schach/training.py +10 −1
| @@ -25,9 +25,18 @@ TAKE_BACK_MS = 1600 | ||
| 25 | 25 | _resources = {} |
| 26 | 26 | |
| 27 | 27 | |
| 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 | + | |
| 28 | 37 | def _book(): |
| 29 | 38 | if "book" not in _resources: |
| 30 | - _resources["book"] = opening.Book() | |
| 39 | + _resources["book"] = opening.Books(opening.book_paths(extra=_book_extra)) | |
| 31 | 40 | return _resources["book"] |
| 32 | 41 | |
| 33 | 42 | |
modified tests/test_opening.py +52 −0
| @@ -124,3 +124,55 @@ class BookTest(unittest.TestCase): | ||
| 124 | 124 | |
| 125 | 125 | if __name__ == "__main__": |
| 126 | 126 | 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)) | |