Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

test(zustand): random test covers courses and local puzzles, reports callback exceptions

public

test(zustand): random test covers courses and local puzzles, reports callback exceptions

New actions: start a course and play its main moves, start a puzzle from
training.sqlite (one is created per run in the empty data directory, never
from Lichess) and play its solution. Exceptions raised in GTK callbacks are
findings too, with the path, the call stack and the board shown.

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

modified tools/zustand_zufall.py +77 −2

@@ -10,11 +10,17 @@ Jeder Verstoß gegen schach/zustand.py wird mit den Schritten davor ausgegeben; mit demselben
1010
 ``--seed`` lässt sich der Lauf wiederholen (bis auf die Rechenzeit der Engines). Ton wird nur
1111
 abgespielt (Wiedergabe), nie aufgenommen: Das Mikrofon bleibt aus.
1212
 
13
+Kurse und die Wiederholung von Rätseln brauchen das Paket fsrs; am einfachsten mit dem Python aus
14
+dem venv von schach.sh starten (``~/.local/share/schach/venv/bin/python``). Rätsel kommen nur aus
15
+dem lokalen training.sqlite (im eigenen, leeren Verzeichnis: vor jedem Rätsel wird eines angelegt),
16
+nie von Lichess. Ausnahmen in GTK-Rückrufen (Zeichnen, Engine-Antworten) zählen wie Verstöße.
17
+
1318
 Jeder echte Fund bekommt einen Regressionstest in tests/test_zustand_regression.py, der den Weg
1419
 ohne Zufall und ohne Engines nachspielt (siehe dort); erst danach wird der Fehler behoben.
1520
 """
1621
 
1722
 import argparse
23
+import datetime
1824
 import os
1925
 import random
2026
 import sys
@@ -38,10 +44,33 @@ gi.require_version("Adw", "1")
3844
 gi.require_version("Gdk", "4.0")
3945
 from gi.repository import Gdk, Gio, GLib  # noqa: E402
4046
 
41
-from schach import app as schach_app, recording, savegames, zustand  # noqa: E402
47
+from schach import app as schach_app, opening, recording, savegames, training, zustand  # noqa: E402
4248
 
4349
 STEP_MS = 400  # Zeit zwischen zwei Schritten: Engines und Ton laufen dazwischen weiter
4450
 
51
+# Rätsel für training.sqlite: (FEN vor dem Gegnerzug, Gegnerzug, Lösung in UCI)
52
+PUZZLES = [
53
+    (chess.Board().fen(), "e2e4", ["e7e5", "g1f3", "b8c6"]),
54
+    ("r1bqkbnr/pppp1ppp/2n5/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R b KQkq - 3 3", "f8c5", ["c2c3"]),
55
+    ("rnbqkbnr/ppp2ppp/8/3pp3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 0 3", "e4d5", ["d8d5", "b1c3", "d5a5"]),
56
+]
57
+
58
+
59
+def progress():
60
+    """training.progress() oder None (ohne fsrs: keine Kurse, keine lokalen Rätsel)."""
61
+    try:
62
+        return training.progress()
63
+    except RuntimeError:
64
+        return None
65
+
66
+
67
+def board_info(win):
68
+    """Was das Brett gerade zeigt, für den Bericht."""
69
+    board = getattr(getattr(win, "view", None), "board", None)
70
+    if board is None:
71
+        return "Brett: –"
72
+    return f"Brett: {board.root().fen()} + {' '.join(m.uci() for m in board.move_stack)}"
73
+
4574
 
4675
 def review_file(folder):
4776
     """Nachbesprechung einer laufenden Partie (Weiß am Zug), 20 s Ton, Zeitleiste über alle Züge."""
@@ -70,6 +99,10 @@ def review_file(folder):
7099
 class Fuzzer:
71100
     def __init__(self, app, rng, steps, review):
72101
         self.app, self.rng, self.left, self.review = app, rng, steps, review
102
+        self.progress = progress()
103
+        self.courses = opening.load_courses() if self.progress is not None else []
104
+        self.puzzle_count = 0
105
+        self.current = None  # Fenster des letzten Schritts (für Ausnahmen in Rückrufen)
73106
         self.trail = []  # (Fenster-Nr., Schritt)
74107
         self.found = []  # (Schritt-Nr., Fenster-Nr., Verstöße, Weg dorthin)
75108
         self.seen = set()
@@ -118,6 +151,31 @@ class Fuzzer:
118151
             win.new_game(self.rng.choice([chess.WHITE, chess.BLACK]),
119152
                          self.rng.choice(["Ohne Uhr", "5 Minuten", "10 + 5"]))
120153
 
154
+        def puzzle():
155
+            """Ein Rätsel aus training.sqlite: vorher eines anlegen, das seit gestern fällig ist."""
156
+            fen, last, solution = self.rng.choice(PUZZLES)
157
+            self.puzzle_count += 1
158
+            info = {"id": f"zufall-{self.puzzle_count}", "fen": fen, "last": last, "solution": solution,
159
+                    "rating": 1500, "themes": []}
160
+            self.progress.save_puzzle(info, now=datetime.datetime.now() - datetime.timedelta(days=30))
161
+            a("win.puzzle", None)
162
+
163
+        def solution_move():
164
+            p = getattr(win, "puzzle", None)
165
+            if win.mode == "puzzle" and p and not p["done"] and win.board.turn == win.human \
166
+                    and p["index"] < len(p["solution"]):
167
+                move = p["solution"][p["index"]]
168
+                win._on_board_move(move.from_square, move.to_square)
169
+
170
+        def course():
171
+            win.start_opening(self.rng.choice(self.courses))
172
+
173
+        def course_move():
174
+            if win.mode == "opening" and win.course is not None and win.board.turn == win.human:
175
+                options = win.course.options(win.board)
176
+                if options:
177
+                    win._on_board_move(options[0].move.from_square, options[0].move.to_square)
178
+
121179
         steps = [
122180
             (8, "H", lambda: a("win.hint", None)),
123181
             (3, "B", lambda: a("win.threat", None)),
@@ -139,6 +197,10 @@ class Fuzzer:
139197
         ]
140198
         if self.review:
141199
             steps.append((2, "Nachbesprechung öffnen", lambda: win.open_review(self.review)))
200
+        if self.progress is not None:
201
+            steps += [(1, "Rätsel", puzzle), (4, "Lösungszug", solution_move)]
202
+        if self.courses:
203
+            steps += [(1, "Kurs", course), (6, "Kurszug", course_move)]
142204
         return steps
143205
 
144206
     def step(self):
@@ -155,10 +217,13 @@ class Fuzzer:
155217
         choices = self.actions(win)
156218
         _, name, run = self.rng.choices(choices, weights=[c[0] for c in choices])[0]
157219
         self.trail.append((self.number(win), name))
220
+        self.current = win
158221
         try:
159222
             run()
160223
         except Exception as error:  # noqa: BLE001 – auch Abstürze gehören in den Bericht
161
-            self.note(win, [f"Ausnahme bei {name}: {type(error).__name__}: {error}"])
224
+            frames = [f for f in traceback.extract_tb(error.__traceback__) if "/schach/" in f.filename]
225
+            self.note(win, [f"Ausnahme bei {name}: {type(error).__name__}: {error}"],
226
+                      [f"{os.path.basename(f.filename)}:{f.lineno} {f.name}" for f in frames] + [board_info(win)])
162227
         for w in self.windows():
163228
             self.note(w, zustand.violations(w))
164229
         return True
@@ -192,6 +257,16 @@ def main():
192257
                     fuzzer.note(w, found, [f"{os.path.basename(f.filename)}:{f.lineno} {f.name}" for f in frames])
193258
                 return found
194259
             zustand.check = check
260
+            hook = sys.excepthook
261
+
262
+            def excepthook(kind, error, tb):  # Ausnahmen in GTK-Rückrufen: mit Weg und Brett
263
+                frames = [f for f in traceback.extract_tb(tb) if "/schach/" in f.filename]
264
+                where = [f"{os.path.basename(f.filename)}:{f.lineno} {f.name}" for f in frames]
265
+                win = fuzzer.current or win_first
266
+                fuzzer.note(win, [f"Ausnahme: {kind.__name__}: {error}"], where + [board_info(win)])
267
+                hook(kind, error, tb)
268
+            win_first = win
269
+            sys.excepthook = excepthook
195270
             GLib.timeout_add(3000, lambda: GLib.timeout_add(STEP_MS, fuzzer.step) and False)
196271
 
197272
     App().run([])