Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(opening): several Warum demos per move, split button

public

feat(opening): several Warum demos per move, split button

A demo starting with a playable sibling move explains that move;
otherwise it stays a what-if for the main move. The checker flags
more than MAX_DEMOS questions or duplicate titles.

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

modified ROADMAP.md +7 −0

@@ -389,6 +389,13 @@ Erklärung:
389389
   „Heute dran: 2 zum Wiederholen und 5 neu (von 13 Linien)“, das Ende einer Linie
390390
   „Diese Linie kommt in 3 Tagen wieder.“ Gespeichert in
391391
   `~/.local/share/schach/training.json`.
392
+- **„Warum?“-Vorführungen** (umgesetzt 20.11.2026): Nebenvarianten mit `[%warum]`
393
+  oder `[%warum Frage?]` spielt der Gegner nie. Sie laufen als kleiner Film mit Pfeilen
394
+  auf dem Brett. Beginnt eine Vorführung mit einem Kurszug, erklärt sie diesen Zug,
395
+  sonst ist sie ein „Was wäre, wenn …“ zum Hauptzug. Bis zu drei Fragen pro Zug: eine
396
+  als Knopf, mehrere als Split-Button mit Menü. `tools/kurse_pruefen.py` prüft alle
397
+  Kurse mit Stockfish (Kurszüge, unerklärte Gegnerfehler, Linienenden, Pfeile,
398
+  zu viele oder doppelte Fragen).
392399
 - **Eröffnung in eigenen Partien:** Nach einer Partie gegen Maia steht in der
393400
   Zugliste „Buch bis Zug 6, dann Abweichung: Kurs empfiehlt …“. So merkt Florian
394401
   in echten Partien, wo er den Plan verlassen hat.

modified schach/opening.py +11 −5

@@ -63,7 +63,7 @@ class Course:
6363
     reached: set  # alle Stellungs-Hashes, die im Kurs vorkommen (auch Endstellungen)
6464
     path: str = ""
6565
     welcome_shapes: tuple = ()
66
-    demos: dict = dataclasses.field(default_factory=dict)  # (Stellungs-Hash, erklärter Zug) -> Demo
66
+    demos: dict = dataclasses.field(default_factory=dict)  # (Stellungs-Hash, erklärter Zug) -> [Demo]
6767
 
6868
     def start(self):
6969
         return chess.Board(self.start_fen)
@@ -77,13 +77,14 @@ class Course:
7777
     def knows(self, board):
7878
         return key(board) in self.reached
7979
 
80
-    def demo(self, board, move):
81
-        """Vorführung zum Zug ``move`` in ``board`` – oder None."""
82
-        return self.demos.get((key(board), move))
80
+    def demos_for(self, board, move):
81
+        """Vorführungen zum Zug ``move`` in ``board``, in Kursreihenfolge (oft keine)."""
82
+        return self.demos.get((key(board), move), [])
8383
 
8484
 
8585
 COMMAND_RE = re.compile(r"\[%[^\]]*\]")
8686
 WARUM_RE = re.compile(r"\[%warum\s*([^\]]*)\]")
87
+MAX_DEMOS = 3  # mehr „Warum?“-Fragen zu einem Zug überfordern eher (das Prüfskript warnt)
8788
 
8889
 
8990
 def clean_comment(text):
@@ -107,6 +108,8 @@ def parse_course(text, path=""):
107108
     def walk(node):
108109
         board = node.board()
109110
         reached.add(key(board))
111
+        # Züge, die wirklich gespielt werden (ohne Vorführungen)
112
+        playable = {c.move for i, c in enumerate(node.variations) if i == 0 or not WARUM_RE.search(c.comment)}
110113
         for index, child in enumerate(node.variations):
111114
             warum = WARUM_RE.search(child.comment)
112115
             if warum and index > 0:
@@ -114,7 +117,10 @@ def parse_course(text, path=""):
114117
                 while step is not None:
115118
                     steps.append((step.move, clean_comment(step.comment), shapes(step)))
116119
                     step = step.variations[0] if step.variations else None
117
-                demos[(key(board), node.variations[0].move)] = Demo(board.fen(), steps, warum.group(1).strip())
120
+                # beginnt mit einem Kurszug: erklärt diesen; sonst „Was wäre, wenn …“ zum Hauptzug
121
+                explained = child.move if child.move in playable else node.variations[0].move
122
+                demos.setdefault((key(board), explained), []).append(
123
+                    Demo(board.fen(), steps, warum.group(1).strip()))
118124
                 continue
119125
             options = positions.setdefault(key(board), [])
120126
             existing = next((o for o in options if o.move == child.move), None)

modified schach/training.py +49 −25

@@ -14,7 +14,7 @@ import gi
1414
 
1515
 gi.require_version("Gtk", "4.0")
1616
 gi.require_version("Adw", "1")
17
-from gi.repository import Adw, GLib, Gtk  # noqa: E402
17
+from gi.repository import Adw, Gio, GLib, Gtk  # noqa: E402
1818
 
1919
 from . import annotate, notation, opening, repetition  # noqa: E402
2020
 from .engines import maia_candidates  # noqa: E402
@@ -87,7 +87,7 @@ class OpeningMixin:
8787
         self._name_cache = {}
8888
         self.coach_log = []  # Rückmeldungen: {"ply": Halbzug der zugehörigen Stellung, "markup": Text}
8989
         self.coach_index = None  # angezeigte Rückmeldung; None = die neueste
90
-        self.demo = None  # laufende „Warum?“-Vorführung: {"demo": Demo, "label": "h3", "index": Schritt}
90
+        self.demo = None  # laufende „Warum?“-Vorführung: {"demo": Demo, "label": "Warum h3?", "index": Schritt}
9191
 
9292
     # --- Oberfläche --------------------------------------------------------
9393
 
@@ -107,7 +107,15 @@ class OpeningMixin:
107107
         self.coach_button.set_action_name("win.opening-continue")
108108
         self.coach_why = Gtk.Button(valign=Gtk.Align.CENTER, visible=False, margin_end=10,
109109
                                     tooltip_text="Zeigt auf dem Brett, was hinter dem Zug steckt")
110
-        self.coach_why.connect("clicked", lambda *_: self._demo_start())
110
+        self.coach_why.connect("clicked", lambda *_: self._demo_start(0))
111
+        # mehrere Fragen zum selben Zug: die erste per Klick, die anderen im Menü
112
+        self.coach_why_more = Adw.SplitButton(valign=Gtk.Align.CENTER, visible=False, margin_end=10,
113
+                                              tooltip_text="Zeigt auf dem Brett, was hinter dem Zug steckt",
114
+                                              dropdown_tooltip="Weitere Fragen zu diesem Zug")
115
+        self.coach_why_more.connect("clicked", lambda *_: self._demo_start(0))
116
+        action = Gio.SimpleAction.new("coach-demo", GLib.VariantType.new("i"))
117
+        action.connect("activate", lambda _a, value: self._demo_start(value.get_int32()))
118
+        self.add_action(action)
111119
         # Blättern durch die letzten Rückmeldungen; das Brett zeigt die Stellung dazu
112120
         self.coach_nav = Gtk.Box(spacing=2, valign=Gtk.Align.CENTER, margin_end=6)
113121
         self.coach_prev = Gtk.Button(icon_name="go-previous-symbolic", tooltip_text="Vorherige Rückmeldung",
@@ -126,17 +134,19 @@ class OpeningMixin:
126134
         card.append(self.coach_label)
127135
         card.append(self.coach_nav)
128136
         card.append(self.coach_why)
137
+        card.append(self.coach_why_more)
129138
         card.append(self.coach_button)
130139
         self.coach = Gtk.Revealer(child=card, transition_type=Gtk.RevealerTransitionType.SLIDE_UP)
131140
         return self.coach
132141
 
133
-    def _coach(self, markup, ply=None, replace=False, shapes=(), demo=None):
142
+    def _coach(self, markup, ply=None, replace=False, shapes=(), demos=()):
134143
         """Neue Rückmeldung zur Stellung nach Halbzug ``ply`` (Standard: aktuelle Stellung).
135144
 
136145
         ``shapes``: Pfeile und Felder aus dem Kurskommentar, solange diese Rückmeldung zu sehen ist.
146
+        ``demos``: „Warum?“-Vorführungen dazu, [{"demo": Demo, "label": Frage}].
137147
         """
138148
         entry = {"ply": len(self.board.move_stack) - 1 if ply is None else ply, "markup": markup,
139
-                 "shapes": tuple(shapes), "demo": demo}
149
+                 "shapes": tuple(shapes), "demos": list(demos)}
140150
         self.demo = None
141151
         if replace and self.coach_log:
142152
             self.coach_log[-1] = entry
@@ -150,7 +160,7 @@ class OpeningMixin:
150160
         if self.demo is not None:
151161
             self._demo_show()
152162
             return
153
-        self.coach_why.set_visible(False)
163
+        self._coach_why_show(())
154164
         if not self.coach_log:
155165
             self.coach.set_reveal_child(False)
156166
             self.view.shapes = ()
@@ -166,12 +176,22 @@ class OpeningMixin:
166176
         self.coach_last.set_sensitive(index < last)
167177
         self.coach_button.set_visible(self.final_text is not None and index == last)
168178
         self.coach_last.set_tooltip_text("Zum aktuellen Zug")
169
-        why = self.coach_log[index].get("demo")
170
-        if why is not None:
171
-            self.coach_why.set_label(why["label"])
172
-        self.coach_why.set_visible(why is not None)
179
+        self._coach_why_show(self.coach_log[index].get("demos", ()))
173180
         self.coach.set_reveal_child(True)
174181
 
182
+    def _coach_why_show(self, demos):
183
+        """Eine Frage: einfacher Knopf. Mehrere: Split-Button, die übrigen im Menü."""
184
+        self.coach_why.set_visible(len(demos) == 1)
185
+        self.coach_why_more.set_visible(len(demos) > 1)
186
+        if len(demos) == 1:
187
+            self.coach_why.set_label(demos[0]["label"])
188
+        elif demos:
189
+            self.coach_why_more.set_label(demos[0]["label"])
190
+            menu = Gio.Menu()
191
+            for number, why in enumerate(demos[1:], start=1):
192
+                menu.append(why["label"].replace("_", "__"), f"win.coach-demo({number})")
193
+            self.coach_why_more.set_menu_model(menu)
194
+
175195
     def _coach_step(self, delta):
176196
         if self.demo is not None:
177197
             self._demo_step(delta)
@@ -198,20 +218,24 @@ class OpeningMixin:
198218
 
199219
     # --- „Warum?“-Vorführung ----------------------------------------------
200220
 
201
-    def _demo_entry(self, before, move):
202
-        demo = self.course.demo(before, move) if self.course else None
203
-        if demo is None:
204
-            return None
205
-        title = notation.text(demo.title, self._notation()) if demo.title else (
206
-            f"Warum {notation.move(before, move, self._notation())}?")
207
-        return {"demo": demo, "label": title}
221
+    def _demo_entries(self, before, move):
222
+        """Die „Warum?“-Fragen zu ``move`` für die Coach-Leiste (leer, wenn es keine gibt)."""
223
+        if not self.course:
224
+            return []
225
+        entries = []
226
+        for demo in self.course.demos_for(before, move):
227
+            title = notation.text(demo.title, self._notation()) if demo.title else (
228
+                f"Warum {notation.move(before, move, self._notation())}?")
229
+            entries.append({"demo": demo, "label": title})
230
+        return entries
208231
 
209
-    def _demo_start(self):
232
+    def _demo_start(self, number=0):
210233
         last = len(self.coach_log) - 1
211234
         index = last if self.coach_index is None else self.coach_index
212
-        why = self.coach_log[index].get("demo") if self.coach_log else None
213
-        if why is None:
235
+        demos = self.coach_log[index].get("demos", ()) if self.coach_log else ()
236
+        if not 0 <= number < len(demos):
214237
             return
238
+        why = demos[number]
215239
         self.demo = dict(why, index=0)
216240
         demo = why["demo"]
217241
         self.view.animate_move(chess.Board(demo.start_fen), demo.steps[0][0])
@@ -266,7 +290,7 @@ class OpeningMixin:
266290
         self.coach_next.set_sensitive(index < len(demo.steps) - 1)
267291
         self.coach_last.set_sensitive(True)
268292
         self.coach_last.set_tooltip_text("Zurück zur Partie")
269
-        self.coach_why.set_visible(False)
293
+        self._coach_why_show(())
270294
         self.coach_button.set_visible(False)
271295
         self.coach.set_reveal_child(True)
272296
 
@@ -440,14 +464,14 @@ class OpeningMixin:
440464
             return False
441465
         label = notation.label(self.board, option.move, self._notation())
442466
         # „Warum?“ zum eigenen Zug davor bleibt erreichbar, auch wenn der Gegner schon geantwortet hat
443
-        why = self._demo_entry(self.board, option.move) or (
444
-            self.coach_log[-1].get("demo") if self.coach_log else None)
467
+        why = self._demo_entries(self.board, option.move) or (
468
+            self.coach_log[-1].get("demos", ()) if self.coach_log else ())
445469
         self.view.animate_move(self.board, option.move)
446470
         self.board.push(option.move)
447471
         self.opening_busy = False
448472
         self._changed()
449473
         comment = f" – {_escape(notation.text(option.comment, self._notation()))}" if option.comment else ""
450
-        self._coach(f"<b>{_escape(label)}</b>{comment}", shapes=option.shapes, demo=why)
474
+        self._coach(f"<b>{_escape(label)}</b>{comment}", shapes=option.shapes, demos=why)
451475
         self._refresh()
452476
         if not self.course.options(self.board):
453477
             self._opening_finished()
@@ -470,7 +494,7 @@ class OpeningMixin:
470494
                 comment = "Zugumstellung – auch so kommst du zu unserem Ziel."
471495
             self._coach(f"✓ <b>{label}</b> – {_escape(notation.text(comment, self._notation()))}",
472496
                         shapes=verdict.option.shapes if verdict.option else (),
473
-                        demo=self._demo_entry(before, move))
497
+                        demos=self._demo_entries(before, move))
474498
             self._refresh()
475499
             self._opening_next_step()
476500
             return

modified tests/test_opening.py +15 −3

@@ -49,15 +49,27 @@ class CourseTest(unittest.TestCase):
4949
             '( 2. Qh5 { [%warum] Stell dir vor … } 2... Nc6 { Gedeckt. [%cal Gc6e5] } ) 2... Nc6 *')
5050
         before = play("e4", "e5")
5151
         self.assertEqual([o.move.uci() for o in course.options(before)], ["g1f3"])
52
-        demo = course.demo(before, chess.Move.from_uci("g1f3"))
52
+        [demo] = course.demos_for(before, chess.Move.from_uci("g1f3"))
5353
         self.assertEqual([m.uci() for m, _c, _s in demo.steps], ["d1h5", "b8c6"])
5454
         self.assertEqual(demo.steps[0][1], "Stell dir vor …")
5555
         self.assertEqual(demo.steps[1][2], ((chess.C6, chess.E5, "green"),))
5656
         self.assertEqual(demo.board_at(1).fen().split()[0], "r1bqkbnr/pppp1ppp/2n5/4p2Q/4P3/8/PPPP1PPP/RNB1KBNR")
57
-        self.assertIsNone(course.demo(before, chess.Move.from_uci("d1h5")))
57
+        self.assertEqual(course.demos_for(before, chess.Move.from_uci("d1h5")), [])
5858
         self.assertEqual(demo.title, "")
5959
         titled = opening.parse_course('[Event "T"]\n\n1. e4 ( 1. e4 { [%warum Wozu e4?] x } ) *')
60
-        self.assertEqual(titled.demo(chess.Board(), chess.Move.from_uci("e2e4")).title, "Wozu e4?")
60
+        self.assertEqual(titled.demos_for(chess.Board(), chess.Move.from_uci("e2e4"))[0].title, "Wozu e4?")
61
+
62
+    def test_several_demos_per_move_and_demo_for_alternative(self):
63
+        course = opening.parse_course(
64
+            '[Event "T"]\n\n1. e4 e5 2. Nf3 ( 2. Nf3 { [%warum Wozu Sf3?] a } 2... Nc6 ) '
65
+            '( 2. Qh5 { [%warum Und Dh5?] b } 2... Nc6 ) ( 2. Bc4 { auch gut } ) '
66
+            '( 2. Bc4 { [%warum Warum Lc4?] c } 2... Nf6 ) 2... Nc6 *')
67
+        before = play("e4", "e5")
68
+        main = course.demos_for(before, chess.Move.from_uci("g1f3"))
69
+        self.assertEqual([d.title for d in main], ["Wozu Sf3?", "Und Dh5?"])  # Was-wäre-wenn hängt am Hauptzug
70
+        alt = course.demos_for(before, chess.Move.from_uci("f1c4"))
71
+        self.assertEqual([d.title for d in alt], ["Warum Lc4?"])  # erklärt die Alternative selbst
72
+        self.assertEqual({o.move.uci() for o in course.options(before)}, {"g1f3", "f1c4"})
6173
 
6274
     def test_options_main_first(self):
6375
         italian = self.courses["Italienisch"]

modified tools/kurse_pruefen.py +12 −0

@@ -5,6 +5,7 @@ Meldet:
55
 - Kurszüge der lernenden Seite, die deutlich schlechter sind als Stockfishs bester Zug,
66
 - grobe Fehler der Gegenseite (manchmal Absicht – dann sollte es im Kommentar stehen),
77
 - Linienenden, an denen die lernende Seite schlechter steht,
8
+- Züge mit mehr als drei „Warum?“-Fragen (opening.MAX_DEMOS) und doppelte Fragen,
89
 - Pfeile, deren Weg durch eine eigene Figur führt (zum Ansehen: Abzugsangriff, Plan oder Fehler),
910
 - und den Bewertungsverlauf jeder „Warum?“-Vorführung zum Gegenlesen.
1011
 
@@ -164,6 +165,17 @@ def check_course(path, ev):
164165
             walk(child, demo, log)
165166
 
166167
     walk(game, False, None)
168
+    with open(path) as fh:
169
+        course = opening.parse_course(fh.read(), path)
170
+    for (position, move), group in course.demos.items():
171
+        board = chess.Board(group[0].start_fen)
172
+        san = board.san(move)
173
+        titles = [d.title or f"Warum {san}?" for d in group]
174
+        if len(group) > opening.MAX_DEMOS:
175
+            findings.append(f"Zu viele Fragen zu {san} nach {group[0].start_fen}: {len(group)} (höchstens "
176
+                            f"{opening.MAX_DEMOS})")
177
+        if len(set(titles)) < len(titles):
178
+            findings.append(f"Gleiche Frage doppelt zu {san} nach {group[0].start_fen}: {titles}")
167179
     return title, findings, demos, arrows
168180
 
169181