feat(hints): third hint stage explains the hint move as imagined future
public
feat(hints): third hint stage explains the hint move as imagined future Pressing H a third time shows Stockfish's main line for the hint move (also when Maia suggested it, via root_moves) in the coach bar, one comment per move. explain.py derives the reasons with simple detectors: capture, check, mate, fork, pin, rescued piece, parried threat (null move, shown as orange arrow), castling, development, centre, only move, and the material result. The line ends at mate or once the material gain is settled (at most 6 plies, 4 when quiet) and is then cut after the last eventful move, so a quiet continuation shows only the move itself. The demo bar, shared with the course demos, now reads |< < > (the present is on the left), tints the board slightly while showing the imagined future and offers a 'Spur' toggle with arrows of all moves up to the current step. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| Changeset | 45f827567c3529ac2eecc93e12a6f6f878f3f48f |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | c1ab5ff75ae7 |
| Children | e149876e2ada |
| Pushlog | by timo via ssh by timo via ssh |
modified schach/app.py +49 −3
| @@ -21,6 +21,7 @@ from .movelist import MoveList # noqa: | ||
| 21 | 21 | from .prefs import Preferences # noqa: E402 |
| 22 | 22 | from .engines import MAIA_CMD, MAIA_CWD, MAIA_PREPARE, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move # noqa: E402 |
| 23 | 23 | from .threat import null_board, threat_job # noqa: E402 |
| 24 | +from .explain import explain_job # noqa: E402 | |
| 24 | 25 | from .online import OnlineMixin # noqa: E402 |
| 25 | 26 | from .puzzles import PuzzleMixin # noqa: E402 |
| 26 | 27 | from .training import OpeningMixin, set_book_paths # noqa: E402 |
| @@ -138,6 +139,8 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 138 | 139 | self.hint_pending = False |
| 139 | 140 | self.hint_error = None |
| 140 | 141 | self.hint_prefetch_gen = None |
| 142 | + self.explain_pending = False # dritte Hinweisstufe: Stockfish rechnet die Erklärung | |
| 143 | + self.explanation = None # (gen, {"demo": Demo, "label": "Warum Sf3?"}) – fertig für diese Stellung | |
| 141 | 144 | self.threat_move = None # Bedrohung: Zug des Gegners, den er spielen würde, wäre er am Zug |
| 142 | 145 | self.threat_level = 0 # 1 = bedrohtes Feld, 2 = auch die drohende Figur (2 ohne Zug: keine Drohung) |
| 143 | 146 | self.threat_pending = False |
| @@ -530,6 +533,7 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 530 | 533 | return self.browse_ply is not None and self.browse_ply < len(self.board.move_stack) - 1 |
| 531 | 534 | |
| 532 | 535 | def _refresh(self): |
| 536 | + self.view.imagined = False # nur die Vorführung tönt das Brett (_demo_refresh) | |
| 533 | 537 | if self.mode == "setup": |
| 534 | 538 | self._setup_refresh() |
| 535 | 539 | return |
| @@ -638,8 +642,8 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 638 | 642 | hints = self.mode in ("maia", "puzzle", "opening", "duo") |
| 639 | 643 | budget = self.mode != "duo" or self._duo_can_help() or self.hint_level == 1 |
| 640 | 644 | can_hint = ( |
| 641 | - hints and budget and self._human_to_move() and self.hint_level < 2 and not self.hint_pending | |
| 642 | - and not self._browsing() | |
| 645 | + hints and budget and self._human_to_move() and not self.hint_pending and not self._browsing() | |
| 646 | + and (self.hint_level < 2 or self._can_explain()) | |
| 643 | 647 | ) |
| 644 | 648 | self.duo_btn.set_visible(self.mode == "duo") |
| 645 | 649 | self._action("duo-draw").set_enabled(self.mode == "duo" and not self._over()) |
| @@ -652,6 +656,7 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 652 | 656 | self.hint_btn.set_tooltip_text( |
| 653 | 657 | "Hinweis (H) – das Rätsel zählt dann nicht als gelöst" if self.mode == "puzzle" |
| 654 | 658 | else "Kurszug zeigen (H)" if self.mode == "opening" |
| 659 | + else "Warum ist der Zug gut? (H)" if self.hint_level >= 2 | |
| 655 | 660 | else f"Zug zeigen (H) – von {HELPERS[self._helper()][0]}" if self.hint_level == 1 |
| 656 | 661 | else f"Hinweis von {HELPERS[self._helper()][0]} (H)" |
| 657 | 662 | ) |
| @@ -850,6 +855,11 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 850 | 855 | self.hint_pending = False |
| 851 | 856 | self.hint_error = None |
| 852 | 857 | self.hint_prefetch_gen = None |
| 858 | + self.explain_pending = False | |
| 859 | + self.explanation = None | |
| 860 | + if self.demo is not None and self.mode != "opening": | |
| 861 | + self.demo = None # die gedachte Zukunft gehört zur alten Stellung | |
| 862 | + self.coach.set_reveal_child(bool(self.coach_log)) | |
| 853 | 863 | self.threat_move = None |
| 854 | 864 | self.threat_level = 0 |
| 855 | 865 | self.threat_pending = False |
| @@ -1029,7 +1039,10 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 1029 | 1039 | self.course_stats["reveals"] += 1 # zweite Hälfte des Hinweises: auch das Zielfeld |
| 1030 | 1040 | self._refresh() |
| 1031 | 1041 | return |
| 1032 | - if self.hint_level >= 2 or self.hint_pending: | |
| 1042 | + if self.hint_level >= 2: | |
| 1043 | + self._explain_hint() | |
| 1044 | + return | |
| 1045 | + if self.hint_pending: | |
| 1033 | 1046 | return |
| 1034 | 1047 | if self.mode == "puzzle": |
| 1035 | 1048 | self._puzzle_hint() |
| @@ -1051,6 +1064,39 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 1051 | 1064 | self.hint_pending = True # Vorausberechnung läuft noch; zeigt sich, sobald fertig |
| 1052 | 1065 | self._refresh() |
| 1053 | 1066 | |
| 1067 | + def _can_explain(self): | |
| 1068 | + """Dritte Stufe: Erklärung zum gezeigten Zug (Kurse haben ihre eigenen „Warum?“-Fragen).""" | |
| 1069 | + return (self.mode in ("maia", "duo", "puzzle") and self.hint_level >= 2 and self.hint_move is not None | |
| 1070 | + and not self.explain_pending and self.demo is None) | |
| 1071 | + | |
| 1072 | + def _explain_hint(self): | |
| 1073 | + """Hauptvariante zum Hinweiszug als gedachte Zukunft vorführen, mit Erklärung pro Zug.""" | |
| 1074 | + if not self._can_explain() or not self._human_to_move(): | |
| 1075 | + return | |
| 1076 | + if self.explanation is not None and self.explanation[0] == self.gen: | |
| 1077 | + self._demo_begin(self.explanation[1]) | |
| 1078 | + return | |
| 1079 | + gen, board, move = self.gen, self.board.copy(), self.hint_move | |
| 1080 | + self.explain_pending = True | |
| 1081 | + self._refresh_chrome() | |
| 1082 | + | |
| 1083 | + def on_done(demo, error): | |
| 1084 | + if gen != self.gen: | |
| 1085 | + return | |
| 1086 | + self.explain_pending = False | |
| 1087 | + if error is not None or demo is None or not demo.steps: | |
| 1088 | + self.toasts.add_toast(Adw.Toast(title=f"Keine Erklärung möglich: {error or 'keine Variante'}")) | |
| 1089 | + self._refresh_chrome() | |
| 1090 | + return | |
| 1091 | + why = {"demo": demo, "label": f"Warum {notation.move(board, move, self._notation())}?"} | |
| 1092 | + self.explanation = (gen, why) | |
| 1093 | + if self._human_to_move() and not self._browsing(): | |
| 1094 | + self._demo_begin(why) | |
| 1095 | + else: | |
| 1096 | + self._refresh_chrome() | |
| 1097 | + | |
| 1098 | + self.get_application().side_engine().submit(explain_job(board, move), on_done) | |
| 1099 | + | |
| 1054 | 1100 | def play_hint(self, *_): |
| 1055 | 1101 | """Enter: den Hinweiszug spielen, sobald Figur und Zielfeld gezeigt werden.""" |
| 1056 | 1102 | if self.hint_level >= 2 and self.hint_move is not None and not self._browsing(): |
modified schach/diagram.py +7 −1
| @@ -66,7 +66,8 @@ CHECK = (0.88, 0.11, 0.14) | ||
| 66 | 66 | SPOTLIGHT = (0.96, 0.76, 0.10) # Feld, dessen Name im Kommentar unter der Maus liegt |
| 67 | 67 | # Farben der Kurs-Pfeile ([%cal]/[%csl]), wie bei Lichess |
| 68 | 68 | SHAPE_COLORS = {"green": (0.08, 0.55, 0.20), "red": (0.80, 0.13, 0.13), |
| 69 | - "blue": (0.10, 0.35, 0.80), "yellow": (0.90, 0.60, 0.0)} | |
| 69 | + "blue": (0.10, 0.35, 0.80), "yellow": (0.90, 0.60, 0.0), | |
| 70 | + "hint": HINT, "threat": THREAT} # die beiden letzten: Spur der Vorführung | |
| 70 | 71 | BADGE = { |
| 71 | 72 | "!!": (0.10, 0.62, 0.55), |
| 72 | 73 | "!": (0.30, 0.52, 0.80), |
| @@ -155,6 +156,7 @@ class BoardPainter: | ||
| 155 | 156 | self.spotlight = None # Feld, das gerade im Text gezeigt wird (Maus über „e4“) |
| 156 | 157 | self.spotlight_from = None # bei „Ld3“: der Läufer, der dorthin ziehen kann (Pfeil) |
| 157 | 158 | self.spotlight_via = None # bei „Se5“ nach „Sf3“ im Text: Zwischenfeld, zwei Pfeile |
| 159 | + self.imagined = False # gedachte Zukunft („Warum?“-Vorführung): Brett leicht getönt | |
| 158 | 160 | self.shapes = () # Pfeile und Felder aus Kurskommentaren: ((von, nach, Farbe), …) |
| 159 | 161 | self.preview = None # Zug, der halb durchsichtig gezeigt wird (Explorer: Maus über einer Zeile) |
| 160 | 162 | self.hint_preview = None # Hinweiszug, sobald beide Felder gezeigt werden: ebenso halb durchsichtig |
| @@ -233,6 +235,10 @@ class BoardPainter: | ||
| 233 | 235 | cr.set_source_rgb(*(light_rgb if light else dark_rgb)) |
| 234 | 236 | cr.rectangle(x, y, sq, sq) |
| 235 | 237 | cr.fill() |
| 238 | + if self.imagined: | |
| 239 | + cr.set_source_rgba(*HINT, 0.12) | |
| 240 | + cr.rectangle(ox, oy, sq * 8, sq * 8) | |
| 241 | + cr.fill() | |
| 236 | 242 | |
| 237 | 243 | if self.last_move: |
| 238 | 244 | for s in (self.last_move.from_square, self.last_move.to_square): |
added schach/explain.py +237 −0
| @@ -0,0 +1,237 @@ | ||
| 1 | +"""Dritte Hinweisstufe: Warum ist der Zug gut? Die Hauptvariante als gedachte Zukunft. | |
| 2 | + | |
| 3 | +Stockfish liefert nur Bewertung und Hauptvariante, kein „Warum“. Das Warum leiten | |
| 4 | +einfache Detektoren aus der Variante ab (Schlagen, Schach, Gabel, Fesselung, gerettete | |
| 5 | +Figur, abgewehrte Drohung …). Die Texte sind auf Deutsch mit deutschen Figurenbuchstaben | |
| 6 | +geschrieben; die Coach-Leiste übersetzt sie bei Bedarf (notation.text). | |
| 7 | +""" | |
| 8 | + | |
| 9 | +import chess | |
| 10 | +import chess.engine | |
| 11 | + | |
| 12 | +from .annotate import VALUE, win_pct | |
| 13 | +from .opening import Demo | |
| 14 | +from .threat import threat_job | |
| 15 | + | |
| 16 | +EXPLAIN_LIMIT = chess.engine.Limit(depth=16) | |
| 17 | +MAX_PLIES = 6 # länger wird eine Variante für Kinder zu Rauschen | |
| 18 | +QUIET_PLIES = 4 # ohne Materialwechsel reicht ein kurzer Blick in die Zukunft | |
| 19 | +ONLY_MOVE_GAP = 15.0 # so viele Prozentpunkte Gewinnchance liegt der Zug vor dem zweitbesten | |
| 20 | + | |
| 21 | +NOMINATIVE = {chess.PAWN: "der Bauer", chess.KNIGHT: "der Springer", chess.BISHOP: "der Läufer", | |
| 22 | + chess.ROOK: "der Turm", chess.QUEEN: "die Dame", chess.KING: "der König"} | |
| 23 | +ACCUSATIVE = {chess.PAWN: "den Bauern", chess.KNIGHT: "den Springer", chess.BISHOP: "den Läufer", | |
| 24 | + chess.ROOK: "den Turm", chess.QUEEN: "die Dame", chess.KING: "den König"} | |
| 25 | +COLOR = {chess.WHITE: "Weiß", chess.BLACK: "Schwarz"} | |
| 26 | + | |
| 27 | + | |
| 28 | +def _san(board, move): | |
| 29 | + return board.san(move).translate(str.maketrans({"N": "S", "B": "L", "R": "T", "Q": "D"})) | |
| 30 | + | |
| 31 | + | |
| 32 | +def material(board, color): | |
| 33 | + return sum(VALUE[p.piece_type] * (1 if p.color == color else -1) for p in board.piece_map().values()) | |
| 34 | + | |
| 35 | + | |
| 36 | +def gain_text(gain): | |
| 37 | + """Materialgewinn in Bauerneinheiten, kindgerecht.""" | |
| 38 | + if gain >= 8: | |
| 39 | + return "die Dame" | |
| 40 | + if gain >= 5: | |
| 41 | + return "einen Turm" | |
| 42 | + if gain >= 3: | |
| 43 | + return "eine Figur" | |
| 44 | + if gain == 2: | |
| 45 | + return "zwei Bauern" | |
| 46 | + return "einen Bauern" | |
| 47 | + | |
| 48 | + | |
| 49 | +def trim(board, pv): | |
| 50 | + """Hauptvariante kürzen: bis Matt, bis der Gewinn eingefahren ist, höchstens MAX_PLIES.""" | |
| 51 | + hero = board.turn | |
| 52 | + start = material(board, hero) | |
| 53 | + probe = board.copy(stack=False) | |
| 54 | + kept = [] | |
| 55 | + for i, move in enumerate(pv[:MAX_PLIES]): | |
| 56 | + if move not in probe.legal_moves: | |
| 57 | + break | |
| 58 | + probe.push(move) | |
| 59 | + kept.append(move) | |
| 60 | + if probe.is_checkmate(): | |
| 61 | + break | |
| 62 | + # nach einer Antwort des Gegners: Material hat sich verändert, und es wird nicht weitergeschlagen | |
| 63 | + if i % 2 == 1 and len(pv) > i + 1: | |
| 64 | + following = pv[i + 1] | |
| 65 | + settled = material(probe, hero) != start and not probe.is_capture(following) | |
| 66 | + if settled or (material(probe, hero) == start and i + 1 >= QUIET_PLIES): | |
| 67 | + break | |
| 68 | + return kept | |
| 69 | + | |
| 70 | + | |
| 71 | +def _valuable_targets(after, square): | |
| 72 | + """Gegnerische Figuren, die die Figur auf ``square`` angreift und die etwas einbringen würden.""" | |
| 73 | + piece = after.piece_at(square) | |
| 74 | + targets = [] | |
| 75 | + for target in after.attacks(square): | |
| 76 | + victim = after.piece_at(target) | |
| 77 | + if victim is None or victim.color == piece.color: | |
| 78 | + continue | |
| 79 | + if victim.piece_type == chess.KING: | |
| 80 | + targets.append(target) | |
| 81 | + elif VALUE[victim.piece_type] > VALUE[piece.piece_type] or not after.attackers(victim.color, target): | |
| 82 | + targets.append(target) | |
| 83 | + return targets | |
| 84 | + | |
| 85 | + | |
| 86 | +def _hanging(board, square): | |
| 87 | + """Steht die Figur auf ``square`` in Gefahr (angegriffen und ungedeckt oder von Billigerem)?""" | |
| 88 | + piece = board.piece_at(square) | |
| 89 | + if piece is None or piece.piece_type == chess.KING: | |
| 90 | + return False | |
| 91 | + attackers = board.attackers(not piece.color, square) | |
| 92 | + if not attackers: | |
| 93 | + return False | |
| 94 | + if not board.attackers(piece.color, square): | |
| 95 | + return True | |
| 96 | + return min(VALUE[board.piece_type_at(a)] for a in attackers) < VALUE[piece.piece_type] | |
| 97 | + | |
| 98 | + | |
| 99 | +def describe(before, move, hero): | |
| 100 | + """Sätze und Kreise ((feld, feld, Farbe), …) zu einem Zug der Variante.""" | |
| 101 | + mover = before.turn | |
| 102 | + piece = before.piece_at(move.from_square) | |
| 103 | + after = before.copy(stack=False) | |
| 104 | + after.push(move) | |
| 105 | + you = mover == hero | |
| 106 | + who = "Du" if you else COLOR[mover] | |
| 107 | + sentences, shapes = [], [] | |
| 108 | + | |
| 109 | + if after.is_checkmate(): | |
| 110 | + return ["Schachmatt!" if you else f"Schachmatt – {COLOR[mover]} gewinnt."], shapes | |
| 111 | + | |
| 112 | + if before.is_castling(move): | |
| 113 | + sentences.append("Rochade: Der König steht sicher, und der Turm kommt ins Spiel." if you | |
| 114 | + else f"{COLOR[mover]} bringt mit der Rochade den König in Sicherheit.") | |
| 115 | + elif before.is_capture(move): | |
| 116 | + victim = before.piece_at(move.to_square) | |
| 117 | + victim_type = victim.piece_type if victim else chess.PAWN # en passant | |
| 118 | + verb = "schlägst" if you else "schlägt" | |
| 119 | + sentences.append(f"{who} {verb} {ACCUSATIVE[victim_type]} auf {chess.square_name(move.to_square)}.") | |
| 120 | + | |
| 121 | + if after.is_check(): | |
| 122 | + sentences.append("Schach!") | |
| 123 | + | |
| 124 | + targets = [t for t in _valuable_targets(after, move.to_square)] | |
| 125 | + if len(targets) >= 2: | |
| 126 | + names = [ACCUSATIVE[after.piece_type_at(t)] for t in targets[:2]] | |
| 127 | + name = NOMINATIVE[after.piece_type_at(move.to_square)] | |
| 128 | + sentences.append(f"Gabel: {name[0].upper() + name[1:]} greift {names[0]} und {names[1]} gleichzeitig an.") | |
| 129 | + shapes += [(t, t, "red") for t in targets[:2]] | |
| 130 | + | |
| 131 | + for square in chess.SQUARES: | |
| 132 | + victim = after.piece_at(square) | |
| 133 | + if victim is None or victim.color == mover or victim.piece_type == chess.KING: | |
| 134 | + continue | |
| 135 | + if after.is_pinned(victim.color, square) and not before.is_pinned(victim.color, square): | |
| 136 | + if move.to_square in after.pin(victim.color, square): | |
| 137 | + owner = "der König" if victim.color != hero else "dein König" | |
| 138 | + sentences.append(f"Fesselung: {NOMINATIVE[victim.piece_type][0].upper()}" | |
| 139 | + f"{NOMINATIVE[victim.piece_type][1:]} auf {chess.square_name(square)} " | |
| 140 | + f"darf nicht ziehen, sonst stünde {owner} im Schach.") | |
| 141 | + shapes.append((square, square, "red")) | |
| 142 | + break | |
| 143 | + | |
| 144 | + if you and piece and _hanging(before, move.from_square) and not _hanging(after, move.to_square) \ | |
| 145 | + and not before.is_capture(move): | |
| 146 | + sentences.append(f"{NOMINATIVE[piece.piece_type][0].upper()}{NOMINATIVE[piece.piece_type][1:]} " | |
| 147 | + "stand in Gefahr und ist jetzt in Sicherheit.") | |
| 148 | + | |
| 149 | + if you and not sentences and piece and piece.piece_type == chess.PAWN \ | |
| 150 | + and move.to_square in (chess.D4, chess.E4, chess.D5, chess.E5): | |
| 151 | + sentences.append("Der Bauer besetzt das Zentrum.") | |
| 152 | + if you and not sentences and piece and piece.piece_type in (chess.KNIGHT, chess.BISHOP) \ | |
| 153 | + and before.fullmove_number <= 12 and chess.square_rank(move.from_square) in (0, 7): | |
| 154 | + sentences.append("Du entwickelst eine Figur.") | |
| 155 | + return sentences, shapes | |
| 156 | + | |
| 157 | + | |
| 158 | +def eventful(before, move): | |
| 159 | + """Passiert mit dem Zug etwas, das zur Erklärung gehört? Schlagen, Schach, Gabel, Fesselung.""" | |
| 160 | + if before.is_capture(move) or before.gives_check(move): | |
| 161 | + return True | |
| 162 | + return bool(describe(before, move, before.turn)[1]) # Kreise gibt es nur bei Gabel und Fesselung | |
| 163 | + | |
| 164 | + | |
| 165 | +def relevant(board, moves): | |
| 166 | + """Variante nur so weit, wie noch etwas passiert; eine ruhige Variante ist nur der Zug selbst.""" | |
| 167 | + probe = board.copy(stack=False) | |
| 168 | + last = 0 | |
| 169 | + for index, move in enumerate(moves): | |
| 170 | + if index and eventful(probe, move): | |
| 171 | + last = index | |
| 172 | + probe.push(move) | |
| 173 | + return moves[: last + 1] | |
| 174 | + | |
| 175 | + | |
| 176 | +def build_steps(board, pv, threat=None, only_move=False, mate=False): | |
| 177 | + """Schritte für die Vorführung: [(Zug, Kommentar, Kreise)].""" | |
| 178 | + hero = board.turn | |
| 179 | + full = trim(board, pv) | |
| 180 | + moves = relevant(board, full) | |
| 181 | + if not moves: | |
| 182 | + return [] | |
| 183 | + start = material(board, hero) | |
| 184 | + steps = [] | |
| 185 | + probe = board.copy(stack=False) | |
| 186 | + for index, move in enumerate(moves): | |
| 187 | + sentences, shapes = describe(probe, move, hero) | |
| 188 | + if index == 0: | |
| 189 | + if threat is not None and (len(full) < 2 or full[1] != threat): | |
| 190 | + sentences.append(f"Das wehrt die Drohung {_san(board_null(board), threat)} ab.") | |
| 191 | + shapes.append((threat.from_square, threat.to_square, "threat")) # was gedroht hätte | |
| 192 | + if only_move: | |
| 193 | + sentences.append("Alle anderen Züge sind deutlich schlechter.") | |
| 194 | + if not sentences: | |
| 195 | + sentences.append("Stockfish hält das für den besten Zug.") | |
| 196 | + elif index % 2 == 1 and not sentences: | |
| 197 | + sentences.append(f"Die beste Antwort von {COLOR[probe.turn]}.") | |
| 198 | + probe.push(move) | |
| 199 | + if index == len(moves) - 1 and not probe.is_checkmate(): | |
| 200 | + gain = material(probe, hero) - start | |
| 201 | + if mate: | |
| 202 | + sentences.append("Am Ende steht ein Matt.") | |
| 203 | + elif gain > 0: | |
| 204 | + sentences.append(f"Ergebnis: Du gewinnst {gain_text(gain)}.") | |
| 205 | + elif gain < 0: | |
| 206 | + sentences.append(f"Ergebnis: Du gibst {gain_text(-gain)} her, bekommst aber eine bessere Stellung.") | |
| 207 | + steps.append((move, " ".join(sentences), tuple(shapes))) | |
| 208 | + return steps | |
| 209 | + | |
| 210 | + | |
| 211 | +def board_null(board): | |
| 212 | + probe = board.copy(stack=False) | |
| 213 | + probe.push(chess.Move.null()) | |
| 214 | + return probe | |
| 215 | + | |
| 216 | + | |
| 217 | +def explain_job(board, move, limit=EXPLAIN_LIMIT): | |
| 218 | + """Job für Stockfish: Demo mit der Hauptvariante zu ``move`` (auch wenn Maia ihn vorschlug).""" | |
| 219 | + board = board.copy() | |
| 220 | + | |
| 221 | + def job(engine): | |
| 222 | + info = engine.analyse(board, limit, root_moves=[move]) | |
| 223 | + pv = info.get("pv") or [move] | |
| 224 | + if pv[0] != move: | |
| 225 | + pv = [move] | |
| 226 | + score = info["score"].pov(board.turn) | |
| 227 | + mate = score.is_mate() and score.mate() > 0 | |
| 228 | + played = win_pct(info["score"], board.turn) | |
| 229 | + others = [win_pct(i["score"], board.turn) | |
| 230 | + for i in engine.analyse(board, limit, multipv=3) | |
| 231 | + if i.get("pv") and i["pv"][0] != move and "score" in i] | |
| 232 | + only_move = bool(others) and played - max(others) >= ONLY_MOVE_GAP | |
| 233 | + threat = None if board.is_check() else threat_job(board, None, played)(engine) | |
| 234 | + steps = build_steps(board, pv, threat, only_move, mate) | |
| 235 | + return Demo(start_fen=board.fen(), steps=steps) | |
| 236 | + | |
| 237 | + return job | |
modified schach/training.py +32 −3
| @@ -185,6 +185,11 @@ def square_at(label, x, y): | ||
| 185 | 185 | return next((tuple(hit[2:]) for hit in squares_in(text) if hit[0] <= char < hit[1]), None) |
| 186 | 186 | |
| 187 | 187 | |
| 188 | +def demo_side(demo): | |
| 189 | + """Wer die Vorführung beginnt – dessen Züge sind blau, die Antworten orange.""" | |
| 190 | + return chess.Board(demo.start_fen).turn | |
| 191 | + | |
| 192 | + | |
| 188 | 193 | class OpeningMixin: |
| 189 | 194 | def _opening_init(self): |
| 190 | 195 | self.course = None |
| @@ -231,6 +236,11 @@ class OpeningMixin: | ||
| 231 | 236 | self.add_action(action) |
| 232 | 237 | # Blättern durch die letzten Rückmeldungen; das Brett zeigt die Stellung dazu |
| 233 | 238 | self.coach_nav = Gtk.Box(spacing=2, valign=Gtk.Align.CENTER, margin_end=6) |
| 239 | + # Vorführung: die Gegenwart liegt links (|<), die gedachte Zukunft rechts davon | |
| 240 | + self.coach_first = Gtk.Button(icon_name="go-first-symbolic", tooltip_text="Zurück zur Partie (Esc)", | |
| 241 | + css_classes=["flat"], visible=False) | |
| 242 | + self.coach_first.connect("clicked", lambda *_: self._demo_end()) | |
| 243 | + self.coach_nav.append(self.coach_first) | |
| 234 | 244 | self.coach_prev = Gtk.Button(icon_name="go-previous-symbolic", tooltip_text="Vorherige Rückmeldung", |
| 235 | 245 | css_classes=["flat"]) |
| 236 | 246 | self.coach_next = Gtk.Button(icon_name="go-next-symbolic", tooltip_text="Nächste Rückmeldung", |
| @@ -246,6 +256,10 @@ class OpeningMixin: | ||
| 246 | 256 | card.append(Gtk.Image(icon_name="dialog-information-symbolic", margin_start=14, valign=Gtk.Align.CENTER)) |
| 247 | 257 | card.append(self.coach_label) |
| 248 | 258 | card.append(self.coach_nav) |
| 259 | + self.coach_trace = Gtk.CheckButton(label="Spur", valign=Gtk.Align.CENTER, visible=False, margin_end=10, | |
| 260 | + tooltip_text="Alle Züge der Vorführung bis hierher als Pfeile") | |
| 261 | + self.coach_trace.connect("toggled", lambda *_: self.demo is not None and self._refresh()) | |
| 262 | + card.append(self.coach_trace) | |
| 249 | 263 | card.append(self.coach_why) |
| 250 | 264 | card.append(self.coach_why_more) |
| 251 | 265 | card.append(self.coach_button) |
| @@ -300,6 +314,9 @@ class OpeningMixin: | ||
| 300 | 314 | self.coach_last.set_sensitive(index < last) |
| 301 | 315 | self.coach_button.set_visible(self.final_text is not None and index == last) |
| 302 | 316 | self.coach_last.set_tooltip_text("Zum aktuellen Zug") |
| 317 | + self.coach_last.set_visible(True) | |
| 318 | + self.coach_first.set_visible(False) | |
| 319 | + self.coach_trace.set_visible(False) | |
| 303 | 320 | self._coach_why_show(self.coach_log[index].get("demos", ())) |
| 304 | 321 | self.coach.set_reveal_child(True) |
| 305 | 322 | |
| @@ -359,7 +376,10 @@ class OpeningMixin: | ||
| 359 | 376 | demos = self.coach_log[index].get("demos", ()) if self.coach_log else () |
| 360 | 377 | if not 0 <= number < len(demos): |
| 361 | 378 | return |
| 362 | - why = demos[number] | |
| 379 | + self._demo_begin(demos[number]) | |
| 380 | + | |
| 381 | + def _demo_begin(self, why): | |
| 382 | + """Vorführung starten: {"demo": Demo, "label": Frage}. Der erste Zug wird gleich gezeigt.""" | |
| 363 | 383 | self.demo = dict(why, index=0) |
| 364 | 384 | demo = why["demo"] |
| 365 | 385 | self.view.animate_move(chess.Board(demo.start_fen), demo.steps[0][0]) |
| @@ -398,6 +418,14 @@ class OpeningMixin: | ||
| 398 | 418 | v.hint_from = v.hint_to = v.threat_from = v.threat_to = None |
| 399 | 419 | v.hint_preview = v.threat_preview = None |
| 400 | 420 | v.shapes = demo.steps[index][2] |
| 421 | + if self.coach_trace.get_active(): | |
| 422 | + trace = chess.Board(demo.start_fen) | |
| 423 | + arrows = [] | |
| 424 | + for move, _c, _s in demo.steps[: index + 1]: | |
| 425 | + arrows.append((move.from_square, move.to_square, "hint" if trace.turn == demo_side(demo) else "threat")) | |
| 426 | + trace.push(move) | |
| 427 | + v.shapes = tuple(arrows) + tuple(v.shapes) | |
| 428 | + v.imagined = True | |
| 401 | 429 | v.queue_draw() |
| 402 | 430 | self._refresh_chrome() |
| 403 | 431 | |
| @@ -413,8 +441,9 @@ class OpeningMixin: | ||
| 413 | 441 | self.coach_nav.set_visible(True) |
| 414 | 442 | self.coach_prev.set_sensitive(index > 0) |
| 415 | 443 | self.coach_next.set_sensitive(index < len(demo.steps) - 1) |
| 416 | - self.coach_last.set_sensitive(True) | |
| 417 | - self.coach_last.set_tooltip_text("Zurück zur Partie") | |
| 444 | + self.coach_last.set_visible(False) | |
| 445 | + self.coach_first.set_visible(True) | |
| 446 | + self.coach_trace.set_visible(True) | |
| 418 | 447 | self._coach_why_show(()) |
| 419 | 448 | self.coach_button.set_visible(False) |
| 420 | 449 | self.coach.set_reveal_child(True) |
added tests/test_explain.py +100 −0
| @@ -0,0 +1,100 @@ | ||
| 1 | +import shutil | |
| 2 | +import unittest | |
| 3 | + | |
| 4 | +import chess | |
| 5 | +import chess.engine | |
| 6 | + | |
| 7 | +from schach import explain | |
| 8 | + | |
| 9 | + | |
| 10 | +def m(uci): | |
| 11 | + return chess.Move.from_uci(uci) | |
| 12 | + | |
| 13 | + | |
| 14 | +class DescribeTest(unittest.TestCase): | |
| 15 | + def test_knight_fork_on_king_and_rook(self): | |
| 16 | + board = chess.Board("r3k3/8/8/8/8/8/3N4/4K3 w - - 0 1") | |
| 17 | + sentences, shapes = explain.describe(board, m("d2c4"), chess.WHITE) | |
| 18 | + self.assertFalse(any("Gabel" in s for s in sentences)) # c4 greift nichts an | |
| 19 | + board = chess.Board("r3k3/8/8/3N4/8/8/8/4K3 w - - 0 1") | |
| 20 | + sentences, shapes = explain.describe(board, m("d5c7"), chess.WHITE) | |
| 21 | + self.assertTrue(any(s.startswith("Gabel: Der Springer") for s in sentences), sentences) | |
| 22 | + self.assertIn("Schach!", sentences) | |
| 23 | + self.assertEqual({s[0] for s in shapes}, {chess.E8, chess.A8}) | |
| 24 | + | |
| 25 | + def test_capture_names_victim(self): | |
| 26 | + board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1") | |
| 27 | + sentences, _ = explain.describe(board, m("c3d5"), chess.WHITE) | |
| 28 | + self.assertEqual(sentences[0], "Du schlägst die Dame auf d5.") | |
| 29 | + | |
| 30 | + def test_opponent_capture_uses_color(self): | |
| 31 | + board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 b - - 0 1") | |
| 32 | + sentences, _ = explain.describe(board, m("d5c3"), chess.WHITE) | |
| 33 | + self.assertEqual(sentences[0], "Schwarz schlägt den Springer auf c3.") | |
| 34 | + | |
| 35 | + def test_pin_against_king(self): | |
| 36 | + board = chess.Board("4k3/8/2n5/8/8/8/8/4KB2 w - - 0 1") | |
| 37 | + sentences, shapes = explain.describe(board, m("f1b5"), chess.WHITE) | |
| 38 | + self.assertTrue(any(s.startswith("Fesselung: Der Springer auf c6") for s in sentences), sentences) | |
| 39 | + self.assertIn((chess.C6, chess.C6, "red"), shapes) | |
| 40 | + | |
| 41 | + def test_mate(self): | |
| 42 | + board = chess.Board("6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1") | |
| 43 | + sentences, _ = explain.describe(board, m("a1a8"), chess.WHITE) | |
| 44 | + self.assertEqual(sentences, ["Schachmatt!"]) | |
| 45 | + | |
| 46 | + | |
| 47 | +class TrimTest(unittest.TestCase): | |
| 48 | + def test_stops_after_exchange_settles(self): | |
| 49 | + # Sxd5, danach ruhige Züge: nach der Antwort ist der Gewinn eingefahren | |
| 50 | + board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1") | |
| 51 | + pv = [m("c3d5"), m("e8d7"), m("d5f4"), m("d7d6"), m("e1e2"), m("d6d5")] | |
| 52 | + self.assertEqual(explain.trim(board, pv), pv[:2]) | |
| 53 | + | |
| 54 | + def test_quiet_line_is_short(self): | |
| 55 | + board = chess.Board() | |
| 56 | + pv = [m(u) for u in ("e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6", "b5a4")] | |
| 57 | + self.assertEqual(len(explain.trim(board, pv)), explain.QUIET_PLIES) | |
| 58 | + | |
| 59 | + def test_mate_ends_line(self): | |
| 60 | + board = chess.Board("6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1") | |
| 61 | + self.assertEqual(explain.trim(board, [m("a1a8"), m("g8h8")]), [m("a1a8")]) | |
| 62 | + | |
| 63 | + | |
| 64 | +class BuildStepsTest(unittest.TestCase): | |
| 65 | + def test_parried_threat_and_result(self): | |
| 66 | + board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1") | |
| 67 | + steps = explain.build_steps(board, [m("c3d5"), m("e8d7")]) | |
| 68 | + self.assertEqual(len(steps), 1) # Kd7 ist ruhig: nur Sxd5 mit Ergebnis | |
| 69 | + self.assertIn("Ergebnis: Du gewinnst die Dame.", steps[-1][1]) | |
| 70 | + | |
| 71 | + def test_threat_mentioned_when_not_replayed(self): | |
| 72 | + board = chess.Board("r1bqkbnr/pppp1ppp/2n5/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 3 3") | |
| 73 | + steps = explain.build_steps(board, [m("g7g6"), m("h5f3")], threat=m("h5f7")) | |
| 74 | + self.assertIn("Das wehrt die Drohung Dxf7# ab.", steps[0][1]) | |
| 75 | + self.assertIn((chess.H5, chess.F7, "threat"), steps[0][2]) | |
| 76 | + | |
| 77 | + def test_quiet_continuation_is_dropped(self): | |
| 78 | + # Lb3 weicht dem Bauern aus; danach passiert nichts mehr, was zum Zug gehört | |
| 79 | + board = chess.Board("rn1qkb1r/5ppp/2pp1n2/1p2p3/2B1P1b1/3P1N2/PPP2PPP/RNBQR1K1 w kq - 0 7") | |
| 80 | + pv = [m("c4b3"), m("a7a6"), m("h2h3"), m("g4h5")] | |
| 81 | + steps = explain.build_steps(board, pv, threat=m("b5c4")) | |
| 82 | + self.assertEqual([s[0] for s in steps], [m("c4b3")]) | |
| 83 | + self.assertIn("stand in Gefahr", steps[0][1]) | |
| 84 | + | |
| 85 | + | |
| 86 | +@unittest.skipUnless(shutil.which("stockfish"), "stockfish nicht installiert") | |
| 87 | +class ExplainJobTest(unittest.TestCase): | |
| 88 | + def test_job_explains_given_move(self): | |
| 89 | + board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1") | |
| 90 | + engine = chess.engine.SimpleEngine.popen_uci("stockfish") | |
| 91 | + try: | |
| 92 | + demo = explain.explain_job(board, m("c3d5"), chess.engine.Limit(depth=10))(engine) | |
| 93 | + finally: | |
| 94 | + engine.quit() | |
| 95 | + self.assertEqual(demo.steps[0][0], m("c3d5")) | |
| 96 | + self.assertEqual(demo.start_fen, board.fen()) | |
| 97 | + | |
| 98 | + | |
| 99 | +if __name__ == "__main__": | |
| 100 | + unittest.main() | |