Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(analyse): side lines in the move list, on Ctrl+C and in the export

public

feat(analyse): side lines in the move list, on Ctrl+C and in the export

Side lines from the analysis board appear indented under the move they branch
from; a click jumps there. Ctrl+C and the PGN/HTML export include them with
comments and arrows ([%cal]); the export has a "Varianten" switch. Saving them
in game files is still open (stage 4).

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

modified README.md +3 −2

@@ -25,8 +25,9 @@ Schlichtes GNOME-Schachprogramm (Python,
2525
   **Analysebrett** (gegen Maia und bei fertigen Partien; sonst wird die Stellung nur
2626
   gezeigt). Dort zieht man selbst beide Seiten, die Engine antwortet, und jede
2727
   Abweichung bleibt als Nebenvariante stehen. Die echte Partie ist nicht getönt,
28
-  Gedachtes schon. ← und → gehen einen Zug zurück oder vor, Esc führt zurück ins
29
-  Spiel. Bei fertigen Partien ist das Analysebrett die normale Ansicht. Knöpfe:
28
+  Gedachtes schon. Nebenvarianten stehen eingerückt in der Zugliste (anklicken
29
+  springt hin) und kommen bei Strg+C und im Export (PGN, HTML) mit. ← und → gehen
30
+  einen Zug zurück oder vor, Esc führt zurück ins Spiel. Bei fertigen Partien ist das Analysebrett die normale Ansicht. Knöpfe:
3031
   „Warum nicht?“ (bei `?!` `?` `??`), FEN kopieren, von hier weiterspielen (als
3132
   Abzweigung in einem neuen Fenster – die Originalpartie bleibt erhalten).
3233
 - **Spielstände:** mit Namen speichern (Strg+S) und laden (Strg+O). Die laufende

modified roadmap/analysebrett.md +8 −1

@@ -164,8 +164,15 @@ Was übrig bleibt, bestimmt die Pfeile an den Gabelungen und die Tiefe.
164164
    Analysebrett die normale Ansicht, Esc führt dort zum Ende der Partie.
165165
    Abweichungen: Rätsel, Kurse, Online-Partien und zu zweit blättern weiter wie
166166
    bisher (Online wäre Betrug, Rätsel verriete die Lösung). „Warum nicht?“ bleibt
167
-   ein eigener Baum und hängt sich noch nicht in den Partiebaum.
167
+   ein eigener Baum und hängt sich noch nicht in den Partiebaum. Nebenvarianten
168
+   stehen eingerückt unter dem Zug, nach dem sie abzweigen („↳ 4. a3 Sxe4 …“,
169
+   höchstens 8 Halbzüge), ein Klick springt hin.
168170
 4. **Speichern und Kopieren:** Analysen im Spielstand und als PGN.
171
+   **Teilweise umgesetzt (22.11.2026):** Strg+C und der Export (PGN, HTML)
172
+   nehmen die Nebenvarianten mit, samt Kommentaren und Pfeilen (`[%cal]`, eigene
173
+   blau, Gegner gelb). Beim Export lassen sie sich mit dem Schalter „Varianten“
174
+   abschalten. PDF, LaTeX und ASCII zeigen nur die Partie. Noch offen: Varianten
175
+   im Spielstand speichern und beim Öffnen wieder einlesen.
169176
 
170177
 Die Stufen 1 und 2 bringen fürs Lernen am meisten.
171178
 

modified schach/app.py +26 −6

@@ -333,6 +333,7 @@ class Window(OnlineMixin, PuzzleMixin, O
333333
         self.movelist.on_copy = self._copy_fen
334334
         self.movelist.on_continue = self._continue_from
335335
         self.movelist.on_why_not = self._why_not_from_list
336
+        self.movelist.on_variation = self._on_list_variation
336337
 
337338
         self.split = Adw.OverlaySplitView(
338339
             content=box, sidebar=self._build_sidebar(self.movelist), sidebar_position=Gtk.PackType.END,
@@ -763,7 +764,7 @@ class Window(OnlineMixin, PuzzleMixin, O
763764
                 self.list_btn.set_active(True)  # Partie vorbei: Analyse aufklappen
764765
 
765766
         if self.split.get_show_sidebar():
766
-            self.movelist.update(self.board, self.evals, self.symbols, self._list_ply())
767
+            self._movelist_update()
767768
             self._request_missing_evals()
768769
             self._explorer_refresh()
769770
 
@@ -1394,7 +1395,7 @@ class Window(OnlineMixin, PuzzleMixin, O
13941395
             return  # kaum Änderung: Liste nicht neu aufbauen
13951396
         self.evals[ply] = white
13961397
         if self.split.get_show_sidebar():
1397
-            self.movelist.update(self.board, self.evals, self.symbols, self._list_ply())
1398
+            self._movelist_update()
13981399
 
13991400
     def _request_missing_evals(self):
14001401
         if self.mode == "online" or (self.mode == "puzzle" and not self._over()):
@@ -1454,6 +1455,22 @@ class Window(OnlineMixin, PuzzleMixin, O
14541455
             return
14551456
         self._analysis_open(min(ply, last))
14561457
 
1458
+    def _movelist_update(self):
1459
+        """Zugliste samt Nebenvarianten vom Analysebrett; markiert, wo das Analysebrett gerade steht."""
1460
+        self.list_variations = self._list_variations()
1461
+        selected = None
1462
+        if self.demo is not None and self.demo.get("game") and not self._demo_real(self.demo["node"]):
1463
+            top = self.demo["node"]
1464
+            while not self._demo_real(top.parent):
1465
+                top = top.parent
1466
+            selected = next((i for i, (_p, _t, n) in enumerate(self.list_variations) if n is top), None)
1467
+        self.movelist.update(self.board, self.evals, self.symbols, None if selected is not None else self._list_ply(),
1468
+                             [(p, t) for p, t, _n in self.list_variations], selected)
1469
+
1470
+    def _on_list_variation(self, index):
1471
+        if 0 <= index < len(getattr(self, "list_variations", ())) and not (self.demo and self.demo["busy"]):
1472
+            self._analysis_open_node(self.list_variations[index][2])
1473
+
14571474
     def _list_ply(self):
14581475
         """Markierte Zeile in der Zugliste: beim Analysebrett der Zug der Partie, an dem man gerade ist."""
14591476
         if self.demo is not None and self.demo.get("game"):
@@ -1538,7 +1555,8 @@ class Window(OnlineMixin, PuzzleMixin, O
15381555
             self._copy_fen(-1)  # noch keine Züge: wenigstens die Stellung
15391556
             return
15401557
         self.get_clipboard().set(self._pgn())
1541
-        self.toasts.add_toast(Adw.Toast(title="Partie als PGN kopiert", timeout=2))
1558
+        title = "Partie samt Varianten als PGN kopiert" if self._game_variations() else "Partie als PGN kopiert"
1559
+        self.toasts.add_toast(Adw.Toast(title=title, timeout=2))
15421560
 
15431561
     def _copy_shown_fen(self, *_):
15441562
         if self.mode == "setup":
@@ -1864,7 +1882,8 @@ class Window(OnlineMixin, PuzzleMixin, O
18641882
 
18651883
     # --- Spielstände -------------------------------------------------------
18661884
 
1867
-    def state(self):
1885
+    def state(self, variations=False):
1886
+        """Spielstand; ``variations``: mit den Nebenvarianten vom Analysebrett (Kopieren, Export)."""
18681887
         return savegames.GameState(
18691888
             board=self.board.copy(),
18701889
             human=self.human,
@@ -1877,6 +1896,7 @@ class Window(OnlineMixin, PuzzleMixin, O
18771896
             opponent=self.opponent,
18781897
             final_text=self.final_text or "",
18791898
             names=("Weiß", "Schwarz") if self.mode == "duo" else self.names,
1899
+            variations=self._game_variations() if variations else {},
18801900
         )
18811901
 
18821902
     def load_state(self, state):
@@ -2024,7 +2044,7 @@ class Window(OnlineMixin, PuzzleMixin, O
20242044
             self.load_state(state)
20252045
 
20262046
     def _pgn(self):
2027
-        return savegames.to_pgn(self.state())
2047
+        return savegames.to_pgn(self.state(variations=True))
20282048
 
20292049
     def _export_dialog(self, *_):
20302050
         from .exportdialog import ExportDialog
@@ -2033,7 +2053,7 @@ class Window(OnlineMixin, PuzzleMixin, O
20332053
         if self.demo is not None and self.demo.get("game"):
20342054
             plies = self._game_ply(self.demo["node"]) + 1
20352055
         ExportDialog(
2036
-            self, self.state(), plies, self.settings.get("export"), flipped=self.view.flipped,
2056
+            self, self.state(variations=True), plies, self.settings.get("export"), flipped=self.view.flipped,
20372057
             theme=self.settings["theme"], scheme=self.settings["scheme"], style=self._notation(),
20382058
         ).present(self)
20392059
 

modified schach/export.py +13 −2

@@ -44,6 +44,7 @@ class Options:
4444
     players: bool = True  # Spielerköpfe: Namen, Datum, Ergebnis
4545
     last_move: bool = True  # letzten Zug markieren
4646
     flipped: bool = False  # Schwarz unten
47
+    variations: bool = True  # Nebenvarianten vom Analysebrett (PGN, HTML)
4748
     theme: str = BUILTIN_THEME
4849
     scheme: str = DEFAULT_SCHEME
4950
 
@@ -61,7 +62,8 @@ class Format:
6162
 
6263
 _BOARD = frozenset({"last_move", "flipped"})
6364
 FORMATS = {
64
-    "pgn": Format("PGN", "pgn", "application/vnd.chess-pgn", ("position", "game"), frozenset({"symbols", "evals"})),
65
+    "pgn": Format("PGN", "pgn", "application/vnd.chess-pgn", ("position", "game"),
66
+                  frozenset({"symbols", "evals", "variations"})),
6567
     "fen": Format("FEN", "fen", "text/plain", ("position",), frozenset()),
6668
     "svg": Format("SVG-Bild", "svg", "image/svg+xml", ("position",), _BOARD | {"symbols", "evals", "players"}),
6769
     "png": Format("PNG-Bild", "png", "image/png", ("position",), _BOARD | {"symbols", "evals", "players"}, binary=True),
@@ -70,7 +72,8 @@ FORMATS = {
7072
                   _BOARD | {"symbols", "evals", "players"}, binary=True, clipboard=False),
7173
     "pdf-latex": Format("PDF über LaTeX", "pdf", "application/pdf", ("position", "game"),
7274
                         _BOARD | {"symbols", "players"}, binary=True, clipboard=False),
73
-    "html": Format("HTML-Seite", "html", "text/html", ("position", "game"), _BOARD | {"symbols", "evals", "players"}),
75
+    "html": Format("HTML-Seite", "html", "text/html", ("position", "game"),
76
+                   _BOARD | {"symbols", "evals", "players", "variations"}),
7477
     "ascii": Format("ASCII-Art", "txt", "text/plain", ("position", "game"), {"flipped", "symbols", "players"}),
7578
 }
7679
 
@@ -251,6 +254,10 @@ def to_pgn(state, opts):
251254
     book_ply, eco, name = book_end(state)
252255
     if name:
253256
         game.headers["ECO"], game.headers["Opening"] = eco or "?", name
257
+    if not opts.variations:
258
+        for node in [game, *game.mainline()]:
259
+            for side in node.variations[1:]:
260
+                node.remove_variation(side)
254261
     for ply, node in enumerate(game.mainline()):
255262
         if not opts.symbols:
256263
             node.nags.clear()
@@ -800,6 +807,10 @@ def _html_pgn(pgn_text, selected):
800807
         units.append([" ".join(parts), True])
801808
         if comment:
802809
             units.append([comment, False])  # lang: eigener, umbrechbarer Teil
810
+        for side in node.parent.variations[1:]:  # Nebenvarianten vom Analysebrett: grau, in Klammern
811
+            text = side.accept(chess.pgn.StringExporter(headers=False, columns=None))
812
+            text = " ".join(opening.COMMAND_RE.sub(" ", text).split())
813
+            units.append([f'<span class="c">( {esc(text)} )</span>', False])
803814
         board.push(node.move)
804815
     result = esc(game.headers.get("Result", "*"))
805816
     if units and units[-1][1]:

modified schach/exportdialog.py +8 −3

@@ -16,7 +16,8 @@ from gi.repository import Adw, Gdk, GLib
1616
 
1717
 from . import export  # noqa: E402
1818
 
19
-DEFAULTS = {"format": "pgn", "scope": "game", "symbols": True, "evals": True, "players": True, "last_move": True}
19
+DEFAULTS = {"format": "pgn", "scope": "game", "symbols": True, "evals": True, "players": True, "last_move": True,
20
+            "variations": True}
2021
 
2122
 # Schalter für die Darstellung: (Option, Titel, Untertitel)
2223
 SWITCHES = [
@@ -25,6 +26,7 @@ SWITCHES = [
2526
     ("players", "Spielerköpfe", "Namen, Datum und Ergebnis"),
2627
     ("last_move", "Letzten Zug markieren", "Felder des letzten Zugs hervorheben"),
2728
     ("flipped", "Schwarz unten", "Brett gedreht"),
29
+    ("variations", "Varianten", "Selbst gezogene Züge vom Analysebrett"),
2830
 ]
2931
 
3032
 FORMAT_HINTS = {
@@ -141,9 +143,12 @@ class ExportDialog(Adw.Dialog):
141143
             if self.scope.get_active_name() != scope:
142144
                 self.scope.set_active_name(scope)
143145
             self._updating = False
146
+        game = self.scope.get_active_name() == "game"
147
+        shown = {name for name in self.switches if name in fmt.options and
148
+                 (name != "variations" or game and bool(self.state.variations))}
144149
         for name, row in self.switches.items():
145
-            row.set_visible(name in fmt.options)
146
-        self.look.set_visible(any(name in fmt.options for name in self.switches))
150
+            row.set_visible(name in shown)
151
+        self.look.set_visible(bool(shown))
147152
         self.copy_btn.set_sensitive(fmt.clipboard)
148153
         self.copy_btn.set_tooltip_text(None if fmt.clipboard else "PDF lässt sich nur als Datei speichern")
149154
 

modified schach/movelist.py +57 −11

@@ -20,6 +20,14 @@ CSS = b"""
2020
 }
2121
 .move-pill.selected-move { background: @accent_bg_color; color: @accent_fg_color; }
2222
 .move-row-buttons button { min-height: 22px; min-width: 22px; padding: 1px; }
23
+.variation-row { padding: 2px 8px 2px 30px; }
24
+.variation-pill {
25
+  background: alpha(@accent_bg_color, 0.12);
26
+  border-radius: 6px;
27
+  padding: 1px 7px;
28
+  font-size: smaller;
29
+}
30
+.variation-pill.selected-move { background: @accent_bg_color; color: @accent_fg_color; }
2331
 """
2432
 
2533
 
@@ -40,6 +48,7 @@ class MoveList(Gtk.Box):
4048
         self.on_copy = None  # callback(halbzug)
4149
         self.on_continue = None  # callback(halbzug)
4250
         self.on_why_not = None  # callback(halbzug): „Warum nicht?“ bei ?!, ? und ??
51
+        self.on_variation = None  # callback(nummer): Nebenvariante vom Analysebrett angeklickt
4352
 
4453
         header = Gtk.Box(spacing=6, margin_start=12, margin_end=6, margin_top=6, margin_bottom=6)
4554
         header.append(Gtk.Box(hexpand=True))  # Überschrift steht schon im Umschalter „Partie | Buch | Lichess“
@@ -58,25 +67,36 @@ class MoveList(Gtk.Box):
5867
 
5968
         self.notation = "de"  # Schreibweise der Züge, siehe notation.py
6069
         self._rows = []
70
+        self._variation_rows = []
6171
         self._selected = None
72
+        self._selected_variation = None
6273
         self._signature = None
6374
         self._updating = False
6475
 
6576
     # --- Aufbau ------------------------------------------------------------
6677
 
67
-    def update(self, board, evals, symbols, selected):
68
-        """Baut die Liste neu, wenn sich Züge, Bewertungen oder Zeichen geändert haben."""
78
+    def update(self, board, evals, symbols, selected, variations=(), selected_variation=None):
79
+        """Baut die Liste neu, wenn sich Züge, Bewertungen, Zeichen oder Varianten geändert haben.
80
+
81
+        ``variations``: [(Halbzug, Text)] – Nebenvarianten vom Analysebrett, eingerückt unter dem Zug,
82
+        nach dem sie abzweigen (-1: vor dem ersten Zug). ``selected_variation``: Nummer darin."""
6983
         moves = list(board.move_stack)
70
-        signature = (tuple(moves), tuple(sorted(evals.items())), tuple(sorted(symbols.items())), self.notation)
84
+        signature = (tuple(moves), tuple(sorted(evals.items())), tuple(sorted(symbols.items())), self.notation,
85
+                     tuple(variations))
7186
         if signature != self._signature:
7287
             self._signature = signature
73
-            self._rebuild(board, moves, evals, symbols)
74
-        self._apply_selection(selected)
88
+            self._rebuild(board, moves, evals, symbols, variations)
89
+        self._apply_selection(selected, selected_variation)
7590
 
76
-    def _rebuild(self, board, moves, evals, symbols):
91
+    def _rebuild(self, board, moves, evals, symbols, variations=()):
7792
         self._updating = True
7893
         self.listbox.remove_all()
7994
         self._rows = []
95
+        self._variation_rows = []
96
+        after = {}
97
+        for index, (ply, text) in enumerate(variations):
98
+            after.setdefault(ply, []).append((index, text))
99
+        ordered = [self._make_variation_row(i, t) for i, t in after.get(-1, [])]
80100
         replay = board.root()
81101
         for ply, move in enumerate(moves):
82102
             number = replay.fullmove_number
@@ -84,7 +104,9 @@ class MoveList(Gtk.Box):
84104
             san = notation.move(replay, move, self.notation)
85105
             replay.push(move)
86106
             self._rows.append(self._make_row(ply, prefix, san, symbols.get(ply), evals.get(ply)))
87
-        for row, _ in self._rows:
107
+            ordered.append(self._rows[-1][0])
108
+            ordered += [self._make_variation_row(i, t) for i, t in after.get(ply, [])]
109
+        for row in ordered:
88110
             self.listbox.append(row)
89111
         self._updating = False
90112
         if self._rows:
@@ -140,6 +162,19 @@ class MoveList(Gtk.Box):
140162
         row.add_controller(hover)
141163
         return row, buttons
142164
 
165
+    def _make_variation_row(self, index, text):
166
+        """Eingerückte Zeile für eine Nebenvariante: „↳ 4. a3 Sxe4 5. d4 …“."""
167
+        pill = Gtk.Label(use_markup=True, label=f"↳ {text}", css_classes=["variation-pill"],
168
+                         ellipsize=3, xalign=0)  # 3 = Pango.EllipsizeMode.END
169
+        content = Gtk.Box(css_classes=["variation-row"])
170
+        content.append(pill)
171
+        row = Gtk.ListBoxRow(child=content, tooltip_text="Nebenvariante vom Analysebrett")
172
+        row.ply = None
173
+        row.variation = index
174
+        row.pill = pill
175
+        self._variation_rows.append(row)
176
+        return row
177
+
143178
     @staticmethod
144179
     def _draw_bar(area, cr, width, height, white_pct):
145180
         if white_pct is None:
@@ -160,15 +195,22 @@ class MoveList(Gtk.Box):
160195
 
161196
     # --- Auswahl -----------------------------------------------------------
162197
 
163
-    def _apply_selection(self, selected):
198
+    def _apply_selection(self, selected, selected_variation=None):
164199
         self._updating = True
165
-        if selected is None or selected < 0 or selected >= len(self._rows):
200
+        if selected_variation is not None and 0 <= selected_variation < len(self._variation_rows):
201
+            self.listbox.select_row(self._variation_rows[selected_variation])
202
+        elif selected is None or selected < 0 or selected >= len(self._rows):
166203
             self.listbox.unselect_all()
167204
         else:
168205
             self.listbox.select_row(self._rows[selected][0])
169206
         self._updating = False
170
-        self._show_buttons(selected)
171
-        self.live_btn.set_sensitive(selected is not None)
207
+        self._show_buttons(None if selected_variation is not None else selected)
208
+        for index, row in enumerate(self._variation_rows):
209
+            if index == selected_variation:
210
+                row.pill.add_css_class("selected-move")
211
+            else:
212
+                row.pill.remove_css_class("selected-move")
213
+        self.live_btn.set_sensitive(selected is not None or selected_variation is not None)
172214
 
173215
     def _show_buttons(self, selected):
174216
         self._selected = selected
@@ -182,6 +224,10 @@ class MoveList(Gtk.Box):
182224
     def _on_row_selected(self, listbox, row):
183225
         if self._updating:
184226
             return
227
+        if row is not None and getattr(row, "variation", None) is not None:
228
+            if self.on_variation:
229
+                self.on_variation(row.variation)
230
+            return
185231
         self._select(row.ply if row is not None else None)
186232
 
187233
     def _select(self, ply):

modified schach/savegames.py +24 −0

@@ -13,6 +13,7 @@ import re
1313
 
1414
 import chess
1515
 import chess.pgn
16
+import chess.svg
1617
 from gi.repository import GLib
1718
 
1819
 from .annotate import NAG
@@ -38,6 +39,9 @@ class GameState:
3839
     opponent: str = ""  # Gegnername, wenn nicht Maia
3940
     final_text: str = ""  # Partie-Ende, das nicht am Brett ablesbar ist (Aufgabe, Zeit …)
4041
     names: tuple = ()  # (Weiß, Schwarz) bei fremden Partien, an denen man selbst nicht beteiligt war
42
+    # Nebenvarianten vom Analysebrett: {Halbzug: [Variante]}, hängen nach diesem Halbzug (-1: vor dem
43
+    # ersten Zug). Variante = (Zug, Kommentar, Pfeile ((von, nach, Farbe), …), [Fortsetzungen])
44
+    variations: dict = dataclasses.field(default_factory=dict)
4145
 
4246
     def truncated(self, ply):
4347
         """Kopie bis einschließlich Halbzug ``ply`` (für Abzweigungen)."""
@@ -83,15 +87,35 @@ def to_pgn(state):
8387
     if root.fen() != chess.STARTING_FEN:
8488
         game.setup(root)
8589
     node = game
90
+    played = {-1: game}
8691
     for ply, move in enumerate(state.board.move_stack):
8792
         node = node.add_variation(move)
93
+        played[ply] = node
8894
         if ply in state.symbols:
8995
             node.nags.add(NAG[state.symbols[ply]])
9096
         if ply in state.evals:
9197
             node.comment = f"[%wp {state.evals[ply]:.1f}]"
98
+    for ply, variations in sorted(state.variations.items()):
99
+        if ply in played:
100
+            for variation in variations:
101
+                _add_variation(played[ply], variation)
92102
     return str(game) + "\n"
93103
 
94104
 
105
+# Pfeilfarben des Analysebretts als PGN-Farben ([%cal Bd2d4]): eigene Züge blau, Gegner gelb
106
+PGN_COLOR = {"hint": "blue", "threat": "yellow", "red": "red", "green": "green"}
107
+
108
+
109
+def _add_variation(parent, variation):
110
+    move, comment, shapes, children = variation
111
+    if move not in parent.board().legal_moves:
112
+        return
113
+    node = parent.add_variation(move, comment=comment or "")
114
+    node.set_arrows(chess.svg.Arrow(tail, head, color=PGN_COLOR.get(color, "green")) for tail, head, color in shapes)
115
+    for child in children:
116
+        _add_variation(node, child)
117
+
118
+
95119
 def from_pgn(text, path=""):
96120
     game = chess.pgn.read_game(io.StringIO(text))
97121
     if game is None:

modified schach/training.py +58 −0

@@ -572,6 +572,64 @@ class OpeningMixin:
572572
         if self._game_tree() is not self.demo["tree"]:
573573
             self.demo = None
574574
 
575
+    def _game_variations(self):
576
+        """Selbst gezogene Nebenvarianten für PGN: {Halbzug: [(Zug, Kommentar, Pfeile, [Fortsetzungen])]}."""
577
+        tree = self.game_tree
578
+        if tree is None or not self.board.move_stack or self._game_tree() is not tree:
579
+            return {}
580
+
581
+        def pack(node):
582
+            return (node.move, node.comment, tree.shapes(node), [pack(c) for c in node.variations])
583
+        found, node, ply = {}, tree.game, -1
584
+        while True:
585
+            side = [c for c in node.variations if not tree.meta.get(c, {}).get("played")]
586
+            if side:
587
+                found[ply] = [pack(c) for c in side]
588
+            main = node.variations[0] if node.variations else None
589
+            if main is None or not tree.meta.get(main, {}).get("played"):
590
+                return found
591
+            node, ply = main, ply + 1
592
+
593
+    VARIATION_PLIES = 8  # so viele Halbzüge zeigt eine Variantenzeile der Zugliste, dann „…“
594
+
595
+    def _list_variations(self):
596
+        """Nebenvarianten für die Zugliste: [(Halbzug, Text, Knoten)], Text als Pango-Markup."""
597
+        tree = self.game_tree
598
+        if tree is None or not self._analysis_allowed() or self._game_tree() is not tree:
599
+            return []
600
+        style = self._notation()
601
+        found, node, ply = [], tree.game, -1
602
+        while True:
603
+            for child in node.variations:
604
+                if tree.meta.get(child, {}).get("played"):
605
+                    continue
606
+                words, step, board = [], child, node.board()
607
+                while step is not None and len(words) < self.VARIATION_PLIES:
608
+                    if board.turn == chess.WHITE or not words:
609
+                        words.append(f"{board.fullmove_number}." if board.turn == chess.WHITE
610
+                                     else f"{board.fullmove_number}…")
611
+                    words.append(notation.move(board, step.move, style))
612
+                    board.push(step.move)
613
+                    step = step.variations[0] if step.variations else None
614
+                text = " ".join(words) + (" …" if step is not None else "")
615
+                found.append((ply, _escape(text), child))
616
+            main = node.variations[0] if node.variations else None
617
+            if main is None or not tree.meta.get(main, {}).get("played"):
618
+                return found
619
+            node, ply = main, ply + 1
620
+
621
+    def _analysis_open_node(self, node):
622
+        """Analysebrett an einem Knoten des Partiebaums (z. B. Klick auf eine Variantenzeile)."""
623
+        self._analysis_open(-1, show=False)
624
+        step = node
625
+        while step.parent is not None:
626
+            self.demo["chosen"][step.parent] = step
627
+            step = step.parent
628
+        self.demo["node"] = node
629
+        self.view.animate_move(node.parent.board(), node.move)
630
+        self._refresh()
631
+        self._coach_show()
632
+
575633
     PLAYED_WORDS = {"!!": "Ein brillanter Zug.", "!": "Ein starker Zug.", "?!": "Ungenau.", "?": "Ein Fehler.",
576634
                     "??": "Ein grober Fehler."}
577635
 

modified tests/test_export.py +29 −1

@@ -1,5 +1,5 @@
11
 import io
2
-from html import escape as html_escape
2
+from html import escape as html_escape, unescape
33
 import re
44
 import shutil
55
 import subprocess
@@ -79,6 +79,34 @@ class TextFormatsTest(unittest.TestCase)
7979
         self.assertTrue(export.caption(chess.Board()).startswith("Ausgangsstellung"))
8080
 
8181
 
82
+class VariationTest(unittest.TestCase):
83
+    """Nebenvarianten vom Analysebrett: in PGN und HTML, abschaltbar."""
84
+
85
+    def state(self):
86
+        state = sample()
87
+        m = chess.Move.from_uci
88
+        # nach 3. Lc4 (Halbzug 4): 3… Sf6 statt 3… Sd4, mit Kommentar, Pfeil und Fortsetzung
89
+        state.variations = {4: [(m("g8f6"), "So spielt Maia 600 oft.", ((chess.G8, chess.F6, "threat"),),
90
+                                 [(m("f3g5"), "Du greifst f7 an.", (), [])])]}
91
+        return state
92
+
93
+    def test_pgn_contains_variation_with_comment_and_arrow(self):
94
+        text = savegames.to_pgn(self.state())
95
+        self.assertIn("( 3... Nf6 { [%cal Yg8f6] So spielt Maia 600 oft. } 4. Ng5 { Du greifst f7 an. } )", text)
96
+        game = chess.pgn.read_game(io.StringIO(text))
97
+        self.assertEqual([n.san() for n in game.mainline()], MOVES)  # Hauptlinie bleibt die Partie
98
+
99
+    def test_export_can_drop_variations(self):
100
+        with_them = export.export("pgn", self.state(), opts(scope="game"))
101
+        without = export.export("pgn", self.state(), opts(scope="game", variations=False))
102
+        self.assertIn("3... Nf6", with_them)
103
+        self.assertNotIn("3... Nf6", without)
104
+
105
+    def test_html_shows_variation_without_commands(self):
106
+        page = export.export("html", self.state(), opts(scope="game"))
107
+        self.assertIn("( 3... Nf6 { So spielt Maia 600 oft. } 4. Ng5", unescape(page))
108
+
109
+
82110
 class LatexTest(unittest.TestCase):
83111
     def test_game_splits_mainline_at_diagram(self):
84112
         tex = export.export("latex", sample(), opts(scope="game", plies=8, flipped=True))