Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

chore(tools): check every course branch with Stockfish

public

chore(tools): check every course branch with Stockfish

Flags weak learner moves, opponent blunders, bad line ends and
arrows blocked by pieces; prints eval traces of every demo.
Evals cached in ~/.cache/schach.

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

added tools/kurse_pruefen.py +190 −0

@@ -0,0 +1,190 @@
1
+#!/usr/bin/env python3
2
+"""Eröffnungskurse mit Stockfish prüfen – jeden Ast, nicht nur Stichproben.
3
+
4
+Meldet:
5
+- Kurszüge der lernenden Seite, die deutlich schlechter sind als Stockfishs bester Zug,
6
+- grobe Fehler der Gegenseite (manchmal Absicht – dann sollte es im Kommentar stehen),
7
+- Linienenden, an denen die lernende Seite schlechter steht,
8
+- Pfeile, deren Weg durch eine Figur versperrt ist,
9
+- und den Bewertungsverlauf jeder „Warum?“-Vorführung zum Gegenlesen.
10
+
11
+Bewertungen werden zwischengespeichert (~/.cache/schach/kurse_pruefen.json), ein zweiter
12
+Lauf nach kleinen Änderungen ist also schnell.
13
+
14
+    python tools/kurse_pruefen.py                 # alle Kurse
15
+    python tools/kurse_pruefen.py schach/kurse/london.pgn --depth 20
16
+"""
17
+
18
+import argparse
19
+import glob
20
+import json
21
+import os
22
+import sys
23
+
24
+import chess
25
+import chess.engine
26
+import chess.pgn
27
+
28
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
29
+from schach import opening  # noqa: E402
30
+
31
+CACHE = os.path.expanduser("~/.cache/schach/kurse_pruefen.json")
32
+LEARNER_LOSS = 70  # Centipawns: so viel schlechter als der beste Zug ist bei eigenen Kurszügen verdächtig
33
+OPPONENT_LOSS = 200  # grober Fehler der Gegenseite
34
+LINE_END = -50  # Linienende: so schlecht darf es für die lernende Seite höchstens stehen
35
+MATE = 10000
36
+
37
+
38
+class Evaluator:
39
+    def __init__(self, depth, threads):
40
+        self.depth = depth
41
+        self.engine = chess.engine.SimpleEngine.popen_uci("stockfish")
42
+        self.engine.configure({"Threads": threads, "Hash": 256})
43
+        self.cache = {}
44
+        if os.path.exists(CACHE):
45
+            try:
46
+                with open(CACHE) as fh:
47
+                    self.cache = json.load(fh)
48
+            except (OSError, ValueError):
49
+                self.cache = {}
50
+
51
+    def score(self, board):
52
+        """(Centipawns aus Sicht von Weiß, bester Zug als UCI oder None)."""
53
+        if board.is_game_over():
54
+            outcome = board.outcome()
55
+            if outcome.winner is None:
56
+                return 0, None
57
+            return (MATE if outcome.winner == chess.WHITE else -MATE), None
58
+        key = f"{board.fen()}|{self.depth}"
59
+        if key not in self.cache:
60
+            info = self.engine.analyse(board, chess.engine.Limit(depth=self.depth))
61
+            cp = info["score"].white().score(mate_score=MATE)
62
+            best = info["pv"][0].uci() if info.get("pv") else None
63
+            self.cache[key] = [cp, best]
64
+        cp, best = self.cache[key]
65
+        return cp, best
66
+
67
+    def close(self):
68
+        self.engine.quit()
69
+        os.makedirs(os.path.dirname(CACHE), exist_ok=True)
70
+        with open(CACHE, "w") as fh:
71
+            json.dump(self.cache, fh)
72
+
73
+
74
+def pov(cp, color):
75
+    return cp if color == chess.WHITE else -cp
76
+
77
+
78
+def fmt(cp):
79
+    if abs(cp) >= MATE - 100:
80
+        return "Matt" if cp > 0 else "-Matt"
81
+    return f"{cp / 100:+.2f}"
82
+
83
+
84
+def label(board, move):
85
+    number = f"{board.fullmove_number}." if board.turn == chess.WHITE else f"{board.fullmove_number}…"
86
+    return f"{number}{board.san(move)}"
87
+
88
+
89
+def path_of(board, node):
90
+    moves = []
91
+    while node.parent is not None:
92
+        moves.append(node)
93
+        node = node.parent
94
+    out, b = [], node.board()
95
+    for n in reversed(moves):
96
+        out.append(label(b, n.move))
97
+        b.push(n.move)
98
+    return " ".join(out)
99
+
100
+
101
+def blocked_arrows(board, node):
102
+    """Pfeile von Läufer/Turm/Dame/Bauer, deren Weg durch eine Figur versperrt ist."""
103
+    problems = []
104
+    for arrow in node.arrows():
105
+        tail, head = arrow.tail, arrow.head
106
+        if tail == head:
107
+            continue
108
+        piece = board.piece_at(tail)
109
+        if piece is None or piece.piece_type in (chess.KNIGHT, chess.KING):
110
+            continue
111
+        between = chess.SquareSet(chess.between(tail, head))
112
+        if not between and chess.square_distance(tail, head) > 1:
113
+            continue  # keine Linie (z. B. Plan-Pfeil) – nicht prüfbar
114
+        blockers = [chess.square_name(s) for s in between if board.piece_at(s)]
115
+        if blockers:
116
+            problems.append(f"{chess.square_name(tail)}→{chess.square_name(head)} versperrt auf {', '.join(blockers)}")
117
+    return problems
118
+
119
+
120
+def check_course(path, ev):
121
+    with open(path) as fh:
122
+        game = chess.pgn.read_game(fh)
123
+    color = chess.BLACK if game.headers.get("SchachColor", "white").lower() == "black" else chess.WHITE
124
+    title = game.headers.get("Event", path)
125
+    findings, demos = [], []
126
+
127
+    def walk(node, in_demo, demo_log):
128
+        board = node.board()
129
+        for problem in blocked_arrows(board, node):
130
+            findings.append(f"Pfeil: {path_of(board, node) or 'Start'}: {problem}")
131
+        children = node.variations
132
+        if not children and not in_demo:
133
+            cp, _ = ev.score(board)
134
+            if pov(cp, color) < LINE_END:
135
+                findings.append(f"Linienende: {path_of(board, node)} → {fmt(pov(cp, color))} für die lernende Seite")
136
+        for index, child in enumerate(children):
137
+            demo = in_demo or (index > 0 and "[%warum" in child.comment)
138
+            if demo and not in_demo:
139
+                log = []
140
+                demos.append((path_of(board, node) or "Start", opening.clean_comment(child.comment)[:70], log))
141
+            else:
142
+                log = demo_log
143
+            after = child.board()
144
+            cp_after, _ = ev.score(after)
145
+            if demo:
146
+                log.append(f"{label(board, child.move)} {fmt(cp_after)}")
147
+            else:
148
+                cp_before, best = ev.score(board)
149
+                mover = board.turn
150
+                loss = pov(cp_before, mover) - pov(cp_after, mover)
151
+                best_san = board.san(chess.Move.from_uci(best)) if best else "?"
152
+                where = path_of(after, child)
153
+                if mover == color and loss > LEARNER_LOSS and child.move.uci() != best:
154
+                    findings.append(f"Kurszug: {where} verliert {loss / 100:.2f} (besser {best_san}, danach {fmt(cp_after)})")
155
+                elif mover != color and loss > OPPONENT_LOSS:
156
+                    note = opening.clean_comment(child.comment)[:60]
157
+                    findings.append(f"Gegnerfehler: {where} (−{loss / 100:.2f}; Kommentar: „{note}“)")
158
+            walk(child, demo, log)
159
+
160
+    walk(game, False, None)
161
+    return title, findings, demos
162
+
163
+
164
+def main():
165
+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
166
+    parser.add_argument("paths", nargs="*")
167
+    parser.add_argument("--depth", type=int, default=18)
168
+    parser.add_argument("--threads", type=int, default=4)
169
+    args = parser.parse_args()
170
+    paths = args.paths or sorted(glob.glob(os.path.join(opening.COURSE_DIR, "*.pgn")))
171
+    ev = Evaluator(args.depth, args.threads)
172
+    total = 0
173
+    try:
174
+        for path in paths:
175
+            title, findings, demos = check_course(path, ev)
176
+            total += len(findings)
177
+            print(f"\n=== {title} ({os.path.basename(path)}) – {len(findings)} Befund(e)")
178
+            for finding in findings:
179
+                print("  •", finding)
180
+            for where, text, log in demos:
181
+                print(f"  ▸ Vorführung nach {where}: „{text}“")
182
+                print("      " + " ".join(log))
183
+    finally:
184
+        ev.close()
185
+    print(f"\n{total} Befund(e) insgesamt.")
186
+    return 1 if total else 0
187
+
188
+
189
+if __name__ == "__main__":
190
+    sys.exit(main())