Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(training): "Warum?" demos from [%warum] side lines

public

feat(training): "Warum?" demos from [%warum] side lines

A side line whose first comment holds [%warum] is never played; it
becomes a demo for the main move there. Coach bar shows
"Warum h3?", pages through the demo with arrows, >> or Esc goes
back. The opponent's reply keeps the button for the move before.

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

modified schach/app.py +7 −2

@@ -478,7 +478,7 @@ class Window(OnlineMixin, PuzzleMixin, O
478478
         return self._end_text() is not None
479479
 
480480
     def _human_to_move(self):
481
-        if self.mode in ("review", "setup"):
481
+        if self.mode in ("review", "setup") or self.demo is not None:
482482
             return False
483483
         if self.mode == "puzzle" and self.puzzle is None:
484484
             return False
@@ -533,6 +533,9 @@ class Window(OnlineMixin, PuzzleMixin, O
533533
         if self.mode == "setup":
534534
             self._setup_refresh()
535535
             return
536
+        if self.demo is not None:
537
+            self._demo_refresh()
538
+            return
536539
         v = self.view
537540
         v.human = self.human
538541
         if self._browsing():
@@ -683,7 +686,7 @@ class Window(OnlineMixin, PuzzleMixin, O
683686
         self.undo_btn.set_visible(self.mode in ("maia", "opening", "online", "duo"))
684687
         self._action("offer-draw").set_enabled(self._online_running() and len(self.board.move_stack) >= 2)
685688
         self._action("resign").set_enabled(self._online_running() and self.online_full is not None)
686
-        self._action("end-browse").set_enabled(self.browse_ply is not None)
689
+        self._action("end-browse").set_enabled(self.browse_ply is not None or self.demo is not None)
687690
         logged_in = self.get_application().lichess_user is not None
688691
         self._action("challenge").set_enabled(logged_in)
689692
         self._action("lichess-games").set_enabled(logged_in)
@@ -1243,6 +1246,8 @@ class Window(OnlineMixin, PuzzleMixin, O
12431246
         self._refresh()
12441247
 
12451248
     def _end_browse(self, *_):
1249
+        if self.demo is not None:
1250
+            return self._demo_end()
12461251
         if self.browse_ply is None:
12471252
             return False
12481253
         self.browse_ply = None

modified schach/opening.py +27 −1

@@ -36,6 +36,19 @@ class Option:
3636
 
3737
 
3838
 @dataclasses.dataclass
39
+class Demo:
40
+    """„Warum?“-Vorführung: Nebenvariante mit [%warum], die der Gegner nie spielt."""
41
+    start_fen: str  # Stellung vor dem ersten Zug der Vorführung
42
+    steps: list  # [(Zug, Kommentar, Pfeile)]
43
+
44
+    def board_at(self, index):
45
+        board = chess.Board(self.start_fen)
46
+        for move, _c, _s in self.steps[: index + 1]:
47
+            board.push(move)
48
+        return board
49
+
50
+
51
+@dataclasses.dataclass
3952
 class Course:
4053
     title: str
4154
     color: bool
@@ -46,6 +59,7 @@ class Course:
4659
     reached: set  # alle Stellungs-Hashes, die im Kurs vorkommen (auch Endstellungen)
4760
     path: str = ""
4861
     welcome_shapes: tuple = ()
62
+    demos: dict = dataclasses.field(default_factory=dict)  # (Stellungs-Hash, erklärter Zug) -> Demo
4963
 
5064
     def start(self):
5165
         return chess.Board(self.start_fen)
@@ -59,6 +73,10 @@ class Course:
5973
     def knows(self, board):
6074
         return key(board) in self.reached
6175
 
76
+    def demo(self, board, move):
77
+        """Vorführung zum Zug ``move`` in ``board`` – oder None."""
78
+        return self.demos.get((key(board), move))
79
+
6280
 
6381
 COMMAND_RE = re.compile(r"\[%[^\]]*\]")
6482
 
@@ -79,12 +97,19 @@ def parse_course(text, path=""):
7997
     if game.errors:
8098
         raise ValueError(f"Fehler im Kurs: {game.errors[0]}")
8199
     headers = game.headers
82
-    positions, reached = {}, set()
100
+    positions, reached, demos = {}, set(), {}
83101
 
84102
     def walk(node):
85103
         board = node.board()
86104
         reached.add(key(board))
87105
         for index, child in enumerate(node.variations):
106
+            if "[%warum" in child.comment and index > 0:
107
+                steps, step = [], child
108
+                while step is not None:
109
+                    steps.append((step.move, clean_comment(step.comment), shapes(step)))
110
+                    step = step.variations[0] if step.variations else None
111
+                demos[(key(board), node.variations[0].move)] = Demo(board.fen(), steps)
112
+                continue
88113
             options = positions.setdefault(key(board), [])
89114
             existing = next((o for o in options if o.move == child.move), None)
90115
             comment = clean_comment(child.comment)
@@ -105,6 +130,7 @@ def parse_course(text, path=""):
105130
         intro=headers.get("SchachIntro", ""),
106131
         welcome=clean_comment(game.comment),
107132
         welcome_shapes=shapes(game),
133
+        demos=demos,
108134
         start_fen=game.board().fen(),
109135
         positions=positions,
110136
         reached=reached,

modified schach/training.py +100 −4

@@ -78,6 +78,7 @@ class OpeningMixin:
7878
         self._name_cache = {}
7979
         self.coach_log = []  # Rückmeldungen: {"ply": Halbzug der zugehörigen Stellung, "markup": Text}
8080
         self.coach_index = None  # angezeigte Rückmeldung; None = die neueste
81
+        self.demo = None  # laufende „Warum?“-Vorführung: {"demo": Demo, "label": "h3", "index": Schritt}
8182
 
8283
     # --- Oberfläche --------------------------------------------------------
8384
 
@@ -95,6 +96,9 @@ class OpeningMixin:
9596
             label="Gegen Maia weiterspielen", valign=Gtk.Align.CENTER, visible=False, margin_end=10,
9697
         )
9798
         self.coach_button.set_action_name("win.opening-continue")
99
+        self.coach_why = Gtk.Button(valign=Gtk.Align.CENTER, visible=False, margin_end=10,
100
+                                    tooltip_text="Zeigt auf dem Brett, was hinter dem Zug steckt")
101
+        self.coach_why.connect("clicked", lambda *_: self._demo_start())
98102
         # Blättern durch die letzten Rückmeldungen; das Brett zeigt die Stellung dazu
99103
         self.coach_nav = Gtk.Box(spacing=2, valign=Gtk.Align.CENTER, margin_end=6)
100104
         self.coach_prev = Gtk.Button(icon_name="go-previous-symbolic", tooltip_text="Vorherige Rückmeldung",
@@ -112,17 +116,19 @@ class OpeningMixin:
112116
         card.append(Gtk.Image(icon_name="dialog-information-symbolic", margin_start=14, valign=Gtk.Align.CENTER))
113117
         card.append(self.coach_label)
114118
         card.append(self.coach_nav)
119
+        card.append(self.coach_why)
115120
         card.append(self.coach_button)
116121
         self.coach = Gtk.Revealer(child=card, transition_type=Gtk.RevealerTransitionType.SLIDE_UP)
117122
         return self.coach
118123
 
119
-    def _coach(self, markup, ply=None, replace=False, shapes=()):
124
+    def _coach(self, markup, ply=None, replace=False, shapes=(), demo=None):
120125
         """Neue Rückmeldung zur Stellung nach Halbzug ``ply`` (Standard: aktuelle Stellung).
121126
 
122127
         ``shapes``: Pfeile und Felder aus dem Kurskommentar, solange diese Rückmeldung zu sehen ist.
123128
         """
124129
         entry = {"ply": len(self.board.move_stack) - 1 if ply is None else ply, "markup": markup,
125
-                 "shapes": tuple(shapes)}
130
+                 "shapes": tuple(shapes), "demo": demo}
131
+        self.demo = None
126132
         if replace and self.coach_log:
127133
             self.coach_log[-1] = entry
128134
         else:
@@ -132,6 +138,10 @@ class OpeningMixin:
132138
         self._coach_show()
133139
 
134140
     def _coach_show(self):
141
+        if self.demo is not None:
142
+            self._demo_show()
143
+            return
144
+        self.coach_why.set_visible(False)
135145
         if not self.coach_log:
136146
             self.coach.set_reveal_child(False)
137147
             self.view.shapes = ()
@@ -146,9 +156,17 @@ class OpeningMixin:
146156
         self.coach_next.set_sensitive(index < last)
147157
         self.coach_last.set_sensitive(index < last)
148158
         self.coach_button.set_visible(self.final_text is not None and index == last)
159
+        self.coach_last.set_tooltip_text("Zum aktuellen Zug")
160
+        why = self.coach_log[index].get("demo")
161
+        if why is not None:
162
+            self.coach_why.set_label(f"Warum {why['label']}?")
163
+        self.coach_why.set_visible(why is not None)
149164
         self.coach.set_reveal_child(True)
150165
 
151166
     def _coach_step(self, delta):
167
+        if self.demo is not None:
168
+            self._demo_step(delta)
169
+            return
152170
         last = len(self.coach_log) - 1
153171
         index = (last if self.coach_index is None else self.coach_index) + delta
154172
         index = max(0, min(last, index))
@@ -161,11 +179,84 @@ class OpeningMixin:
161179
         self._coach_show()
162180
 
163181
     def _coach_latest(self):
182
+        if self.demo is not None:
183
+            self._demo_end()
184
+            return
164185
         self.coach_index = None
165186
         self.browse_ply = None
166187
         self._refresh()
167188
         self._coach_show()
168189
 
190
+    # --- „Warum?“-Vorführung ----------------------------------------------
191
+
192
+    def _demo_entry(self, before, move):
193
+        demo = self.course.demo(before, move) if self.course else None
194
+        return {"demo": demo, "label": notation.move(before, move, self._notation())} if demo else None
195
+
196
+    def _demo_start(self):
197
+        last = len(self.coach_log) - 1
198
+        index = last if self.coach_index is None else self.coach_index
199
+        why = self.coach_log[index].get("demo") if self.coach_log else None
200
+        if why is None:
201
+            return
202
+        self.demo = dict(why, index=0)
203
+        demo = why["demo"]
204
+        self.view.animate_move(chess.Board(demo.start_fen), demo.steps[0][0])
205
+        self._refresh()
206
+        self._coach_show()
207
+
208
+    def _demo_step(self, delta):
209
+        demo = self.demo["demo"]
210
+        index = max(0, min(len(demo.steps) - 1, self.demo["index"] + delta))
211
+        if index == self.demo["index"]:
212
+            return
213
+        if index > self.demo["index"]:
214
+            self.view.animate_move(demo.board_at(index - 1), demo.steps[index][0])
215
+        self.demo["index"] = index
216
+        self._refresh()
217
+        self._coach_show()
218
+
219
+    def _demo_end(self):
220
+        if self.demo is None:
221
+            return False
222
+        self.demo = None
223
+        self._refresh()
224
+        self._coach_show()
225
+        return True
226
+
227
+    def _demo_refresh(self):
228
+        """Brett zeigt die Vorführung; ziehen kann man erst wieder danach."""
229
+        v = self.view
230
+        demo, index = self.demo["demo"], self.demo["index"]
231
+        board = demo.board_at(index)
232
+        v.board = board
233
+        v.last_move = board.peek()
234
+        v.interactive = False
235
+        v.selected = None
236
+        v.badge = None
237
+        v.hint_from = v.hint_to = v.threat_from = v.threat_to = None
238
+        v.shapes = demo.steps[index][2]
239
+        v.queue_draw()
240
+        self._refresh_chrome()
241
+
242
+    def _demo_show(self):
243
+        demo, index = self.demo["demo"], self.demo["index"]
244
+        move, comment, _shapes = demo.steps[index]
245
+        before = demo.board_at(index - 1)
246
+        label = _escape(notation.label(before, move, self._notation()))
247
+        text = _escape(notation.text(comment, self._notation()))
248
+        self.coach_label.set_markup(
249
+            f"<span alpha='70%'>Warum {_escape(self.demo['label'])}? · {index + 1}/{len(demo.steps)}</span>\n"
250
+            f"<b>{label}</b>" + (f" – {text}" if text else ""))
251
+        self.coach_nav.set_visible(True)
252
+        self.coach_prev.set_sensitive(index > 0)
253
+        self.coach_next.set_sensitive(index < len(demo.steps) - 1)
254
+        self.coach_last.set_sensitive(True)
255
+        self.coach_last.set_tooltip_text("Zurück zur Partie")
256
+        self.coach_why.set_visible(False)
257
+        self.coach_button.set_visible(False)
258
+        self.coach.set_reveal_child(True)
259
+
169260
     def _opening_title(self):
170261
         return self.course.title if self.course else "Eröffnung"
171262
 
@@ -268,6 +359,7 @@ class OpeningMixin:
268359
         self._opening_next_step()
269360
 
270361
     def _opening_leave(self):
362
+        self.demo = None
271363
         self.course = None
272364
         self.opening_busy = False
273365
         self.coach_log = []
@@ -334,12 +426,15 @@ class OpeningMixin:
334426
         if gen != self.gen or self.mode != "opening" or option.move not in self.board.legal_moves:
335427
             return False
336428
         label = notation.label(self.board, option.move, self._notation())
429
+        # „Warum?“ zum eigenen Zug davor bleibt erreichbar, auch wenn der Gegner schon geantwortet hat
430
+        why = self._demo_entry(self.board, option.move) or (
431
+            self.coach_log[-1].get("demo") if self.coach_log else None)
337432
         self.view.animate_move(self.board, option.move)
338433
         self.board.push(option.move)
339434
         self.opening_busy = False
340435
         self._changed()
341436
         comment = f" – {_escape(notation.text(option.comment, self._notation()))}" if option.comment else ""
342
-        self._coach(f"<b>{_escape(label)}</b>{comment}", shapes=option.shapes)
437
+        self._coach(f"<b>{_escape(label)}</b>{comment}", shapes=option.shapes, demo=why)
343438
         self._refresh()
344439
         if not self.course.options(self.board):
345440
             self._opening_finished()
@@ -361,7 +456,8 @@ class OpeningMixin:
361456
             else:
362457
                 comment = "Zugumstellung – auch so kommst du zu unserem Ziel."
363458
             self._coach(f"✓ <b>{label}</b> – {_escape(notation.text(comment, self._notation()))}",
364
-                        shapes=verdict.option.shapes if verdict.option else ())
459
+                        shapes=verdict.option.shapes if verdict.option else (),
460
+                        demo=self._demo_entry(before, move))
365461
             self._refresh()
366462
             self._opening_next_step()
367463
             return

modified tests/test_opening.py +13 −0

@@ -43,6 +43,19 @@ class CourseTest(unittest.TestCase):
4343
         self.assertEqual(course.welcome, "Start")
4444
         self.assertEqual(course.welcome_shapes, ((chess.E4, chess.E4, "red"),))
4545
 
46
+    def test_warum_variation_is_demo_not_option(self):
47
+        course = opening.parse_course(
48
+            '[Event "T"]\n\n1. e4 e5 2. Nf3 { Angriff auf e5. } '
49
+            '( 2. Qh5 { [%warum] Stell dir vor … } 2... Nc6 { Gedeckt. [%cal Gc6e5] } ) 2... Nc6 *')
50
+        before = play("e4", "e5")
51
+        self.assertEqual([o.move.uci() for o in course.options(before)], ["g1f3"])
52
+        demo = course.demo(before, chess.Move.from_uci("g1f3"))
53
+        self.assertEqual([m.uci() for m, _c, _s in demo.steps], ["d1h5", "b8c6"])
54
+        self.assertEqual(demo.steps[0][1], "Stell dir vor …")
55
+        self.assertEqual(demo.steps[1][2], ((chess.C6, chess.E5, "green"),))
56
+        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")))
58
+
4659
     def test_options_main_first(self):
4760
         italian = self.courses["Italienisch"]
4861
         options = italian.options(play("e4", "e5", "Nf3", "Nc6", "Bc4"))