Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(hints): Stockfish hint is refined in the background, mate is final at once

public

feat(hints): Stockfish hint is refined in the background, mate is final at once

The hint is precomputed while the human thinks: provisional from depth 8,
updated after every depth up to 18, final at once when Stockfish finds a mate
for the side to move. A hint that is already shown stays put. Replaces the
1 s deadline; the thinking job now runs as a single analysis instead of
restarting after the hint. Inactive windows stop only after the final hint.

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

modified schach/annotate.py +30 −33

@@ -6,7 +6,6 @@ einzeln nachgerechnet ("lazy") – oft lässt sich das sogar ganz vermeiden.
66
 """
77
 
88
 import threading
9
-import time
109
 
1110
 import chess
1211
 import chess.engine
@@ -26,10 +25,10 @@ NAG = {"!": 1, "?": 2, "!!": 3, "??": 4,
2625
 BLUNDER, MISTAKE, INACCURACY = 15.0, 10.0, 5.0
2726
 # Ein "einziger Zug": alle Alternativen sind mindestens so viel schlechter
2827
 ONLY_MOVE_GAP = 12.0
29
-# Hinweis von Stockfish: spätestens nach so vielen Sekunden, wenn mindestens HINT_MIN_DEPTH erreicht
30
-# ist. In klar gewonnenen Stellungen braucht Stockfish für eine einzige Tiefe manchmal Sekunden.
31
-HINT_DEADLINE = 1.0
28
+# Hinweis von Stockfish, auf Vorrat: vorläufig ab HINT_MIN_DEPTH (bei einem eigenen Matt sofort), dann
29
+# mit jeder Tiefe nachgeschärft bis HINT_DEPTH. Wer früh H drückt, bekommt den aktuellen Stand.
3230
 HINT_MIN_DEPTH = 8
31
+HINT_DEPTH = 18
3332
 
3433
 TOP_LINES = 3  # so viele beste Züge rechnet Stockfish live mit
3534
 THINK_LIMIT = chess.engine.Limit(depth=30, time=30)  # Obergrenze fürs Mitdenken
@@ -137,10 +136,10 @@ class Thinking:
137136
 def think_job(board, thinking, on_snapshot, on_hint=None):
138137
     """Job-Fabrik: Stockfish denkt mit, solange der Mensch überlegt.
139138
 
140
-    1. Top-Linien live bis ``MIN_DEPTH`` rechnen (bzw. bis HINT_DEADLINE, s. dort),
141
-    2. ``on_hint(bester Zug)``, falls Stockfish der Hinweisgeber ist,
142
-    3. weiter in die Tiefe, bis ``thinking.stop()``.
143
-    ``on_snapshot``/``on_hint`` laufen im Worker-Thread; Ergebnis ist die letzte Momentaufnahme.
139
+    Rechnet die Top-Linien live immer tiefer, bis ``thinking.stop()``. ``on_hint(zug, endgültig)``
140
+    (nur wenn Stockfish der Hinweisgeber ist): ab HINT_MIN_DEPTH nach jeder Tiefe, endgültig bei
141
+    HINT_DEPTH oder einem eigenen Matt. ``on_snapshot``/``on_hint`` laufen im Worker-Thread;
142
+    Ergebnis ist die letzte Momentaufnahme.
144143
     """
145144
     board = board.copy()
146145
 
@@ -148,31 +147,29 @@ def think_job(board, thinking, on_snapsh
148147
         n = min(TOP_LINES, board.legal_moves.count())
149148
         if n == 0:
150149
             return None
151
-
152
-        def stream(until_depth):
153
-            last = None
154
-            limit = QUICK_LIMIT if thinking.stopped else THINK_LIMIT
155
-            start = time.monotonic()
156
-            with engine.analysis(board, limit, multipv=n) as analysis:
157
-                thinking.attach(analysis)
158
-                for info in analysis:
159
-                    # Zeilen 1..n kommen am Ende jeder Tiefe; Zeile n = Tiefe fertig
160
-                    if info.get("multipv") == n and "depth" in info:
161
-                        last = _entry(analysis.multipv, board.turn, info["depth"])
162
-                        on_snapshot(last)
163
-                        if until_depth and (info["depth"] >= until_depth or info["depth"] >= HINT_MIN_DEPTH
164
-                                            and time.monotonic() - start >= HINT_DEADLINE):
165
-                            break
166
-                if last is None:
167
-                    last = _entry(analysis.multipv, board.turn, 0)
168
-            return last
169
-
170
-        last = stream(MIN_DEPTH)
171
-        if thinking.stopped:
172
-            return last
173
-        if on_hint is not None:
174
-            on_hint(last["best"])
175
-        return stream(None)
150
+        quick = thinking.stopped  # schon gezogen: nur rasch die Bewertung, kein Hinweis
151
+        last, settled = None, on_hint is None or quick
152
+        with engine.analysis(board, QUICK_LIMIT if quick else THINK_LIMIT, multipv=n) as analysis:
153
+            thinking.attach(analysis)
154
+            for info in analysis:
155
+                # Zeilen 1..n kommen am Ende jeder Tiefe; Zeile n = Tiefe fertig
156
+                if info.get("multipv") != n or "depth" not in info:
157
+                    continue
158
+                last = _entry(analysis.multipv, board.turn, info["depth"])
159
+                on_snapshot(last)
160
+                if settled or thinking.stopped:
161
+                    continue
162
+                top = analysis.multipv[0]
163
+                score = top["score"].pov(board.turn) if "score" in top else None
164
+                mate = score is not None and score.is_mate() and score.mate() > 0
165
+                if top.get("pv") and (mate or info["depth"] >= HINT_MIN_DEPTH):
166
+                    settled = mate or info["depth"] >= HINT_DEPTH
167
+                    on_hint(top["pv"][0], settled)
168
+            if last is None:
169
+                last = _entry(analysis.multipv, board.turn, 0)
170
+        if not settled and not thinking.stopped and last["best"] is not None:
171
+            on_hint(last["best"], True)  # Rechnung endete vorher (z. B. Matt gefunden, Zeitgrenze)
172
+        return last
176173
 
177174
     return job
178175
 

modified schach/app.py +11 −5

@@ -137,6 +137,7 @@ class Window(OnlineMixin, PuzzleMixin, O
137137
         self.why_not_entries = {}  # (FEN davor, Zug) -> „Warum nicht?“ aus der Zugliste
138138
         self.badge_ply = None
139139
         self.hint_move = None
140
+        self.hint_final = False
140141
         self.hint_level = 0
141142
         self.hint_pending = False
142143
         self.hint_error = None
@@ -868,6 +869,7 @@ class Window(OnlineMixin, PuzzleMixin, O
868869
         self._wait_done()  # eine laufende Rechnung gehörte zur alten Stellung
869870
         self.gen += 1
870871
         self.hint_move = None
872
+        self.hint_final = False
871873
         self.hint_level = 0
872874
         self.hint_pending = False
873875
         self.hint_error = None
@@ -1292,8 +1294,8 @@ class Window(OnlineMixin, PuzzleMixin, O
12921294
         def snapshot_from_thread(entry):
12931295
             GLib.idle_add(self._on_snapshot, key, entry, False)
12941296
 
1295
-        def hint_from_thread(move):
1296
-            GLib.idle_add(self._on_hint, gen, move)
1297
+        def hint_from_thread(move, final):
1298
+            GLib.idle_add(self._on_hint, gen, move, None, final)
12971299
 
12981300
         def on_done(entry, error):
12991301
             if entry is not None:
@@ -1332,14 +1334,18 @@ class Window(OnlineMixin, PuzzleMixin, O
13321334
             self._annotate(ply, move, before)
13331335
         return False
13341336
 
1335
-    def _on_hint(self, gen, move, error=None):
1337
+    def _on_hint(self, gen, move, error=None, final=True):
1338
+        """Hinweis fertig – oder vorläufig (``final`` False): Stockfish schärft ihn noch nach."""
13361339
         if gen != self.gen:
13371340
             return False
1341
+        if self.hint_level > 0 and self.hint_move is not None:
1342
+            return False  # schon gezeigt: bleibt stehen, auch wenn Stockfish tiefer etwas anderes findet
13381343
         self.hint_move = move
1344
+        self.hint_final = final
13391345
         self.hint_error = error if move is None else None
13401346
         if move is None and error is None:
13411347
             self.hint_error = "kein Zug gefunden"
1342
-        if not self.is_active() and self.thinking is not None:
1348
+        if final and not self.is_active() and self.thinking is not None:
13431349
             self.thinking.stop()  # Hinweis ist da; tiefer rechnet nur das aktive Fenster
13441350
             self.thinking = None
13451351
         if self.hint_pending:
@@ -1980,7 +1986,7 @@ class Window(OnlineMixin, PuzzleMixin, O
19801986
         # sonst: erst den Hinweis fertig rechnen (_on_hint stoppt dann), sonst wartet man nach der Rückkehr
19811987
 
19821988
     def _hint_ready(self):
1983
-        return self.hint_move is not None or self.hint_error is not None
1989
+        return (self.hint_move is not None and self.hint_final) or self.hint_error is not None
19841990
 
19851991
     def _stop_thinking(self):
19861992
         self.thinking.stop()

added tests/test_think.py +48 −0

@@ -0,0 +1,48 @@
1
+import shutil
2
+import threading
3
+import unittest
4
+
5
+import chess
6
+import chess.engine
7
+
8
+from schach import annotate
9
+
10
+MATE_IN_ONE = "rn2kb1r/p4ppp/2p5/Bp2p3/4n1b1/1B3N2/PPP2PPP/RN1QR1K1 w kq - 0 11"  # Dd8#
11
+
12
+
13
+@unittest.skipUnless(shutil.which("stockfish"), "stockfish nicht installiert")
14
+class ThinkJobTest(unittest.TestCase):
15
+    def think(self, fen, until):
16
+        """think_job laufen lassen, bis ``until(hints)`` gilt; gibt die Hinweise zurück."""
17
+        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
18
+        thinking, hints, done = annotate.Thinking(), [], threading.Event()
19
+
20
+        def on_hint(move, final):
21
+            hints.append((move, final))
22
+            if until(hints):
23
+                thinking.stop()
24
+                done.set()
25
+        try:
26
+            worker = threading.Thread(target=annotate.think_job(chess.Board(fen), thinking, lambda e: None,
27
+                                                                on_hint), args=(engine,))
28
+            worker.start()
29
+            done.wait(30)
30
+            thinking.stop()
31
+            worker.join()
32
+        finally:
33
+            engine.quit()
34
+        return hints
35
+
36
+    def test_mate_is_final_at_once(self):
37
+        hints = self.think(MATE_IN_ONE, lambda h: True)
38
+        self.assertEqual(hints[0], (chess.Move.from_uci("d1d8"), True))
39
+
40
+    def test_hint_is_refined_until_final(self):
41
+        hints = self.think(chess.STARTING_FEN, lambda h: h[-1][1])
42
+        self.assertFalse(hints[0][1])  # erst vorläufig …
43
+        self.assertTrue(hints[-1][1])  # … dann endgültig
44
+        self.assertEqual(sum(final for _m, final in hints), 1)
45
+
46
+
47
+if __name__ == "__main__":
48
+    unittest.main()