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