Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(analyse): 'Warum nicht?' and hint stage 3 as variations in the game tree

public

feat(analyse): 'Warum nicht?' and hint stage 3 as variations in the game tree

Against Maia and when viewing a game, 'Warum nicht?' merges the best move as
a variation 'Bester Zug' before the weak move (its first comment says what it
would have gained) and the refutation as 'Warum nicht?' after it, then shows
the fork with both labelled arrows. Hint stage 3 merges its explanation as
'Hinweis' at the present; playing the hint turns it into the played move.
explain.merge reuses moves already in the tree. The analysis board now pauses
a game against Maia (invariant 11). Without a game tree it stays a demo.

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

modified docs/adr/0001-fensterzustand-als-regionen.md +4 −5

@@ -36,7 +36,7 @@ Nicht alle Regionen sind unabhängig:
3636
   dritte Stufe der Region Hinweis.
3737
 - **Pause gibt es nur gegen Maia.** Sie beginnt beim Eintritt in eine Vorführung oder
3838
   eine Rechnung (Hinweis, „Warum?“, „Warum nicht?“) und endet, sobald nichts sie mehr
39
-  hält. Das Analysebrett zur Partie hält sie nicht auf.
39
+  hält. Auch das Analysebrett hält sie fest.
4040
 - **Die Uhr ist kein eigener Zustand, sondern folgt aus den anderen:** Sie läuft genau
4141
   dann, wenn die Aktivität eine eigene Uhr hat (Maia, zu zweit), die Partie läuft und
4242
   keine Pause ist. Heute schalten `_pause` und `_pause_end` sie von Hand; künftig
@@ -60,7 +60,7 @@ Gelten nach jedem äußersten `_refresh` (siehe `zustand.violations`):
6060
 8. Pause ⇒ Aktivität Maia.
6161
 9. Alte Stellung ⇒ weder Analysebrett noch Vorführung.
6262
 10. Eigene Uhr läuft ⇒ keine Pause, Partie nicht beendet, Aktivität Maia oder zu zweit.
63
-11. Gegen Maia, Partie läuft, Vorführung offen ⇒ Pause.
63
+11. Gegen Maia, Partie läuft, Analysebrett oder Vorführung offen ⇒ Pause.
6464
 
6565
 Ein Verstoß wird geloggt (Logger `schach.zustand`, einmal je Meldung). Mit
6666
 `SCHACH_STRENG=1` bricht er ab, für Rauchtests. Der Zufallstest
@@ -76,6 +76,5 @@ mit den echten Mixins, ohne Zufall und o
7676
   Wiedergabe beendet. Das ist der nächste Schritt.
7777
 - Neue Wege in einen Zustand (Taste, Klick, Menü) brauchen dann keine eigene
7878
   Aufräumlogik mehr.
79
-- Entschieden (24.11.2026), noch nicht umgesetzt: Auch das Analysebrett pausiert eine
80
-  Partie gegen Maia. Heute zieht Maia weiter, während man dort schaut. Mit dem Umbau wird
81
-  Invariante 11 zu „Analysebrett oder Vorführung offen ⇒ Pause“.
79
+- Seit 24.11.2026 pausiert auch das Analysebrett eine Partie gegen Maia (vorher zog Maia
80
+  weiter, während man dort schaute); Invariante 11 gilt seitdem für beide.

modified roadmap/analysebrett.md +7 −2

@@ -185,7 +185,7 @@ Was übrig bleibt, bestimmt die Pfeile an den Gabelungen und die Tiefe.
185185
    und die dritte Hinweisstufe bleiben eigene Bäume und werden nicht
186186
    gespeichert.
187187
 
188
-5. **Erklärungen als Nebenvarianten** (geplant, entschieden 24.11.2026):
188
+5. **Erklärungen als Nebenvarianten** (umgesetzt 24.11.2026 gegen Maia und beim Ansehen):
189189
    „Warum nicht?“ und die dritte Hinweisstufe öffnen keine eigene Vorführung mehr,
190190
    sondern hängen sich als Nebenvariante in den Partiebaum. Was man sich erklären lässt,
191191
    bleibt so erhalten: in der Zugliste, im Spielstand, im PGN und in Nachbesprechungen.
@@ -199,7 +199,12 @@ Was übrig bleibt, bestimmt die Pfeile an den Gabelungen und die Tiefe.
199199
    - Die dritte Hinweisstufe hängt die Erklärung an die Gegenwart. Spielt man den
200200
      Hinweiszug, wird ihr erster Zug zum gespielten Zug, der Rest bleibt Nebenvariante.
201201
    - Das Analysebrett pausiert eine Partie gegen Maia, wie heute schon die Vorführung.
202
-   - Nebenvarianten lassen sich in der Zugliste einklappen (neu) und löschen (gibt es).
202
+   - In der Zugliste stehen sie als benannte Zweige („Bester Zug“, „Warum nicht?“,
203
+     „Hinweis“), zugeklappt, solange das Brett nicht in ihnen steht; löschen mit Entf.
204
+   - Varianten an der Gegenwart (etwa der Hinweis, bevor man zieht) stehen im PGN im Header
205
+     `SchachDanach`, sonst würden sie zur Hauptlinie.
206
+   - Ganz am Anfang (noch kein Zug) und überall ohne Partiebaum bleibt es vorerst bei der
207
+     Vorführung.
203208
    - Rätsel, Kurse und zu zweit bekommen dafür eine Zugliste mit Nebenvarianten, siehe
204209
      Stufe 6. Online gibt es weder Hinweise noch Erklärungen.
205210
 6. **Aufdecken statt Verbergen** (geplant, entschieden 24.11.2026, siehe

modified schach/app.py +33 −9

@@ -1271,6 +1271,14 @@ class Window(OnlineMixin, PuzzleMixin, O
12711271
             self._wait_toast("Moment, ich suche einen guten Zug …")
12721272
             self._refresh()
12731273
 
1274
+    def _explanation_show(self, why):
1275
+        """Dritte Hinweisstufe zeigen: mit Partiebaum als Nebenvariante „Hinweis“ an der Gegenwart
1276
+        (training._hint_variation), sonst (Rätsel, zu zweit, ganz am Anfang) als Vorführung."""
1277
+        if self._analysis_allowed():
1278
+            self._hint_variation(why["tree"])
1279
+        else:
1280
+            self._demo_begin(why)
1281
+
12741282
     def _can_explain(self):
12751283
         """Dritte Stufe: Erklärung zum gezeigten Zug (Kurse haben ihre eigenen „Warum?“-Fragen)."""
12761284
         return (self.mode in ("maia", "duo", "puzzle") and self.hint_level >= 2 and self.hint_move is not None
@@ -1285,7 +1293,7 @@ class Window(OnlineMixin, PuzzleMixin, O
12851293
         if not self._can_explain() or not self._human_to_move():
12861294
             return
12871295
         if self.explanation is not None and self.explanation[0] == self.gen:
1288
-            self._demo_begin(self.explanation[1])
1296
+            self._explanation_show(self.explanation[1])
12891297
             return
12901298
         gen, board, move = self.gen, self.board.copy(), self.hint_move
12911299
         self.explain_pending = True
@@ -1306,7 +1314,7 @@ class Window(OnlineMixin, PuzzleMixin, O
13061314
             why = {"tree": tree, "label": f"Warum {notation.move(board, move, self._notation())}?"}
13071315
             self.explanation = (gen, why)
13081316
             if self._human_to_move() and not self._browsing():
1309
-                self._demo_begin(why)
1317
+                self._explanation_show(why)
13101318
             else:
13111319
                 self._pause_check()
13121320
                 self._refresh_chrome()
@@ -1385,10 +1393,20 @@ class Window(OnlineMixin, PuzzleMixin, O
13851393
                 self._refresh()  # ohne Vorführung geht die Partie gleich weiter
13861394
                 return
13871395
             entry["tree"] = tree
1388
-            self._demo_begin(entry)
1396
+            if not entry.get("variation"):
1397
+                self._demo_begin(entry)
1398
+                return
1399
+            ply = len(before.move_stack)
1400
+            stack = self.board.move_stack
1401
+            if self._analysis_allowed() and len(stack) > ply and stack[ply] == move \
1402
+                    and self._board_at(ply - 1).fen() == before.fen():
1403
+                self._why_not_variation(ply, tree)
1404
+            else:
1405
+                self._refresh()  # inzwischen zurückgenommen: der Zug steht nicht mehr in der Partie
13891406
 
13901407
         self.toasts.add_toast(Adw.Toast(title="Moment, ich schaue mir den Zug an …", timeout=2))
1391
-        self.get_application().side_engine().submit(why_not_job(before, move, maia, name), on_done)
1408
+        job = why_not_job(before, move, maia, name, variation=bool(entry.get("variation")))
1409
+        self.get_application().side_engine().submit(job, on_done)
13921410
 
13931411
     def play_hint(self, *_):
13941412
         """Enter: den Hinweiszug spielen, sobald Figur und Zielfeld gezeigt werden."""
@@ -2011,8 +2029,8 @@ class Window(OnlineMixin, PuzzleMixin, O
20112029
         """Hält gerade etwas die Pause fest?"""
20122030
         if self.paused.get("starting"):
20132031
             return True  # „Warum nicht?“ richtet sich gerade ein
2014
-        if self.demo is not None and not self.demo.get("game"):
2015
-            return True  # Erklärung offen (das Analysebrett zur Partie hält nicht auf)
2032
+        if self.demo is not None:
2033
+            return True  # Analysebrett oder Erklärung offen (entschieden 24.11.2026, ADR 0001)
20162034
         if self.hint_pending or self.explain_pending:
20172035
             return True
20182036
         return any(e.get("busy") for e in self.why_not_entries.values())
@@ -2051,11 +2069,17 @@ class Window(OnlineMixin, PuzzleMixin, O
20512069
         if self.paused is not None:
20522070
             self.paused["starting"] = True
20532071
         before, move = self._board_at(ply - 1), self.board.move_stack[ply]
2054
-        key = (before.fen(), move)
2072
+        variation = self._analysis_allowed()  # Partiebaum vorhanden: als Nebenvariante, sonst Vorführung
2073
+        key = (before.fen(), move, variation)
20552074
         if key not in self.why_not_entries:  # einmal berechnet, samt selbst gezogener Züge gemerkt
2056
-            self.why_not_entries[key] = {"label": "Warum nicht?", "why_not": (before, move), "keep": True}
2075
+            self.why_not_entries[key] = {"label": "Warum nicht?", "why_not": (before, move), "keep": True,
2076
+                                         "variation": variation}
20572077
         entry = self.why_not_entries[key]
2058
-        if "tree" in entry:
2078
+        if variation and self._why_not_known(ply):
2079
+            self._why_not_jump(ply)  # steht schon im Partiebaum
2080
+        elif variation and "tree" in entry:
2081
+            self._why_not_variation(ply, entry["tree"])  # war gelöscht: ohne neue Rechnung wieder einhängen
2082
+        elif "tree" in entry:
20592083
             self._demo_begin(entry)
20602084
         else:
20612085
             self._why_not(entry)

modified schach/explain.py +51 −14

@@ -696,9 +696,12 @@ def _explain(engine, board, move, maia,
696696
     return comment(prune(tree), threat, only_move, better, why, rival)
697697
 
698698
 
699
-def why_not_job(board, move, maia=None, name="Maia", limit=EXPLAIN_LIMIT):
699
+def why_not_job(board, move, maia=None, name="Maia", limit=EXPLAIN_LIMIT, variation=False):
700700
     """Job für „Warum nicht?“: Baum vor dem schwachen Zug ``move``. Hauptlinie ist ``move`` mit
701
-    seiner Widerlegung, daneben Stockfishs bester Zug. Gibt None zurück, wenn ``move`` der beste ist."""
701
+    seiner Widerlegung, daneben Stockfishs bester Zug. Gibt None zurück, wenn ``move`` der beste ist.
702
+
703
+    ``variation``: für den Partiebaum (siehe merge) statt für eine Vorführung. Dann steht „Besser
704
+    als …“ am ersten Zug des besten Zweigs, ohne Wegweiser zum Pfeil in der Ausgangsstellung."""
702705
     board = board.copy()
703706
 
704707
     def job(engine):
@@ -710,11 +713,15 @@ def why_not_job(board, move, maia=None,
710713
         info_played = engine.analyse(board, limit, root_moves=[move])
711714
         played = win_pct(info_played["score"], board.turn)
712715
         kept = _kept(board, info.get("pv") or [best], info_played.get("pv") or [move])
713
-        why = _gained(other, played, kept)
716
+        why = _gained(other, played, kept, where=not variation)
714717
         tree = _explain(engine, board, move, maia, name, limit, better=best, why=why)
715718
         graft(tree, tree.game, other)
716719
         tree.info(tree.first())["label"] = "Gespielt"
717
-        tree.info(tree.game.variations[1])["label"] = "Bester Zug"
720
+        top = tree.game.variations[1]
721
+        tree.info(top)["label"] = "Bester Zug"
722
+        if variation:
723
+            own = top.comment.strip()
724
+            top.comment = f"Besser als {_san(board, move)}. {why}" + (f" {own}" if own else "")
718725
         return tree
719726
 
720727
     return job
@@ -744,26 +751,33 @@ def _kept(board, best_pv, played_pv):
744751
     return gain_text(diff)
745752
 
746753
 
747
-def _gained(best, played, kept=None):
748
-    """Was der bessere Zug gebracht hätte, als Satz, mit dem Weg dorthin. ``played``: Gewinnchance
749
-    nach dem gespielten Zug, ``kept``: was der gespielte Zug unnötig hergibt (siehe _kept)."""
754
+def _gained(best, played, kept=None, where=True):
755
+    """Was der bessere Zug gebracht hätte, als Satz, mit dem Weg dorthin (``where``: Wegweiser zum
756
+    Pfeil in der Ausgangsstellung der Vorführung). ``played``: Gewinnchance nach dem gespielten Zug,
757
+    ``kept``: was der gespielte Zug unnötig hergibt (siehe _kept)."""
758
+    text = _gained_text(best, played, kept)
759
+    if where and not text.endswith("sofort matt."):
760
+        text += " Den Weg zeigt der Pfeil „Bester Zug“ in der Ausgangsstellung (mit <)."
761
+    return text
762
+
763
+
764
+def _gained_text(best, played, kept):
750765
     mate, gain, chance = _outcome(best)
751
-    where = "Den Weg zeigt der Pfeil „Bester Zug“ in der Ausgangsstellung (mit <)."
752766
     first = best.first()
753767
     if first is not None and first.board().is_checkmate():
754768
         return "Damit setzt du sofort matt."
755769
     if mate:
756
-        return f"Damit setzt du matt. {where}"
770
+        return "Damit setzt du matt."
757771
     if kept is not None:
758
-        return f"Damit behältst du {kept}. Dein Zug gibt das ohne Not her. {where}"
772
+        return f"Damit behältst du {kept}. Dein Zug gibt das ohne Not her."
759773
     traded = trade(best.game.board(), best.game.end().board(), best.hero)
760774
     if gain > 0 and traded is not None and traded[0]:
761
-        return f"Damit bekommst du {pieces_text(traded[1])} für {pieces_text(traded[0])}. {where}"
775
+        return f"Damit bekommst du {pieces_text(traded[1])} für {pieces_text(traded[0])}."
762776
     if gain > 0 and traded is not None:
763
-        return f"Damit gewinnst du {pieces_text(traded[1])}. {where}"
777
+        return f"Damit gewinnst du {pieces_text(traded[1])}."
764778
     if gain > 0:
765
-        return f"Damit gewinnst du {gain_text(gain)}. {where}"
766
-    return f"Damit stehst du besser (Gewinnchance {round(chance)} statt {round(played)} %). {where}"
779
+        return f"Damit gewinnst du {gain_text(gain)}."
780
+    return f"Damit stehst du besser (Gewinnchance {round(chance)} statt {round(played)} %)."
767781
 
768782
 
769783
 def explore_job(board, move, hero, maia=None, name="Maia", limit=EXPLAIN_LIMIT):
@@ -836,3 +850,26 @@ def graft(tree, node, sub):
836850
     before = len(node.variations)
837851
     copy(node, sub.game)
838852
     return node.variations[before] if len(node.variations) > before else None
853
+
854
+
855
+def merge(tree, node, sub, children, name=""):
856
+    """Die Knoten ``children`` aus ``sub`` samt allem darunter unter ``node`` in ``tree`` mischen
857
+    (``node`` entspricht ihrem Elternknoten in ``sub``). Anders als graft: Züge, die es in ``tree``
858
+    schon gibt (etwa die gespielte Partie oder eine frühere Erklärung), werden weiterbenutzt und
859
+    behalten Kommentar und Zusatzangaben; nur Neues kommt dazu. ``name`` steht vor jedem neuen
860
+    Zweig, der an einem schon vorhandenen Knoten abzweigt (PGN „( { Name } 3. Sf3 … )“, Kopfzeile in
861
+    der Zugliste). Gibt {Knoten in sub: Knoten in tree} zurück."""
862
+    found = {}
863
+
864
+    def walk(target, sources, existing):
865
+        for child in sources:
866
+            new = next((c for c in target.variations if c.move == child.move), None)
867
+            fresh = new is None
868
+            if fresh:
869
+                new = target.add_variation(child.move, comment=child.comment,
870
+                                           starting_comment=name if existing else "")
871
+                tree.meta[new] = dict(sub.meta.get(child, {}))
872
+            found[child] = new
873
+            walk(new, child.variations, not fresh)
874
+    walk(node, children, True)
875
+    return found

modified schach/training.py +42 −1

@@ -636,6 +636,7 @@ class OpeningMixin:
636636
         label = "Nachspielen"
637637
         self.demo = {"label": label, "tree": self.game_tree, "node": node, "chosen": chosen,
638638
                      "busy": False, "keep": True, "game": True}
639
+        self._pause()  # gegen Maia: Uhr steht, Maia wartet, bis das Analysebrett zu ist
639640
         if show:
640641
             self._playback_hold()  # Klick in die Zugliste, ← usw. während der Wiedergabe
641642
             self._refresh()
@@ -835,10 +836,46 @@ class OpeningMixin:
835836
             self.demo["chosen"][step.parent] = step
836837
             step = step.parent
837838
         self.demo["node"] = node
838
-        self.view.animate_move(node.parent.board(), node.move)
839
+        if node.parent is not None:
840
+            self.view.animate_move(node.parent.board(), node.move)
839841
         self._refresh()
840842
         self._coach_show()
841843
 
844
+    WHY_NOT_BEST = "Bester Zug"  # Name der Nebenvariante (PGN-Kommentar vor ihrem ersten Zug)
845
+    WHY_NOT_REFUTATION = "Warum nicht?"
846
+
847
+    def _why_not_known(self, ply):
848
+        """Steht „Warum nicht?“ zu Halbzug ``ply`` schon im Partiebaum (Zweig „Bester Zug“ davor)?"""
849
+        fork = self._game_node(ply - 1)
850
+        return any(c.starting_comment == self.WHY_NOT_BEST for c in fork.variations)
851
+
852
+    def _why_not_jump(self, ply):
853
+        """Analysebrett auf die Gabelung vor Halbzug ``ply``: Pfeile „Partie“ und „Bester Zug“."""
854
+        self._analysis_open_node(self._game_node(ply - 1))
855
+
856
+    HINT_NAME = "Hinweis"
857
+
858
+    def _hint_variation(self, tree):
859
+        """Dritte Hinweisstufe im Partiebaum: die Erklärung (explain.explain_job, Wurzel = Gegenwart)
860
+        als Nebenvariante „Hinweis“ an die Gegenwart, das Brett auf den Hinweiszug. Spielt man ihn
861
+        danach, wird er zum gespielten Zug (_game_tree), der Rest bleibt Nebenvariante."""
862
+        present = self._game_node(len(self.board.move_stack) - 1)
863
+        found = explain.merge(self.game_tree, present, tree, tree.game.variations, self.HINT_NAME)
864
+        first = found[tree.first()]
865
+        self.game_tree.info(first).setdefault("label", self.HINT_NAME)  # Schild am Pfeil
866
+        self._schedule_autosave()
867
+        self._analysis_open_node(first)
868
+
869
+    def _why_not_variation(self, ply, tree):
870
+        """„Warum nicht?“ (explain.why_not_job mit variation=True) in den Partiebaum: der beste Zug als
871
+        Nebenvariante vor dem Zug ``ply``, die Widerlegung des gespielten Zugs als Nebenvariante
872
+        dahinter (wo der Gegner sie nicht ohnehin gespielt hat); dann auf die Gabelung."""
873
+        fork, played = self._game_node(ply - 1), self._game_node(ply)
874
+        explain.merge(self.game_tree, fork, tree, tree.game.variations[1:], self.WHY_NOT_BEST)
875
+        explain.merge(self.game_tree, played, tree, tree.first().variations, self.WHY_NOT_REFUTATION)
876
+        self._schedule_autosave()
877
+        self._why_not_jump(ply)
878
+
842879
     PLAYED_WORDS = {"!!": "Ein brillanter Zug.", "!": "Ein starker Zug.", "?!": "Ungenau.", "?": "Ein Fehler.",
843880
                     "??": "Ein grober Fehler."}
844881
 
@@ -930,6 +967,10 @@ class OpeningMixin:
930967
             comment = self._played_text(node) if self._demo_real(node) else node.comment
931968
             text = _escape(notation.text(comment, style))
932969
             markup = head + f"<b>{label}</b>" + (f" – {text}" if text else "")
970
+        best = next((c for c in node.variations if c.starting_comment == self.WHY_NOT_BEST), None) \
971
+            if self.demo.get("game") and not busy else None
972
+        if best is not None and best.comment:  # „Warum nicht?“: die Begründung schon an der Gabelung
973
+            markup += "\n" + _escape(notation.text(best.comment, style))
933974
         if len(node.variations) > 1 and not busy:
934975
             board = node.board()
935976
             ahead = self._demo_next(node)

modified schach/zustand.py +2 −3

@@ -69,9 +69,8 @@ def violations(win):
6969
             found.append("Uhr läuft nach dem Ende der Partie")
7070
         if mode not in ("maia", "duo"):
7171
             found.append(f"eigene Uhr läuft in Aktivität {mode!r}")
72
-    if mode == "maia" and not over and demo is not None and not demo.get("game") \
73
-            and getattr(win, "paused", None) is None:
74
-        found.append("Vorführung gegen Maia ohne Pause")
72
+    if mode == "maia" and not over and demo is not None and getattr(win, "paused", None) is None:
73
+        found.append("Analysebrett oder Vorführung gegen Maia ohne Pause")
7574
     return found
7675
 
7776
 

modified tests/test_explain.py +46 −0

@@ -198,6 +198,40 @@ class OwnMoveTest(unittest.TestCase):
198198
         self.assertEqual(tree.label(child), "Maia 600 · oft")
199199
         self.assertEqual(child.comment, sub.first().comment)
200200
 
201
+    def test_merge_reuses_existing_moves_and_names_new_branches(self):
202
+        # Partie: 1. Sxd5 Kd7, dazu eine Erklärung mit 1. Sxd5 Kd7 2. Sf4 und 1. Sxd5 Ke7
203
+        game = explain.line(chess.Board(QUEEN_UP), [m("c3d5"), m("e8d7")])
204
+        played = game.first()
205
+        game.info(played)["label"] = "Partie"
206
+        played.comment = "gespielt"
207
+        sub = explain.line(chess.Board(QUEEN_UP), [m("c3d5"), m("e8d7"), m("d5f4")])
208
+        sub.first().add_variation(m("e8e7"), comment="auch möglich")
209
+        sub.first().comment = "aus der Erklärung"
210
+        sub.info(sub.first().variations[1])["label"] = "Bester Zug"
211
+        found = explain.merge(game, game.game, sub, sub.game.variations, "Warum nicht?")
212
+        self.assertIs(found[sub.first()], played)  # vorhandener Zug: weiterbenutzt
213
+        self.assertEqual(played.comment, "gespielt")  # … mit seinem Kommentar
214
+        self.assertEqual(game.label(played), "Partie")
215
+        reply = played.variations[0]
216
+        self.assertEqual([c.move for c in reply.variations], [m("d5f4")])
217
+        self.assertEqual(reply.variations[0].starting_comment, "Warum nicht?")  # zweigt an Vorhandenem ab
218
+        side = played.variations[1]
219
+        self.assertEqual((side.move, side.comment, side.starting_comment), (m("e8e7"), "auch möglich", "Warum nicht?"))
220
+        self.assertEqual(game.label(side), "Bester Zug")
221
+        # noch einmal gemischt: nichts doppelt
222
+        explain.merge(game, game.game, sub, sub.game.variations, "Warum nicht?")
223
+        self.assertEqual(len(played.variations), 2)
224
+        self.assertEqual(len(reply.variations), 1)
225
+
226
+    def test_merge_names_only_where_the_branch_leaves_the_tree(self):
227
+        game = explain.line(chess.Board(QUEEN_UP), [m("c3d5")])
228
+        sub = explain.line(chess.Board(QUEEN_UP), [m("e1e2"), m("e8d7"), m("c3d5")])
229
+        found = explain.merge(game, game.game, sub, sub.game.variations, "Hinweis")
230
+        first = found[sub.first()]
231
+        self.assertEqual(first.starting_comment, "Hinweis")
232
+        self.assertEqual(first.variations[0].starting_comment, "")
233
+        self.assertEqual(first.variations[0].variations[0].starting_comment, "")
234
+
201235
 
202236
 @unittest.skipUnless(shutil.which("stockfish"), "stockfish nicht installiert")
203237
 class ExplainJobTest(unittest.TestCase):
@@ -222,6 +256,18 @@ class ExplainJobTest(unittest.TestCase):
222256
         self.assertEqual(tree.label(tree.first()), "Gespielt")
223257
         self.assertIn("Besser war Sxd5: Damit gewinnst du die Dame.", tree.first().comment)
224258
 
259
+    def test_why_not_for_the_game_tree_puts_the_reason_on_the_best_move(self):
260
+        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
261
+        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
262
+        try:
263
+            tree = explain.why_not_job(board, m("e1e2"), limit=chess.engine.Limit(depth=10),
264
+                                       variation=True)(engine)
265
+        finally:
266
+            engine.quit()
267
+        best = tree.game.variations[1]
268
+        self.assertTrue(best.comment.startswith("Besser als Ke2. Damit gewinnst du die Dame."), best.comment)
269
+        self.assertNotIn("Ausgangsstellung", best.comment)  # kein Wegweiser zur Vorführung
270
+
225271
     def test_hint_that_is_not_stockfishs_best_says_so(self):
226272
         board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
227273
         engine = chess.engine.SimpleEngine.popen_uci("stockfish")

added tests/test_warum_variante.py +126 −0

@@ -0,0 +1,126 @@
1
+"""„Warum nicht?“ und die dritte Hinweisstufe als Nebenvarianten im Partiebaum (Analysebrett,
2
+Stufe 5): mit den echten Mixins, ohne Engine (die Erklärungsbäume sind von Hand gebaut)."""
3
+
4
+import unittest
5
+
6
+import chess
7
+import chess.pgn
8
+
9
+from schach import explain, savegames, zustand
10
+from tests.test_zustand_regression import FakeWindow, played
11
+
12
+
13
+def m(uci):
14
+    return chess.Move.from_uci(uci)
15
+
16
+
17
+def why_not(board, ply, best, refutation=()):
18
+    """Baum wie explain.why_not_job(variation=True): gespielter Zug mit Widerlegung, bester Zug daneben."""
19
+    before = board.root()
20
+    for move in board.move_stack[:ply]:
21
+        before.push(move)
22
+    tree = explain.line(before, [board.move_stack[ply], *refutation])
23
+    tree.info(tree.first())["label"] = "Gespielt"
24
+    top = tree.game.add_variation(best, comment="Besser als … Damit gewinnst du.")
25
+    tree.info(top)["label"] = "Bester Zug"
26
+    return tree
27
+
28
+
29
+class Window(FakeWindow):
30
+    def __init__(self, *sans):
31
+        super().__init__(played(*sans), mode="maia")
32
+        self.saved = 0
33
+
34
+    def _schedule_autosave(self):
35
+        self.saved += 1
36
+
37
+
38
+class WhyNotTest(unittest.TestCase):
39
+    def setUp(self):
40
+        self.win = Window("e4", "e5", "Ke2", "d6")
41
+        self.tree = why_not(self.win.board, 2, m("g1f3"), refutation=[m("d8g5")])
42
+
43
+    def test_best_move_hangs_before_the_played_move(self):
44
+        win = self.win
45
+        win._why_not_variation(2, self.tree)
46
+        fork = win._game_node(1)
47
+        self.assertEqual([(c.move, c.starting_comment) for c in fork.variations],
48
+                         [(m("e1e2"), ""), (m("g1f3"), "Bester Zug")])
49
+        self.assertEqual(win.game_tree.label(fork.variations[1]), "Bester Zug")
50
+        self.assertTrue(win._why_not_known(2))
51
+
52
+    def test_board_jumps_to_the_fork(self):
53
+        win = self.win
54
+        win._why_not_variation(2, self.tree)
55
+        self.assertTrue(win.demo["game"])
56
+        self.assertIs(win.demo["node"], win._game_node(1))
57
+        self.assertIsNotNone(win.paused)  # das Analysebrett hält Maia an
58
+        self.assertEqual(zustand.violations(win), [])
59
+
60
+    def test_refutation_hangs_after_the_played_move(self):
61
+        win = self.win
62
+        win._why_not_variation(2, self.tree)
63
+        after = win._game_node(2)
64
+        self.assertEqual([(c.move, c.starting_comment) for c in after.variations],
65
+                         [(m("d7d6"), ""), (m("d8g5"), "Warum nicht?")])
66
+
67
+    def test_twice_adds_nothing(self):
68
+        win = self.win
69
+        win._why_not_variation(2, self.tree)
70
+        win._why_not_variation(2, self.tree)
71
+        self.assertEqual(len(win._game_node(1).variations), 2)
72
+        self.assertEqual(len(win._game_node(2).variations), 2)
73
+
74
+    def test_saved_with_the_game(self):
75
+        win = self.win
76
+        win._why_not_variation(2, self.tree)
77
+        self.assertGreater(win.saved, 0)
78
+        state = savegames.GameState(board=win.board, human=win.human, elo=1500,
79
+                                    variations=win._game_variations())
80
+        loaded = savegames.from_pgn(savegames.to_pgn(state))
81
+        self.assertEqual([v[0] for v in loaded.variations[1]], [m("g1f3")])
82
+        self.assertEqual(loaded.variations[1][0][4], "Bester Zug")
83
+
84
+
85
+class HintTest(unittest.TestCase):
86
+    def setUp(self):
87
+        self.win = Window("e4", "e5", "Nf3", "Nc6")
88
+        board = self.win.board.copy()
89
+        self.tree = explain.line(board, [m("f1c4"), m("g8f6")])
90
+        self.tree.first().comment = "Du entwickelst eine Figur."
91
+
92
+    def test_hint_hangs_at_the_present_and_board_shows_it(self):
93
+        win = self.win
94
+        win._hint_variation(self.tree)
95
+        present = win._game_node(3)
96
+        hint = present.variations[0]
97
+        self.assertEqual((hint.move, hint.starting_comment), (m("f1c4"), "Hinweis"))
98
+        self.assertIs(win.demo["node"], hint)
99
+        self.assertEqual(zustand.violations(win), [])
100
+
101
+    def test_playing_the_hint_makes_it_the_played_move(self):
102
+        win = self.win
103
+        win._hint_variation(self.tree)
104
+        hint = win._game_node(3).variations[0]
105
+        win.demo = None
106
+        win.paused = None
107
+        win.board.push(m("f1c4"))
108
+        win._game_tree()
109
+        self.assertIs(win._game_node(4), hint)  # derselbe Knoten, jetzt gespielt
110
+        self.assertTrue(win.game_tree.meta[hint]["played"])
111
+        self.assertEqual([c.move for c in hint.variations], [m("g8f6")])  # Rest bleibt Nebenvariante
112
+
113
+    def test_another_move_keeps_the_hint_as_side_line(self):
114
+        win = self.win
115
+        win._hint_variation(self.tree)
116
+        win.demo = None
117
+        win.paused = None
118
+        win.board.push(m("f1b5"))
119
+        win._game_tree()
120
+        present = win._game_node(3)
121
+        self.assertEqual([c.move for c in present.variations], [m("f1b5"), m("f1c4")])
122
+        self.assertEqual(present.variations[1].starting_comment, "Hinweis")
123
+
124
+
125
+if __name__ == "__main__":
126
+    unittest.main()

modified tests/test_zustand.py +6 −4

@@ -46,7 +46,7 @@ class ViolationsTest(unittest.TestCase):
4646
         self.assertValid(window())
4747
 
4848
     def test_wiedergabe_braucht_analysebrett(self):
49
-        self.assertValid(window(demo=ANALYSIS, replaying=True, playback=playback()))
49
+        self.assertValid(window(demo=ANALYSIS, replaying=True, playback=playback(), paused={}))
5050
         self.assertViolates(window(playback=playback(False)), "Wiedergabe ohne Analysebrett")
5151
         # der gemeldete Fehler: eine Vorführung geht auf, der Ton der Wiedergabe läuft weiter
5252
         self.assertViolates(window(demo=SHOW, replaying=True, playback=playback(), paused={}),
@@ -55,7 +55,7 @@ class ViolationsTest(unittest.TestCase):
5555
         self.assertValid(window(demo=SHOW, replaying=True, playback=playback(False), paused={}))
5656
 
5757
     def test_aufnahme(self):
58
-        self.assertValid(window(demo=ANALYSIS, recorder=object()))
58
+        self.assertValid(window(demo=ANALYSIS, recorder=object(), paused={}))
5959
         self.assertViolates(window(recorder=object()), "Aufnahme ohne Analysebrett")
6060
         self.assertViolates(window(demo=ANALYSIS, recorder=object(), playback=playback()), "zugleich")
6161
 
@@ -79,7 +79,9 @@ class ViolationsTest(unittest.TestCase):
7979
     def test_pause(self):
8080
         self.assertValid(window(paused={}))
8181
         self.assertViolates(window(mode="duo", paused={}), "Pause in Aktivität")
82
-        self.assertViolates(window(demo=SHOW), "Vorführung gegen Maia ohne Pause")
82
+        self.assertViolates(window(demo=SHOW), "gegen Maia ohne Pause")
83
+        self.assertViolates(window(demo=ANALYSIS), "gegen Maia ohne Pause")  # seit 24.11.2026
84
+        self.assertValid(window(mode="review", demo=ANALYSIS))
8385
         self.assertValid(window(demo=SHOW, _over=lambda: True))  # nach dem Ende gibt es keine Pause
8486
         self.assertValid(window(mode="puzzle", demo=SHOW))
8587
 
@@ -95,7 +97,7 @@ class ViolationsTest(unittest.TestCase):
9597
         for san in ("e4", "e5", "Nf3"):
9698
             board.push_san(san)
9799
         self.assertValid(window(board=board, browse_ply=0))
98
-        self.assertValid(window(board=board, browse_ply=2, demo=ANALYSIS))  # = Gegenwart, nicht alt
100
+        self.assertValid(window(board=board, browse_ply=2, demo=ANALYSIS, paused={}))  # = Gegenwart, nicht alt
99101
         self.assertViolates(window(board=board, browse_ply=0, demo=ANALYSIS), "alte Stellung")
100102
 
101103
 

modified tests/test_zustand_regression.py +1 −0

@@ -55,6 +55,7 @@ class FakeWindow(OpeningMixin, ReviewMix
5555
         self.board = board
5656
         self.human = chess.WHITE
5757
         self.demo = None
58
+        self.game_tree = None
5859
         self.replaying = False
5960
         self.browse_ply = None
6061
         self.hint_level = 0