Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(threat): show what the opponent threatens (key B)

public

feat(threat): show what the opponent threatens (key B)

Two steps like the hint, reversed: threatened square first, then the
threatening piece with an arrow. Maia at the opponent's strength picks
what would be seen on a null-move board, Stockfish only confirms it
gains >= 10 points win chance. Source switchable to Stockfish in the
hint menu. Runs on a small second Stockfish so live thinking goes on.
Counts as a hint in puzzles.

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

modified README.md +11 −3

@@ -3,8 +3,14 @@
33
 Schlichtes GNOME-Schachprogramm (Python, GTK4, libadwaita).
44
 
55
 - **Gegner:** Maia-3 (79M-Modell), Stärke 600–2500 Elo, mit menschlicher Streuung.
6
-- **Hinweis** (Taste `H`): Maia-3 auf 2000 Elo. Erster Druck lässt die Figur
7
-  leuchten, zweiter Druck auch das Zielfeld.
6
+- **Hinweis** (Taste `H`): Erster Druck lässt die Figur leuchten, zweiter Druck auch
7
+  das Zielfeld. Wer hilft, steht im Pfeil-Menü daneben: Maia 1500, 2000 (Standard) oder
8
+  2500 – jeweils von Stockfish geprüft – oder Stockfish selbst.
9
+- **Drohung** (Taste `B`, Warndreieck): umgekehrt zum Hinweis. Erster Druck zeigt das
10
+  bedrohte Feld (orange), zweiter die drohende Figur mit Pfeil. Die Drohung passt zum
11
+  Gegner: Maia in seiner Stärke schlägt vor, was er sehen würde, Stockfish prüft nur, ob es
12
+  wirklich etwas gewinnt. Im Pfeil-Menü lässt sich auf „Stockfish“ (objektiv) umstellen.
13
+  Bei Rätseln zählt die Drohung wie ein Hinweis.
814
 - **Zugbewertung:** Stockfish denkt mit, während du überlegst (Top-3-Züge, live
915
   immer tiefer); andere Züge werden nur bei Bedarf einzeln nachgerechnet.
1016
   Nur auffällige Züge bekommen ein Zeichen an der Figur: `!!` `!` `?!` `?` `??`.
@@ -59,6 +65,7 @@ Ins App-Menü aufnehmen:
5965
 | Strg+N | Neue Partie |
6066
 | Strg+Z | Zug zurücknehmen |
6167
 | H | Hinweis |
68
+| B | Drohung zeigen |
6269
 | F | Brett drehen |
6370
 | A | Zugliste ein/aus |
6471
 | R | Neues Rätsel |
@@ -73,7 +80,8 @@ Ins App-Menü aufnehmen:
7380
 
7481
 ## Stellschrauben
7582
 
76
-- `schach/app.py`: `HINT_ELO`, `MIN_REPLY_SECONDS`
83
+- `schach/app.py`: `HELPERS` (Hinweis-Helfer), `MIN_REPLY_SECONDS`
84
+- `schach/threat.py`: `THREAT_GAIN` (ab wann eine Drohung zählt), `THREAT_LIMIT`
7785
 - `schach/annotate.py`: Schwellen für `?!`/`?`/`??` und für „einziger Zug“ (`!`)
7886
 - Brettfarben: `SCHEMES` in `schach/board.py`
7987
 - Einstellungen: `~/.config/schach/settings.json`

modified ROADMAP.md +10 −0

@@ -115,6 +115,12 @@ Gilt sofort, ohne Speichern-Knopf (HIG-Muster für Einstellungen).
115115
 
116116
 ## 1. Bedrohungshinweis (Taste B)
117117
 
118
+**Status:** umgesetzt (20.11.2026). Abweichung: Die Rechnung startet erst beim
119
+Drücken, nicht vorab. Dafür läuft sie auf einem zweiten, kleinen Stockfish, damit
120
+das Mitdenken nicht unterbrochen wird. Im Schach zeigt sie die schachgebende Figur
121
+mit Pfeil zum König. Gibt es keine Drohung, erscheint ein Toast, und der Knopf ist
122
+für diese Stellung erledigt.
123
+
118124
 Der Ablauf ist zweistufig wie beim Hinweis, nur umgekehrt:
119125
 
120126
 1. **Erster Druck:** Das bedrohte Feld leuchtet, z. B. die eigene hängende Figur
@@ -153,6 +159,10 @@ wenn er jetzt am Zug wäre?“:
153159
 
154160
 ## 2. Helfer wählbar: Split-Button „Hinweis▾“
155161
 
162
+**Status:** umgesetzt (20.11.2026). Abweichung: Die Auswahl gilt global, nicht pro
163
+Modus. Bei Rätseln ist der Hinweis ohnehin die Lösung, deshalb ist „Hinweis von“
164
+dort ausgegraut.
165
+
156166
 Der Hinweis-Knopf wird ein `Adw.SplitButton`. Die HIG nennt Split-Buttons
157167
 ausdrücklich für Titelleisten. Ein Klick gibt wie bisher einen Hinweis, der Pfeil
158168
 öffnet ein Menü mit zwei Auswahlgruppen (Radio-Aktionen):

modified schach/app.py +126 −1

@@ -20,6 +20,7 @@ from .board import BoardView, available_
2020
 from .movelist import MoveList  # noqa: E402
2121
 from .prefs import Preferences  # noqa: E402
2222
 from .engines import MAIA_CMD, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move  # noqa: E402
23
+from .threat import null_board, threat_job  # noqa: E402
2324
 from .online import OnlineMixin  # noqa: E402
2425
 from .puzzles import PuzzleMixin  # noqa: E402
2526
 
@@ -33,6 +34,8 @@ HELPERS = {
3334
     "stockfish": ("Stockfish", None),
3435
 }
3536
 DEFAULT_HELPER = "maia2000"
37
+# Wer bestimmt die Bedrohung? "opponent": Maia in der Stärke des Gegners, geprüft von Stockfish
38
+THREAT_SOURCES = {"opponent": "wie der Gegner", "stockfish": "Stockfish"}
3639
 OPPONENT_TEMPERATURE = 1.0  # menschliche Streuung; 0 = immer der wahrscheinlichste Zug
3740
 MIN_REPLY_SECONDS = 0.6
3841
 AUTOSAVE_DELAY_MS = 800
@@ -45,6 +48,7 @@ SETTINGS_PATH = os.path.join(GLib.get_us
4548
 DEFAULTS = {
4649
     "elo": 1200, "color": "white", "theme": "cburnett", "puzzle_difficulty": "normal",
4750
     "temperature": OPPONENT_TEMPERATURE, "scheme": "holz", "hint_helper": DEFAULT_HELPER,
51
+    "threat_source": "opponent",
4852
 }
4953
 
5054
 
@@ -101,6 +105,9 @@ class Window(OnlineMixin, PuzzleMixin, A
101105
         self.hint_pending = False
102106
         self.hint_error = None
103107
         self.hint_prefetch_gen = None
108
+        self.threat_move = None  # Bedrohung: Zug des Gegners, den er spielen würde, wäre er am Zug
109
+        self.threat_level = 0  # 1 = bedrohtes Feld, 2 = auch die drohende Figur (2 ohne Zug: keine Drohung)
110
+        self.threat_pending = False
104111
         self.thinking = None  # laufende Stockfish-Rechnung, während der Mensch nachdenkt
105112
         self.pending_symbols = {}  # FEN -> (Halbzug, Zug, Stellung davor)
106113
         self.maia_ready = app.maia_ready
@@ -205,8 +212,12 @@ class Window(OnlineMixin, PuzzleMixin, A
205212
         helpers = Gio.Menu()
206213
         for key, (label, _elo) in HELPERS.items():
207214
             helpers.append(label, f"win.hint-helper::{key}")
215
+        sources = Gio.Menu()
216
+        for key, label in THREAT_SOURCES.items():
217
+            sources.append(label, f"win.threat-source::{key}")
208218
         helper_menu = Gio.Menu()
209219
         helper_menu.append_section("Hinweis von", helpers)
220
+        helper_menu.append_section("Drohung von", sources)
210221
         self.helper_menu = helper_menu
211222
         self.hint_content = Adw.ButtonContent(icon_name="dialog-information-symbolic", label="Hinweis")
212223
         self.hint_btn = Adw.SplitButton(
@@ -215,6 +226,9 @@ class Window(OnlineMixin, PuzzleMixin, A
215226
         self.hint_btn.set_action_name("win.hint")
216227
         self.help_box = Gtk.Box(spacing=6)
217228
         self.help_box.append(self.hint_btn)
229
+        self.threat_btn = Gtk.Button(icon_name="dialog-warning-symbolic")
230
+        self.threat_btn.set_action_name("win.threat")
231
+        self.help_box.append(self.threat_btn)
218232
         self.mode_stack.add_named(self.help_box, "help")
219233
 
220234
         online_menu = Gio.Menu()
@@ -303,6 +317,7 @@ class Window(OnlineMixin, PuzzleMixin, A
303317
             ("new-game", self._new_game_dialog),
304318
             ("undo", self.undo),
305319
             ("hint", self.hint),
320
+            ("threat", self.threat),
306321
             ("flip", self.flip),
307322
             ("save-pgn", self._save_pgn),
308323
             ("save-game", self._save_game_dialog),
@@ -339,11 +354,17 @@ class Window(OnlineMixin, PuzzleMixin, A
339354
         )
340355
         helper.connect("activate", lambda _a, v: self.get_application().update_setting("hint_helper", v.get_string()))
341356
         self.add_action(helper)
357
+        source = Gio.SimpleAction.new_stateful(
358
+            "threat-source", GLib.VariantType.new("s"), GLib.Variant.new_string(self._threat_source()),
359
+        )
360
+        source.connect("activate", lambda _a, v: self.get_application().update_setting("threat_source", v.get_string()))
361
+        self.add_action(source)
342362
 
343363
         app = self.get_application()
344364
         app.set_accels_for_action("win.new-game", ["<Control>n"])
345365
         app.set_accels_for_action("win.undo", ["<Control>z"])
346366
         app.set_accels_for_action("win.hint", ["h"])
367
+        app.set_accels_for_action("win.threat", ["b"])
347368
         app.set_accels_for_action("win.flip", ["f"])
348369
         app.set_accels_for_action("win.save-game", ["<Control>s"])
349370
         app.set_accels_for_action("win.open-saves", ["<Control>o"])
@@ -444,6 +465,7 @@ class Window(OnlineMixin, PuzzleMixin, A
444465
             v.interactive = False
445466
             v.selected = None
446467
             v.hint_from = v.hint_to = None
468
+            v.threat_from = v.threat_to = None
447469
             symbol = self.symbols.get(self.browse_ply)
448470
             v.badge = (shown.peek().to_square, symbol) if symbol else None
449471
             v.queue_draw()
@@ -459,6 +481,9 @@ class Window(OnlineMixin, PuzzleMixin, A
459481
 
460482
         v.hint_from = self.hint_move.from_square if self.hint_move and self.hint_level >= 1 else None
461483
         v.hint_to = self.hint_move.to_square if self.hint_move and self.hint_level >= 2 else None
484
+        threat = self.threat_move if self._human_to_move() else None
485
+        v.threat_to = threat.to_square if threat and self.threat_level >= 1 else None
486
+        v.threat_from = threat.from_square if threat and self.threat_level >= 2 else None
462487
 
463488
         v.badge = None
464489
         if self.badge_ply is not None and self.badge_ply in self.symbols:
@@ -517,6 +542,21 @@ class Window(OnlineMixin, PuzzleMixin, A
517542
             else f"Hinweis von {HELPERS[self._helper()][0]} (H)"
518543
         )
519544
         self._action("hint-helper").set_enabled(self.mode == "maia")  # Rätsel: Hinweis = Lösung
545
+        puzzle_open = self.mode != "puzzle" or (self.puzzle is not None and not self.puzzle["done"])
546
+        can_threat = (
547
+            hints and puzzle_open and self._human_to_move() and self.threat_level < 2
548
+            and not self.threat_pending and not self._browsing()
549
+        )
550
+        self._action("threat").set_enabled(can_threat)
551
+        if self.threat_level == 1:
552
+            tip = "Drohende Figur zeigen (B)"
553
+        elif self._threat_source() == "stockfish":
554
+            tip = "Drohung zeigen (B) – von Stockfish"
555
+        else:
556
+            tip = f"Drohung zeigen (B) – was {self._opponent_label()} sehen würde"
557
+        if self.mode == "puzzle":
558
+            tip += " – das Rätsel zählt dann nicht als gelöst"
559
+        self.threat_btn.set_tooltip_text(tip)
520560
         user = self.get_application().lichess_user
521561
         self.online_content.set_label((user or {}).get("username") or "Lichess")
522562
         slot = "help" if hints else "online" if self.mode == "online" else "none"
@@ -582,6 +622,9 @@ class Window(OnlineMixin, PuzzleMixin, A
582622
         self.hint_pending = False
583623
         self.hint_error = None
584624
         self.hint_prefetch_gen = None
625
+        self.threat_move = None
626
+        self.threat_level = 0
627
+        self.threat_pending = False
585628
         if self.thinking is not None:
586629
             self.thinking.stop()
587630
             self.thinking = None
@@ -730,6 +773,75 @@ class Window(OnlineMixin, PuzzleMixin, A
730773
             self.hint_pending = True  # Vorausberechnung läuft noch; zeigt sich, sobald fertig
731774
             self._refresh()
732775
 
776
+    # --- Bedrohung ---------------------------------------------------------
777
+
778
+    def _threat_source(self):
779
+        source = self.settings.get("threat_source", "opponent")
780
+        return source if source in THREAT_SOURCES else "opponent"
781
+
782
+    def _opponent_elo(self):
783
+        if self.mode == "puzzle" and self.puzzle and self.puzzle.get("rating"):
784
+            return min(2500, max(600, int(self.puzzle["rating"])))
785
+        return self.elo
786
+
787
+    def _opponent_label(self):
788
+        return f"Maia {self._opponent_elo()}"
789
+
790
+    def threat(self, *_):
791
+        """Erster Druck: bedrohtes Feld, zweiter: auch die drohende Figur."""
792
+        if self.mode not in ("maia", "puzzle") or not self._human_to_move() or self._browsing():
793
+            return
794
+        if self.mode == "puzzle" and (self.puzzle is None or self.puzzle["done"]):
795
+            return
796
+        if self.threat_level == 1:
797
+            self.threat_level = 2
798
+            self._refresh()
799
+            return
800
+        if self.threat_level >= 2 or self.threat_pending:
801
+            return
802
+        self.threat_pending = True
803
+        self._refresh_chrome()
804
+        gen = self.gen
805
+        board = self.board.copy()
806
+        entry = self.analyses.get(annotate.key(board))
807
+        baseline = None
808
+        if entry and entry["depth"] >= annotate.MIN_DEPTH and entry["scores"]:
809
+            baseline = max(entry["scores"].values())  # eigene Gewinnchance, schon vom Mitdenken bekannt
810
+        side = self.get_application().side_engine()
811
+        stockfish = self._threat_source() == "stockfish"
812
+        who = "Stockfish" if stockfish else self._opponent_label()
813
+
814
+        def on_threat(move, error):
815
+            if gen != self.gen:
816
+                return
817
+            self.threat_pending = False
818
+            if error is not None:
819
+                self.toasts.add_toast(Adw.Toast(title=f"Drohung nicht berechenbar: {error}"))
820
+            elif move is None:
821
+                self.threat_level = 2  # für diese Stellung erledigt
822
+                text = "Stockfish sieht keine akute Drohung" if stockfish else f"Keine Drohung, die {who} sehen würde"
823
+                self.toasts.add_toast(Adw.Toast(title=text, timeout=3))
824
+            else:
825
+                self.threat_move = move
826
+                self.threat_level = 1
827
+                if self.mode == "puzzle":
828
+                    self._puzzle_fail()
829
+            self._refresh()
830
+
831
+        if stockfish or board.is_check():
832
+            side.submit(threat_job(board, None, baseline), on_threat)
833
+            return
834
+
835
+        def on_candidates(moves, error):
836
+            if gen != self.gen:
837
+                return
838
+            if error is not None:
839
+                on_threat(None, error)
840
+                return
841
+            side.submit(threat_job(board, moves or [], baseline), on_threat)
842
+
843
+        self.maia.submit(maia_candidates(null_board(board), self._opponent_elo(), 5), on_candidates)
844
+
733845
     def _reveal_hint(self):
734846
         if self.hint_move is None:
735847
             self.toasts.add_toast(Adw.Toast(title=f"Kein Hinweis möglich: {self.hint_error}"))
@@ -1036,6 +1148,11 @@ class Window(OnlineMixin, PuzzleMixin, A
10361148
     def apply_setting(self, key, value):
10371149
         """Von den Einstellungen gerufen (für jedes Fenster)."""
10381150
         self.settings[key] = value
1151
+        if key == "threat_source":
1152
+            self._action("threat-source").set_state(GLib.Variant.new_string(value))
1153
+            if self.threat_level == 2 and self.threat_move is None:
1154
+                self.threat_level = 0  # „keine Drohung“ galt nur für die alte Quelle
1155
+            self._refresh_chrome()
10391156
         if key == "hint_helper":
10401157
             self._action("hint-helper").set_state(GLib.Variant.new_string(value))
10411158
             if self.mode == "maia" and self._human_to_move():
@@ -1125,7 +1242,7 @@ class Window(OnlineMixin, PuzzleMixin, A
11251242
         for title, items in [
11261243
             ("Partie", [
11271244
                 ("Neue Partie", "<Control>n"), ("Zug zurücknehmen", "<Control>z"),
1128
-                ("Hinweis", "h"), ("Neues Rätsel", "r"),
1245
+                ("Hinweis", "h"), ("Drohung zeigen", "b"), ("Neues Rätsel", "r"),
11291246
             ]),
11301247
             ("Ansicht", [
11311248
                 ("Brett drehen", "f"), ("Zugliste und Bewertung", "a"),
@@ -1383,6 +1500,7 @@ class SchachApp(Adw.Application):
13831500
         self.maia_ready = False
13841501
         self.maia = None
13851502
         self.stockfish = None
1503
+        self.stockfish_side = None  # zweiter, kleiner Stockfish für Bedrohungen (das Mitdenken läuft weiter)
13861504
         self.lichess_client = None  # nur angemeldet
13871505
         self.lichess_user = None
13881506
         self.lichess_events = None
@@ -1468,6 +1586,11 @@ class SchachApp(Adw.Application):
14681586
             win._refresh()
14691587
         self._toast(Adw.Toast(title="Von Lichess abgemeldet", timeout=2))
14701588
 
1589
+    def side_engine(self):
1590
+        if self.stockfish_side is None:
1591
+            self.stockfish_side = EngineWorker(STOCKFISH_CMD, options={"Threads": 2, "Hash": 64})
1592
+        return self.stockfish_side
1593
+
14711594
     def update_setting(self, key, value):
14721595
         settings = load_settings()
14731596
         settings[key] = value
@@ -1559,6 +1682,8 @@ class SchachApp(Adw.Application):
15591682
             self.lichess_events.close()
15601683
         self.maia.close()
15611684
         self.stockfish.close()
1685
+        if self.stockfish_side is not None:
1686
+            self.stockfish_side.close()
15621687
         Adw.Application.do_shutdown(self)
15631688
 
15641689
 

modified schach/board.py +42 −7

@@ -54,6 +54,7 @@ def scheme_colors(name):
5454
     return light, dark, scheme["last"], scheme["selected"]
5555
 
5656
 HINT = (0.21, 0.52, 0.89)
57
+THREAT = (0.91, 0.36, 0.11)
5758
 CHECK = (0.88, 0.11, 0.14)
5859
 BADGE = {
5960
     "!!": (0.10, 0.62, 0.55),
@@ -101,6 +102,8 @@ class BoardView(Gtk.DrawingArea):
101102
         self.last_move = None
102103
         self.hint_from = None
103104
         self.hint_to = None
105
+        self.threat_from = None  # Bedrohung: drohende Figur (Stufe 2) …
106
+        self.threat_to = None  # … und bedrohtes Feld (Stufe 1)
104107
         self.badge = None  # (feld, symbol)
105108
         self.selected = None
106109
         self.on_move = None  # callback(von, nach)
@@ -310,13 +313,10 @@ class BoardView(Gtk.DrawingArea):
310313
                 self._glow(cr, king, sq, CHECK, 0.85)
311314
         for s in (self.hint_from, self.hint_to):
312315
             if s is not None:
313
-                self._glow(cr, s, sq, HINT, 0.9)
314
-                x, y = self._square_origin(s)
315
-                cr.set_source_rgba(*HINT, 0.95)
316
-                cr.set_line_width(max(sq * 0.05, 2))
317
-                inset = sq * 0.04
318
-                cr.rectangle(x + inset, y + inset, sq - 2 * inset, sq - 2 * inset)
319
-                cr.stroke()
316
+                self._mark(cr, s, sq, HINT)
317
+        for s in (self.threat_from, self.threat_to):
318
+            if s is not None:
319
+                self._mark(cr, s, sq, THREAT)
320320
 
321321
         self._draw_coordinates(cr, sq)
322322
 
@@ -345,6 +345,9 @@ class BoardView(Gtk.DrawingArea):
345345
                 x1, y1 = self._square_origin(dst)
346346
                 self._draw_piece(cr, piece, x0 + (x1 - x0) * p, y0 + (y1 - y0) * p, sq)
347347
 
348
+        if self.threat_from is not None and self.threat_to is not None:
349
+            self._draw_arrow(cr, self.threat_from, self.threat_to, sq, THREAT)
350
+
348351
         self._draw_captures(cr, ox, oy, sq)
349352
         self._draw_players(cr, ox, oy, sq)
350353
 
@@ -371,6 +374,38 @@ class BoardView(Gtk.DrawingArea):
371374
                 s = sq * 1.1
372375
                 self._draw_piece(cr, piece, px - s / 2, py - s / 2, s)
373376
 
377
+    def _mark(self, cr, square, sq, rgb):
378
+        """Leuchtendes Feld mit Rahmen (Hinweis blau, Bedrohung orange)."""
379
+        self._glow(cr, square, sq, rgb, 0.9)
380
+        x, y = self._square_origin(square)
381
+        cr.set_source_rgba(*rgb, 0.95)
382
+        cr.set_line_width(max(sq * 0.05, 2))
383
+        inset = sq * 0.04
384
+        cr.rectangle(x + inset, y + inset, sq - 2 * inset, sq - 2 * inset)
385
+        cr.stroke()
386
+
387
+    def _draw_arrow(self, cr, src, dst, sq, rgb):
388
+        x0, y0 = self._square_origin(src)
389
+        x1, y1 = self._square_origin(dst)
390
+        x0, y0, x1, y1 = x0 + sq / 2, y0 + sq / 2, x1 + sq / 2, y1 + sq / 2
391
+        angle = math.atan2(y1 - y0, x1 - x0)
392
+        head = sq * 0.38
393
+        tip_x, tip_y = x1 - math.cos(angle) * sq * 0.12, y1 - math.sin(angle) * sq * 0.12
394
+        base_x, base_y = tip_x - math.cos(angle) * head * 0.8, tip_y - math.sin(angle) * head * 0.8
395
+        cr.new_path()
396
+        cr.set_source_rgba(*rgb, 0.8)
397
+        cr.set_line_width(sq * 0.13)
398
+        cr.set_line_cap(cairo.LINE_CAP_ROUND)
399
+        cr.move_to(x0 + math.cos(angle) * sq * 0.2, y0 + math.sin(angle) * sq * 0.2)
400
+        cr.line_to(base_x, base_y)
401
+        cr.stroke()
402
+        cr.move_to(tip_x, tip_y)
403
+        for side in (-0.5, 0.5):
404
+            cr.line_to(tip_x - head * math.cos(angle + side), tip_y - head * math.sin(angle + side))
405
+        cr.close_path()
406
+        cr.fill()
407
+        cr.set_line_cap(cairo.LINE_CAP_BUTT)
408
+
374409
     def _fill_square(self, cr, square, sq, rgba):
375410
         x, y = self._square_origin(square)
376411
         cr.set_source_rgba(*rgba)

added schach/threat.py +73 −0

@@ -0,0 +1,73 @@
1
+"""Bedrohungshinweis: Was würde der Gegner spielen, wenn er jetzt am Zug wäre?
2
+
3
+Maia (in der Stärke des Gegners) schlägt vor, *was gesehen wird*; Stockfish prüft
4
+nur, *ob es stimmt*. So bekommt man gegen Maia 800 keine Drohungen gezeigt, die
5
+ein 800er nie fände. Mit ``candidates=None`` sucht Stockfish selbst (objektiv).
6
+"""
7
+
8
+import chess
9
+import chess.engine
10
+
11
+from .annotate import win_pct
12
+
13
+THREAT_LIMIT = chess.engine.Limit(depth=12)
14
+THREAT_GAIN = 10.0  # so viele Prozentpunkte Gewinnchance muss die Drohung dem Gegner bringen
15
+STOCKFISH_LINES = 3
16
+
17
+
18
+def null_board(board):
19
+    """Dieselbe Stellung, aber der Gegner ist am Zug (ohne Zugverlauf, damit Engines nichts verwirrt)."""
20
+    probe = board.copy(stack=False)
21
+    probe.push(chess.Move.null())
22
+    return chess.Board(probe.fen())
23
+
24
+
25
+def check_threat(board):
26
+    """Im Schach ist die Drohung schon da: (schachgebende Figur → König)."""
27
+    king = board.king(board.turn)
28
+    checkers = list(board.checkers())
29
+    if king is None or not checkers:
30
+        return None
31
+    return chess.Move(checkers[0], king)
32
+
33
+
34
+def threat_job(board, candidates, baseline=None):
35
+    """Job-Fabrik für Stockfish: erste echte Drohung aus ``candidates`` oder None.
36
+
37
+    ``baseline``: eigene Gewinnchance in der echten Stellung (aus dem Mitdenken), sonst
38
+    wird sie hier gerechnet.
39
+    """
40
+    board = board.copy()
41
+    candidates = None if candidates is None else list(candidates)
42
+
43
+    def job(engine):
44
+        if board.is_check():
45
+            return check_threat(board)
46
+        nb = null_board(board)
47
+        if not any(nb.legal_moves):
48
+            return None
49
+        mine = baseline
50
+        if mine is None:
51
+            mine = win_pct(engine.analyse(board, THREAT_LIMIT)["score"], board.turn)
52
+        opponent_now = 100.0 - mine
53
+
54
+        known = {}
55
+        moves = candidates
56
+        if moves is None:
57
+            infos = engine.analyse(nb, THREAT_LIMIT, multipv=min(STOCKFISH_LINES, nb.legal_moves.count()))
58
+            for info in infos:
59
+                if info.get("pv") and "score" in info:
60
+                    known[info["pv"][0]] = win_pct(info["score"], nb.turn)
61
+            moves = sorted(known, key=known.get, reverse=True)
62
+        for move in moves:
63
+            if move not in nb.legal_moves:
64
+                continue
65
+            wp = known.get(move)
66
+            if wp is None:
67
+                info = engine.analyse(nb, THREAT_LIMIT, root_moves=[move])
68
+                wp = win_pct(info["score"], nb.turn)
69
+            if wp - opponent_now >= THREAT_GAIN:
70
+                return move
71
+        return None
72
+
73
+    return job

added tests/test_threat.py +58 −0

@@ -0,0 +1,58 @@
1
+import shutil
2
+import unittest
3
+
4
+import chess
5
+import chess.engine
6
+
7
+from schach import threat
8
+
9
+# 1.e4 e5 2.Bc4 Nc6 3.Qh5 – Schwarz am Zug, Weiß droht Dxf7#
10
+SCHOLAR = "r1bqkbnr/pppp1ppp/2n5/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 3 3"
11
+
12
+
13
+class NullBoardTest(unittest.TestCase):
14
+    def test_null_board_switches_side(self):
15
+        board = chess.Board(SCHOLAR)
16
+        nb = threat.null_board(board)
17
+        self.assertEqual(nb.turn, chess.WHITE)
18
+        self.assertFalse(nb.move_stack)
19
+        self.assertIn(chess.Move.from_uci("h5f7"), nb.legal_moves)
20
+
21
+    def test_check_threat_points_from_checker_to_king(self):
22
+        board = chess.Board("rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3")
23
+        self.assertEqual(threat.check_threat(board), chess.Move.from_uci("h4e1"))
24
+
25
+
26
+@unittest.skipUnless(shutil.which("stockfish"), "stockfish nicht installiert")
27
+class ThreatJobTest(unittest.TestCase):
28
+    @classmethod
29
+    def setUpClass(cls):
30
+        cls.engine = chess.engine.SimpleEngine.popen_uci("stockfish")
31
+        cls.engine.configure({"Threads": 2, "Hash": 32})
32
+
33
+    @classmethod
34
+    def tearDownClass(cls):
35
+        cls.engine.quit()
36
+
37
+    def run_job(self, fen, candidates=None):
38
+        return threat.threat_job(chess.Board(fen), candidates)(self.engine)
39
+
40
+    def test_stockfish_finds_mate_threat(self):
41
+        self.assertEqual(self.run_job(SCHOLAR), chess.Move.from_uci("h5f7"))
42
+
43
+    def test_quiet_start_has_no_threat(self):
44
+        self.assertIsNone(self.run_job(chess.STARTING_FEN))
45
+
46
+    def test_candidates_decide_what_is_seen(self):
47
+        quiet = [chess.Move.from_uci("a2a3"), chess.Move.from_uci("h2h3")]
48
+        self.assertIsNone(self.run_job(SCHOLAR, quiet))  # der „Gegner“ sieht das Matt nicht
49
+        seen = quiet + [chess.Move.from_uci("h5f7")]
50
+        self.assertEqual(self.run_job(SCHOLAR, seen), chess.Move.from_uci("h5f7"))
51
+
52
+    def test_in_check_returns_checker(self):
53
+        fen = "rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3"
54
+        self.assertEqual(self.run_job(fen), chess.Move.from_uci("h4e1"))
55
+
56
+
57
+if __name__ == "__main__":
58
+    unittest.main()