Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(explain): longer attacking lines, say what the better move wins, flag hints Stockfish dislikes

public

feat(explain): longer attacking lines, say what the better move wins, flag hints Stockfish dislikes

Lines keep going while checks are given. "Besser war" in "Warum nicht?" names
what the better move gains and where to find it. A hint that is not
Stockfish best says "Stockfish findet ... besser/ähnlich gut". New detector:
a piece dodging a pawn push ("Der Springer geht dem Angriff g4 aus dem Weg").

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

modified roadmap/analysebrett.md +6 −1

@@ -139,7 +139,12 @@ Was übrig bleibt, bestimmt die Pfeile an den Gabelungen und die Tiefe.
139139
    Coach-Leiste, wenn die Zeichen live aufs Brett dürfen, und immer als Knopf
140140
    in der Zugliste bei ?!, ? und ??. Ein Baum merkt sich selbst gezogene Züge,
141141
    bis die Partie weitergeht. Umwandlung auf dem Analysebrett ist immer eine
142
-   Dame.
142
+   Dame. „Besser war …“ sagt bei „Warum nicht?“ auch, was der bessere Zug
143
+   bringt (Matt, Material oder Gewinnchance), und wo man ihn findet. Ist ein
144
+   Hinweiszug (etwa von Maia) nicht Stockfishs bester, steht dort „Stockfish
145
+   findet … besser“ (oder „ähnlich gut“). Eine Linie läuft weiter, solange
146
+   Schach gegeben wird. Neuer Erkenner: „Der Springer geht dem Angriff g4 aus
147
+   dem Weg.“
143148
 3. **Zugliste und Einstiege:** Klick und Knopf „Aufs Analysebrett“, dazu Menü
144149
    und Taste. `review` und das Blättern in der Zugliste gehen im Analysebrett
145150
    auf.

modified schach/explain.py +78 −14

@@ -26,6 +26,7 @@ HARD_PLIES = 10 # … außer ein Tausch oder ein Schach ist noch nicht zu Ende
2626
 QUIET_PLIES = 4  # ohne Materialwechsel reicht ein kurzer Blick in die Zukunft
2727
 ONLY_MOVE_GAP = 15.0  # so viele Prozentpunkte Gewinnchance liegt der Zug vor dem zweitbesten
2828
 CHILD_LIMIT = chess.engine.Limit(depth=12)  # Prüfung der Kandidaten an den Gabelungen
29
+RIVAL_GAP = 3.0  # so knapp hinter Stockfishs bestem Zug heißt es „ähnlich gut“
2930
 BRANCH_GAP = 10.0  # eine Gabelung bleibt, wenn das Ergebnis um so viele Prozentpunkte abweicht
3031
 MAIA_MIN = 0.15  # Züge, die Maia seltener spielt, bekommen keinen eigenen Zweig
3132
 MAIA_MAX = 3
@@ -63,7 +64,7 @@ def gain_text(gain):
6364
 def trim(board, pv):
6465
     """Hauptvariante kürzen: bis Matt, bis ein Tausch abgeschlossen ist, höchstens MAX_PLIES.
6566
 
66
-    Nach jeder Antwort des Gegners: Wird als Nächstes geschlagen oder mattgesetzt, geht es weiter. Sonst ist
67
+    Nach jeder Antwort des Gegners: Wird als Nächstes geschlagen oder Schach gegeben, geht es weiter. Sonst ist
6768
     Schluss, sobald schon geschlagen wurde (Gewinn eingefahren oder Tausch fertig) oder nach
6869
     QUIET_PLIES Halbzügen ganz ohne Schlagen.
6970
     """
@@ -73,8 +74,8 @@ def trim(board, pv):
7374
     for i, move in enumerate(pv[:HARD_PLIES]):
7475
         if move not in probe.legal_moves:
7576
             break
76
-        if i >= MAX_PLIES and not (sharp or probe.is_capture(move)):
77
-            break  # über MAX_PLIES hinaus nur, um einen Tausch oder ein Schach abzuschließen
77
+        if i >= MAX_PLIES and not (sharp or probe.is_capture(move) or probe.gives_check(move)):
78
+            break  # über MAX_PLIES hinaus nur, um einen Tausch oder einen Angriff abzuschließen
7879
         captured = captured or probe.is_capture(move)
7980
         # Schach oder Gabel: die Antwort darauf gehört noch dazu
8081
         sharp = probe.gives_check(move) or bool(describe(probe, move, probe.turn)[1])
@@ -85,7 +86,7 @@ def trim(board, pv):
8586
         if i % 2 == 1 and len(pv) > i + 1:
8687
             following = pv[i + 1]
8788
             if sharp or following in probe.legal_moves and (probe.is_capture(following) or
88
-                                                            _mates(probe, following)):
89
+                                                            probe.gives_check(following)):
8990
                 continue
9091
             if captured or i + 1 >= QUIET_PLIES:
9192
                 break
@@ -128,6 +129,32 @@ def _hanging(board, square):
128129
     return min(VALUE[board.piece_type_at(a)] for a in attackers) < VALUE[piece.piece_type]
129130
 
130131
 
132
+def _pawn_attack(board, square):
133
+    """Bauernzug, mit dem der Gegner die Figur auf ``square`` angreifen könnte (der Bauer stünde dabei
134
+    nicht einfach umsonst), sonst None. Nur für Figuren, die mehr wert sind als ein Bauer."""
135
+    piece = board.piece_at(square)
136
+    if piece is None or piece.piece_type in (chess.PAWN, chess.KING):
137
+        return None
138
+    probe = board.copy(stack=False)
139
+    if probe.turn == piece.color:
140
+        if probe.is_check():
141
+            return None
142
+        probe.push(chess.Move.null())
143
+    if any(probe.piece_type_at(a) == chess.PAWN for a in probe.attackers(not piece.color, square)):
144
+        return None  # schon angegriffen: das ist „in Gefahr“, kein drohender Angriff
145
+    for push in probe.legal_moves:
146
+        if probe.piece_type_at(push.from_square) != chess.PAWN or probe.is_capture(push):
147
+            continue
148
+        if not chess.BB_PAWN_ATTACKS[not piece.color][push.to_square] & chess.BB_SQUARES[square]:
149
+            continue
150
+        after = probe.copy(stack=False)
151
+        after.push(push)
152
+        if after.attackers(piece.color, push.to_square) and not after.attackers(not piece.color, push.to_square):
153
+            continue  # den Bauern könnte man einfach schlagen
154
+        return push
155
+    return None
156
+
157
+
131158
 def describe(before, move, hero):
132159
     """Sätze und Kreise ((feld, feld, Farbe), …) zu einem Zug der Variante."""
133160
     mover = before.turn
@@ -181,6 +208,12 @@ def describe(before, move, hero):
181208
         sentences.append(f"{NOMINATIVE[piece.piece_type][0].upper()}{NOMINATIVE[piece.piece_type][1:]} "
182209
                          "stand in Gefahr und ist jetzt in Sicherheit.")
183210
 
211
+    push = _pawn_attack(before, move.from_square) if you and not sentences and piece else None
212
+    if push is not None and _pawn_attack(after, move.to_square) is None:
213
+        sentences.append(f"{NOMINATIVE[piece.piece_type][0].upper()}{NOMINATIVE[piece.piece_type][1:]} "
214
+                         f"geht dem Angriff {_san(board_null(before), push)} aus dem Weg.")
215
+        shapes.append((push.from_square, push.to_square, "threat"))
216
+
184217
     if you and not sentences and piece and piece.piece_type == chess.PAWN \
185218
             and move.to_square in (chess.D4, chess.E4, chess.D5, chess.E5):
186219
         sentences.append("Der Bauer besetzt das Zentrum.")
@@ -424,10 +457,11 @@ def prune(tree):
424457
     return tree
425458
 
426459
 
427
-def comment(tree, threat=None, only_move=False, better=None):
460
+def comment(tree, threat=None, only_move=False, better=None, why=None, rival=None):
428461
     """Kommentare und Kreise für jeden Knoten (``node.comment``, ``meta["shapes"]``).
429462
 
430
-    ``better``: ein besserer Zug als der erste (für „Warum nicht?“)."""
463
+    ``better``: ein besserer Zug als der erste (für „Warum nicht?“), ``why``: Satz, was er gebracht
464
+    hätte. ``rival``: (Zug, Abstand in Prozentpunkten), wenn Stockfish einen anderen Zug vorzieht."""
431465
     board = tree.game.board()
432466
     hero = tree.hero
433467
     start = material(board, hero)
@@ -448,7 +482,12 @@ def comment(tree, threat=None, only_move
448482
             if only_move:
449483
                 sentences.append("Alle anderen Züge sind deutlich schlechter.")
450484
             if better is not None:
451
-                sentences.append(f"Besser war {_san(board, better)}.")
485
+                name = _san(board, better)
486
+                sentences.append(f"Besser war {name}." if why is None else f"Besser war {name}: {why}")
487
+            elif rival is not None:
488
+                other, gap = rival
489
+                sentences.append(f"Stockfish findet {_san(board, other)} "
490
+                                 + ("ähnlich gut." if gap < RIVAL_GAP else "besser."))
452491
             elif not sentences:
453492
                 sentences.append("Stockfish hält das für den besten Zug.")
454493
         elif before.turn != hero:
@@ -582,21 +621,23 @@ def explain_job(board, move, maia=None,
582621
     return job
583622
 
584623
 
585
-def _explain(engine, board, move, maia, name, limit, hero=None, better=None, cancel=None):
624
+def _explain(engine, board, move, maia, name, limit, hero=None, better=None, cancel=None, why=None):
586625
     _check(cancel)
587626
     tree = grow(board, move, engine, maia, name, limit, hero=hero, cancel=cancel)
588627
     _check(cancel)
589628
     if board.turn != tree.hero:
590629
         return comment(prune(tree))  # Zug des Gegners: keine Drohung, kein „einziger Zug“
591630
     played = tree.meta[tree.first()]["wp"]
592
-    only_move = False
631
+    only_move, rival = False, None
593632
     if better is None:
594
-        others = [win_pct(i["score"], board.turn)
595
-                  for i in engine.analyse(board, limit, multipv=3)
596
-                  if i.get("pv") and i["pv"][0] != move and "score" in i]
633
+        lines = [(i["pv"][0], win_pct(i["score"], board.turn))
634
+                 for i in engine.analyse(board, limit, multipv=3) if i.get("pv") and "score" in i]
635
+        others = [wp for m, wp in lines if m != move]
597636
         only_move = bool(others) and played - max(others) >= ONLY_MOVE_GAP
637
+        if lines and lines[0][0] != move:
638
+            rival = (lines[0][0], max(0.0, lines[0][1] - played))
598639
     threat = None if board.is_check() else threat_job(board, None, played)(engine)
599
-    return comment(prune(tree), threat, only_move, better)
640
+    return comment(prune(tree), threat, only_move, better, why, rival)
600641
 
601642
 
602643
 def why_not_job(board, move, maia=None, name="Maia", limit=EXPLAIN_LIMIT):
@@ -609,8 +650,9 @@ def why_not_job(board, move, maia=None,
609650
         best = (info.get("pv") or [None])[0]
610651
         if best is None or best == move:
611652
             return None
612
-        tree = _explain(engine, board, move, maia, name, limit, better=best)
613653
         other = _explain(engine, board, best, maia, name, limit)
654
+        played = win_pct(engine.analyse(board, limit, root_moves=[move])["score"], board.turn)
655
+        tree = _explain(engine, board, move, maia, name, limit, better=best, why=_gained(other, played))
614656
         graft(tree, tree.game, other)
615657
         tree.info(tree.first())["label"] = "Gespielt"
616658
         tree.info(tree.game.variations[1])["label"] = "Bester Zug"
@@ -619,6 +661,28 @@ def why_not_job(board, move, maia=None,
619661
     return job
620662
 
621663
 
664
+def _outcome(tree):
665
+    """Ende der Hauptlinie: (führt zum Matt, Materialgewinn, eigene Gewinnchance)."""
666
+    leaf = tree.game.end()
667
+    if leaf is tree.game:
668
+        return False, 0, 50.0
669
+    after = leaf.board()
670
+    mate = after.is_checkmate() and after.turn != tree.hero or bool(tree.meta.get(leaf, {}).get("mate"))
671
+    return mate, material(after, tree.hero) - material(tree.game.board(), tree.hero), _chance(tree, leaf)
672
+
673
+
674
+def _gained(best, played):
675
+    """Was der bessere Zug gebracht hätte, als Satz, mit dem Weg dorthin. ``played``: Gewinnchance
676
+    nach dem gespielten Zug."""
677
+    mate, gain, chance = _outcome(best)
678
+    where = "Den Weg zeigt der Pfeil „Bester Zug“ in der Ausgangsstellung (mit <)."
679
+    if mate:
680
+        return f"Damit setzt du matt. {where}"
681
+    if gain > 0:
682
+        return f"Damit gewinnst du {gain_text(gain)}. {where}"
683
+    return f"Damit stehst du besser (Gewinnchance {round(chance)} statt {round(played)} %). {where}"
684
+
685
+
622686
 def explore_job(board, move, hero, maia=None, name="Maia", limit=EXPLAIN_LIMIT):
623687
     """Job fürs Analysebrett: ``move`` selbst gezogen. Für ``hero`` mit „Besser war …“, wenn es
624688
     einen besseren Zug gibt; für den Gegner antwortet Stockfish."""

modified tests/test_explain.py +29 −1

@@ -45,6 +45,13 @@ class DescribeTest(unittest.TestCase):
4545
 
4646
 
4747
 class TrimTest(unittest.TestCase):
48
+    def test_attack_with_checks_runs_on(self):
49
+        board = chess.Board()
50
+        for san in "e4 g6 Nf3 g5 h3 f6".split():
51
+            board.push_san(san)
52
+        pv = [m(u) for u in "f3g5 e7e6 d1h5 e8e7 h5f7 e7d6 g5h7 f8h6".split()]
53
+        self.assertEqual(explain.trim(board, pv), pv[:7])  # bis Sxh7, nicht schon nach Sxg5 e6
54
+
4855
     def test_stops_after_exchange_settles(self):
4956
         # Sxd5, danach ruhige Züge: nach der Antwort ist der Gewinn eingefahren
5057
         board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
@@ -212,7 +219,28 @@ class ExplainJobTest(unittest.TestCase):
212219
             engine.quit()
213220
         self.assertEqual([n.move for n in tree.game.variations], [m("e1e2"), m("c3d5")])
214221
         self.assertEqual(tree.label(tree.first()), "Gespielt")
215
-        self.assertIn("Besser war Sxd5.", tree.first().comment)
222
+        self.assertIn("Besser war Sxd5: Damit gewinnst du die Dame.", tree.first().comment)
223
+
224
+    def test_hint_that_is_not_stockfishs_best_says_so(self):
225
+        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
226
+        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
227
+        try:
228
+            tree = explain.explain_job(board, m("e1e2"), limit=chess.engine.Limit(depth=10))(engine)
229
+        finally:
230
+            engine.quit()
231
+        self.assertIn("Stockfish findet Sxd5 besser.", tree.first().comment)
232
+
233
+
234
+class PawnAttackTest(unittest.TestCase):
235
+    def test_piece_dodging_a_pawn_push_is_explained(self):
236
+        board = chess.Board("rnbqkbnr/p3p3/1ppp1p2/6pp/2B1P3/2PP1N1P/PP3PP1/RNBQ1RK1 w kq - 0 8")
237
+        text, shapes = explain.describe(board, m("f3h2"), chess.WHITE)
238
+        self.assertEqual(text, ["Der Springer geht dem Angriff g4 aus dem Weg."])
239
+        self.assertIn((chess.G5, chess.G4, "threat"), shapes)
240
+
241
+    def test_no_dodge_when_the_pawn_would_just_be_taken(self):
242
+        board = chess.Board("4k3/8/8/6p1/8/5N2/8/4K1R1 w - - 0 1")  # den Bauern auf g4 nähme der Turm
243
+        self.assertIsNone(explain._pawn_attack(board, chess.F3))
216244
 
217245
 
218246
 if __name__ == "__main__":