feat(training): learn from own mistakes after games vs Maia
public
feat(training): learn from own mistakes after games vs Maia On first showing the game end, the worst own ? and ?? (max 3) become cards, silently in the background. Stockfish rechecks the position before; any move within 2 win-% of the best counts, like Lichess' 0.04. Cards appear under puzzles with the opponent's move replayed; repeating the game move is a blunder. New preference, on by default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| Changeset | 1667fbeca365bd5aad660cd64a34ff0398719dc2 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | 82039a0c1547 |
| Children | b23efe6396fa |
| Pushlog | by timo via ssh by timo via ssh |
modified ROADMAP.md +1 −1
| @@ -635,7 +635,7 @@ behält Reihenfolge und offene Fragen. | ||
| 635 | 635 | | --- | --- | --- | |
| 636 | 636 | | [`roadmap/analysebrett.md`](roadmap/analysebrett.md) | Analysebrett mit Variantenbaum, „Warum?“ und „Warum nicht?“ | Stufen 1–4 umgesetzt | |
| 637 | 637 | | [`roadmap/nachbesprechung.md`](roadmap/nachbesprechung.md) | Pfeile zeichnen, Zugliste als Baum, Schlussbild und Nachspielen, Partie vertont durchgehen (Aufnahme, Wiedergabe) | Stufen 1–2a umgesetzt | |
| 638 | -| [`roadmap/training.md`](roadmap/training.md) | Rätsel aus eigenen Partien, „Aus Fehlern lernen“, Wiederholung mit FSRS und SQLite | Schritte 1 bis 3 umgesetzt, zurückgenommene Züge im PGN | | |
| 638 | +| [`roadmap/training.md`](roadmap/training.md) | Rätsel aus eigenen Partien, „Aus Fehlern lernen“, Wiederholung mit FSRS und SQLite | Schritte 1 bis 3 und 5 umgesetzt, zurückgenommene Züge im PGN | | |
| 639 | 639 | |
| 640 | 640 | ## Reihenfolge |
| 641 | 641 | |
modified roadmap/training.md +15 −1
| @@ -237,7 +237,21 @@ Erklärung, was passiert ist, und Art B bekommt später genau diese Fehler als Rohstoff. | ||
| 237 | 237 | 4. Art A: Suche nach der Partie gegen Maia, mit Einzügern; ohne Rückfrage als Karte. |
| 238 | 238 | Einstellung „Partien nach Rätseln absuchen“ (an). |
| 239 | 239 | 5. Art B: „Aus Fehlern lernen“ nach Lichess-Vorbild, schwere Fehler als Karte. |
| 240 | - Einstellung „Partien nach Lernmöglichkeiten absuchen“ (an). | |
| 240 | + Einstellung „Partien nach Lernmöglichkeiten absuchen“ (an). **Umgesetzt** (24.11.2026, | |
| 241 | + `schach/mistakes.py`, Kartenart `own_mistake`): | |
| 242 | + - Beim ersten Anzeigen des Partieendes einer eigenen Partie gegen Maia. Geladene oder | |
| 243 | + eingefügte Partien und Partien zu zweit werden nicht abgesucht. | |
| 244 | + - Die schwersten eigenen `??` und `?`, höchstens 3. Stockfish rechnet die Stellung davor | |
| 245 | + mit 8 Kandidaten nach (Tiefe 16, höchstens 3 s). Richtig ist jeder Zug bis | |
| 246 | + 2 Prozentpunkte Gewinnchance hinter dem besten (Lichess: 0,04 auf −1 … +1). | |
| 247 | + - Ist der Partiezug tiefer gerechnet doch gut genug, entsteht keine Karte. Dieselbe | |
| 248 | + Stellung entsteht nur einmal. | |
| 249 | + - Die Karte ist sofort fällig und kommt unter „Rätsel“ zusammen mit den aufgehobenen | |
| 250 | + Lichess-Rätseln („Aus deiner Partie · Weiß am Zug“). Der Zug des Gegners davor wird | |
| 251 | + vorgespielt. Am Ende: „In deiner Partie kam hier 4. Sxe5?.“ | |
| 252 | + - Der Partiezug noch einmal zählt als Patzer, also sofort Nochmal. | |
| 253 | + - Nicht übernommen: Meisterzüge gelten bei Lichess nie als Fehler; bei uns entscheiden | |
| 254 | + allein die Zeichen aus der Partie. | |
| 241 | 255 | 6. Gemeinsames „Heute dran“ über alle Arten, dann Geschwister und Gruppen. |
| 242 | 256 | 7. `tools/fsrs_optimieren.py`, sobald etwa 500 Wiederholungen da sind. |
| 243 | 257 | |
modified schach/app.py +5 −3
| @@ -30,6 +30,7 @@ from .puzzles import PuzzleMixin # noqa | ||
| 30 | 30 | from .training import OpeningMixin, set_book_paths, set_retention # noqa: E402 |
| 31 | 31 | from .duo import DuoMixin # noqa: E402 |
| 32 | 32 | from .maiadraw import MaiaDrawMixin # noqa: E402 |
| 33 | +from .mistakes import MistakesMixin # noqa: E402 | |
| 33 | 34 | from .review import ReviewMixin # noqa: E402 |
| 34 | 35 | from .setup import SetupMixin # noqa: E402 |
| 35 | 36 | from .explorer import ExplorerMixin # noqa: E402 |
| @@ -83,7 +84,7 @@ DEFAULTS = { | ||
| 83 | 84 | "elo": 1200, "color": "white", "theme": "cburnett", "puzzle_difficulty": "normal", |
| 84 | 85 | "temperature": OPPONENT_TEMPERATURE, "scheme": "holz", "hint_helper": DEFAULT_HELPER, |
| 85 | 86 | "threat_source": "opponent", "notation": notation.DEFAULT, "time_control": "Ohne Uhr", |
| 86 | - "live_glyphs": True, "human_time": True, "books": [], "retention": DEFAULT_RETENTION, | |
| 87 | + "live_glyphs": True, "human_time": True, "books": [], "retention": DEFAULT_RETENTION, "scan_mistakes": True, | |
| 87 | 88 | "sidebar_width": 280, "wdl_source": wdl.DEFAULT_SOURCE, |
| 88 | 89 | } |
| 89 | 90 | |
| @@ -126,8 +127,8 @@ def outcome_text(board, human, opponent= | ||
| 126 | 127 | }.get(outcome.termination, "Remis.") |
| 127 | 128 | |
| 128 | 129 | |
| 129 | -class Window(OnlineMixin, PuzzleMixin, OpeningMixin, DuoMixin, MaiaDrawMixin, SetupMixin, ExplorerMixin, | |
| 130 | - ReviewMixin, Adw.ApplicationWindow): | |
| 130 | +class Window(OnlineMixin, PuzzleMixin, OpeningMixin, DuoMixin, MaiaDrawMixin, MistakesMixin, SetupMixin, | |
| 131 | + ExplorerMixin, ReviewMixin, Adw.ApplicationWindow): | |
| 131 | 132 | """Ein Brett. ``mode``: "maia" (Partie gegen Maia), "online" (Lichess-Partie, ohne Engine-Hilfe), |
| 132 | 133 | "puzzle" (Lichess-Rätsel), "opening" (Eröffnungstraining), "duo" (zwei Spieler an diesem Rechner), |
| 133 | 134 | "review" (fertige Partie ansehen und analysieren).""" |
| @@ -862,6 +863,7 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 862 | 863 | self.banner.show(banner, buttons, level, markup) |
| 863 | 864 | if text and not self.end_shown: |
| 864 | 865 | self.end_shown = True # Seitenleiste bleibt zu: Schlussbild, erst „Nachspielen“ klappt sie auf |
| 866 | + self._mistakes_scan() # still im Hintergrund, ohne Rückfrage | |
| 865 | 867 | |
| 866 | 868 | if self.split.get_show_sidebar(): |
| 867 | 869 | self._movelist_update() |
added schach/mistakes.py +141 −0
| @@ -0,0 +1,141 @@ | ||
| 1 | +"""Aus Fehlern lernen (Art B): eigene Fehler aus Partien gegen Maia werden Übungen. | |
| 2 | + | |
| 3 | +Vorbild ist „Aus Fehlern lernen“ von Lichess (``lila: ui/analyse/src/retrospect``), aber mit | |
| 4 | +Gedächtnis: Nach jeder fertigen eigenen Partie gegen Maia werden still im Hintergrund die | |
| 5 | +schwersten eigenen Fehler (? und ??, höchstens drei) zu Karten. Geübt wird unter „Rätsel“. | |
| 6 | + | |
| 7 | +- Stellung: die vor dem eigenen Fehler; der Zug des Gegners davor wird vorgespielt. | |
| 8 | +- Richtig ist jeder Zug, der höchstens ``SAME`` Prozentpunkte Gewinnchance hinter dem besten | |
| 9 | + liegt (Lichess: 0,04 auf der Skala −1 … +1, das sind 2 Prozentpunkte). | |
| 10 | +- Der Partiezug noch einmal zählt als Patzer (sofort Nochmal). | |
| 11 | + | |
| 12 | +Die Bewertungen ? und ?? entstehen schon während der Partie (``annotate``). Nachgerechnet wird | |
| 13 | +nur, welche Züge in der Stellung davor gut genug sind. | |
| 14 | +""" | |
| 15 | + | |
| 16 | +import chess | |
| 17 | +import chess.engine | |
| 18 | +import gi | |
| 19 | + | |
| 20 | +gi.require_version("Adw", "1") | |
| 21 | +from gi.repository import Adw # noqa: E402 | |
| 22 | + | |
| 23 | +from . import annotate, repetition, training # noqa: E402 | |
| 24 | + | |
| 25 | +MAX_PER_GAME = 3 | |
| 26 | +SAME = 2.0 # Prozentpunkte Gewinnchance: so knapp hinter dem besten gilt ein Zug als richtig | |
| 27 | +LINES = 8 # so viele Kandidaten rechnet Stockfish je Stellung | |
| 28 | +LIMIT = chess.engine.Limit(depth=16, time=3) | |
| 29 | +SYMBOLS = ("??", "?") # schwerste zuerst | |
| 30 | + | |
| 31 | + | |
| 32 | +def candidates(board, human, symbols): | |
| 33 | + """Halbzüge der eigenen Fehler, die eine Übung werden: höchstens ``MAX_PER_GAME``, die schwersten | |
| 34 | + zuerst, dann die früheren. ``board``: Stellung am Ende der Partie (mit ``move_stack``).""" | |
| 35 | + root = board.root() | |
| 36 | + found = [] | |
| 37 | + for ply, symbol in symbols.items(): | |
| 38 | + if symbol not in SYMBOLS or ply >= len(board.move_stack): | |
| 39 | + continue | |
| 40 | + mover = root.turn if ply % 2 == 0 else not root.turn | |
| 41 | + if mover == human: | |
| 42 | + found.append((SYMBOLS.index(symbol), ply)) | |
| 43 | + return sorted(ply for _rank, ply in sorted(found)[:MAX_PER_GAME]) | |
| 44 | + | |
| 45 | + | |
| 46 | +def positions(board, plies, symbols): | |
| 47 | + """Je Fehler: Stellung davor, der Zug des Gegners davor (zum Vorspielen) und der Partiezug.""" | |
| 48 | + stack = board.move_stack | |
| 49 | + root = board.root() | |
| 50 | + result = [] | |
| 51 | + for ply in plies: | |
| 52 | + start = root.copy(stack=False) | |
| 53 | + for move in stack[:max(ply - 1, 0)]: | |
| 54 | + start.push(move) | |
| 55 | + last = stack[ply - 1] if ply > 0 else None | |
| 56 | + before = start.copy(stack=False) | |
| 57 | + if last is not None: | |
| 58 | + before.push(last) | |
| 59 | + result.append({"start": start, "last": last, "before": before, "played": stack[ply], | |
| 60 | + "symbol": symbols[ply]}) | |
| 61 | + return result | |
| 62 | + | |
| 63 | + | |
| 64 | +def accepted(scores, played): | |
| 65 | + """Bester Zug und alle, die höchstens ``SAME`` dahinter liegen (ohne den Partiezug).""" | |
| 66 | + if not scores: | |
| 67 | + return None, [] | |
| 68 | + best = max(scores, key=scores.get) | |
| 69 | + good = [m for m, wp in sorted(scores.items(), key=lambda item: -item[1]) | |
| 70 | + if wp >= scores[best] - SAME and m != played] | |
| 71 | + return best, good | |
| 72 | + | |
| 73 | + | |
| 74 | +def cards_job(found): | |
| 75 | + """Job-Fabrik für Stockfish: zu jedem Fehler (aus ``positions``) Schlüssel und Karteninhalt.""" | |
| 76 | + | |
| 77 | + def job(engine): | |
| 78 | + cards = [] | |
| 79 | + for item in found: | |
| 80 | + before = item["before"] | |
| 81 | + n = min(LINES, before.legal_moves.count()) | |
| 82 | + if n == 0: | |
| 83 | + continue | |
| 84 | + infos = engine.analyse(before, LIMIT, multipv=n) | |
| 85 | + entry = annotate._entry(infos, before.turn, 0) | |
| 86 | + best, good = accepted(entry["scores"], item["played"]) | |
| 87 | + if best is None or best == item["played"] or not good: | |
| 88 | + continue # tiefer gerechnet war der Partiezug doch gut genug | |
| 89 | + content = { | |
| 90 | + "fen": item["start"].fen(), | |
| 91 | + "last": item["last"].uci() if item["last"] else None, | |
| 92 | + "solution": [best.uci()], | |
| 93 | + "accepted": [m.uci() for m in good], | |
| 94 | + "played": item["played"].uci(), | |
| 95 | + "symbol": item["symbol"], | |
| 96 | + } | |
| 97 | + cards.append((repetition.position_key(before), content)) | |
| 98 | + return cards | |
| 99 | + | |
| 100 | + return job | |
| 101 | + | |
| 102 | + | |
| 103 | +def found_text(count): | |
| 104 | + what = "1 Stellung" if count == 1 else f"{count} Stellungen" | |
| 105 | + return f"Aus dieser Partie: {what} zum Üben – unter „Rätsel“" | |
| 106 | + | |
| 107 | + | |
| 108 | +class MistakesMixin: | |
| 109 | + """Nach dem Partieende still nach eigenen Fehlern suchen (Einstellung „scan_mistakes“).""" | |
| 110 | + | |
| 111 | + def _mistakes_scan(self): | |
| 112 | + if self.mode != "maia" or self._foreign() or not self.settings.get("scan_mistakes", True): | |
| 113 | + return | |
| 114 | + stockfish = getattr(self, "stockfish", None) | |
| 115 | + if stockfish is None or not self.board.move_stack: | |
| 116 | + return | |
| 117 | + game, human = self.board.copy(), self.human | |
| 118 | + snapshot = dict(self.symbols) | |
| 119 | + board_now = self.board | |
| 120 | + | |
| 121 | + def ready(_result, _error): | |
| 122 | + # läuft nach den Bewertungen, die bis zum Partieende in der Warteschlange standen | |
| 123 | + symbols = dict(self.symbols) if self.board is board_now else snapshot | |
| 124 | + plies = candidates(game, human, symbols) | |
| 125 | + if plies: | |
| 126 | + stockfish.submit(cards_job(positions(game, plies, symbols)), saved) | |
| 127 | + return False | |
| 128 | + | |
| 129 | + def saved(cards, error): | |
| 130 | + if error is not None or not cards: | |
| 131 | + return False | |
| 132 | + try: | |
| 133 | + progress = training.progress() | |
| 134 | + except RuntimeError: # fsrs fehlt | |
| 135 | + return False | |
| 136 | + added = sum(progress.add_mistake(key, content) for key, content in cards) | |
| 137 | + if added: | |
| 138 | + self.toasts.add_toast(Adw.Toast(title=found_text(added), timeout=4)) | |
| 139 | + return False | |
| 140 | + | |
| 141 | + stockfish.submit(lambda _engine: None, ready) | |
modified schach/prefs.py +9 −1
| @@ -111,7 +111,7 @@ class Preferences(Adw.PreferencesDialog) | ||
| 111 | 111 | return page |
| 112 | 112 | |
| 113 | 113 | def _training_group(self): |
| 114 | - """Wie oft geübte Kurslinien wiederkommen (Zielwert von FSRS).""" | |
| 114 | + """Wie oft Geübtes wiederkommt (Zielwert von FSRS) und was aus Partien geübt wird.""" | |
| 115 | 115 | group = Adw.PreferencesGroup(title="Training") |
| 116 | 116 | keys = [key for key, _label, _text in RETENTION_LEVELS] |
| 117 | 117 | labels = [label for _key, label, _text in RETENTION_LEVELS] |
| @@ -129,6 +129,14 @@ class Preferences(Adw.PreferencesDialog) | ||
| 129 | 129 | show() |
| 130 | 130 | row.connect("notify::selected", changed) |
| 131 | 131 | group.add(row) |
| 132 | + mistakes = Adw.SwitchRow( | |
| 133 | + title="Partien nach Lernmöglichkeiten absuchen", | |
| 134 | + subtitle="Nach jeder Partie gegen Maia werden deine Fehler (? und ??) zu Übungen. " | |
| 135 | + "Sie kommen unter „Rätsel“ wieder.", | |
| 136 | + active=bool(self.win.settings.get("scan_mistakes", True)), | |
| 137 | + ) | |
| 138 | + mistakes.connect("notify::active", lambda r, _p: self._set("scan_mistakes", r.get_active())) | |
| 139 | + group.add(mistakes) | |
| 132 | 140 | return group |
| 133 | 141 | |
| 134 | 142 | def _programs_group(self): |
modified schach/puzzles.py +38 −15
| @@ -5,7 +5,8 @@ Rätselwertung ändert. Wie auf Lichess zählt ein Rätsel nur als gelöst, wenn | ||
| 5 | 5 | kein falscher Zug gespielt und kein Hinweis benutzt wurde. |
| 6 | 6 | |
| 7 | 7 | Falsch gelöste Rätsel (oder mit Hinweis) werden lokal als Karte aufgehoben und |
| 8 | -kommen nach FSRS wieder, vor neuen Rätseln von Lichess. Wiederholungen laufen | |
| 8 | +kommen nach FSRS wieder, vor neuen Rätseln von Lichess – zusammen mit den eigenen | |
| 9 | +Fehlern aus Partien (``mistakes``). Wiederholungen laufen | |
| 9 | 10 | ohne Netz und werden nicht an Lichess gemeldet, sonst stimmt die Wertung nicht. |
| 10 | 11 | """ |
| 11 | 12 | |
| @@ -17,7 +18,7 @@ import gi | ||
| 17 | 18 | gi.require_version("Adw", "1") |
| 18 | 19 | from gi.repository import Adw, GLib # noqa: E402 |
| 19 | 20 | |
| 20 | -from . import lichess, repetition, training # noqa: E402 | |
| 21 | +from . import lichess, notation, repetition, training # noqa: E402 | |
| 21 | 22 | |
| 22 | 23 | OPPONENT_DELAY_MS = 550 |
| 23 | 24 | TAKE_BACK_MS = 900 |
| @@ -38,7 +39,8 @@ class PuzzleMixin: | ||
| 38 | 39 | if due is not None: |
| 39 | 40 | board = chess.Board(due["fen"]) |
| 40 | 41 | solution = [chess.Move.from_uci(uci) for uci in due["solution"]] |
| 41 | - self._puzzle_begin(board, chess.Move.from_uci(due["last"]), solution, due, review=True) | |
| 42 | + last = chess.Move.from_uci(due["last"]) if due.get("last") else None | |
| 43 | + self._puzzle_begin(board, last, solution, due, review=True) | |
| 42 | 44 | return |
| 43 | 45 | gen = self.gen |
| 44 | 46 | app = self.get_application() |
| @@ -62,20 +64,31 @@ class PuzzleMixin: | ||
| 62 | 64 | self._puzzle_begin(board, last, solution, info) |
| 63 | 65 | |
| 64 | 66 | def _puzzle_begin(self, board, last, solution, info, review=False): |
| 65 | - """``review``: ein aufgehobenes Rätsel als Wiederholung, sonst frisch von Lichess.""" | |
| 67 | + """``review``: ein aufgehobenes Rätsel oder ein eigener Fehler als Wiederholung, sonst frisch | |
| 68 | + von Lichess. ``last``: Zug des Gegners, der vorgespielt wird (None: gleich selbst am Zug).""" | |
| 66 | 69 | self.board = board |
| 67 | - self.human = not board.turn # der letzte Zug ist vom Gegner, danach ist man selbst dran | |
| 70 | + self.human = board.turn if last is None else not board.turn | |
| 68 | 71 | self.view.flipped = self.human == chess.BLACK |
| 72 | + played = chess.Move.from_uci(info["played"]) if info.get("played") else None | |
| 73 | + played_san = None | |
| 74 | + if played is not None: | |
| 75 | + probe = board.copy(stack=False) | |
| 76 | + if last is not None: | |
| 77 | + probe.push(last) | |
| 78 | + played_san = notation.label(probe, played, self._notation()) + (info.get("symbol") or "") | |
| 69 | 79 | self.puzzle = { |
| 70 | 80 | "id": info["id"], "rating": info.get("rating"), "themes": info.get("themes", []), |
| 71 | 81 | "solution": solution, "index": 0, "failed": False, "done": False, |
| 72 | 82 | "reported": False, "rating_diff": None, |
| 73 | 83 | "review": review, "errors": 0, "hints": 0, "reveals": 0, "recorded": False, "saved_days": None, |
| 74 | - "fen": board.fen(), "last": last.uci(), "started": time.monotonic(), | |
| 84 | + "fen": board.fen(), "last": last.uci() if last else None, "started": time.monotonic(), | |
| 85 | + "card": info.get("card"), "blunders": 0, "played": played, "played_san": played_san, | |
| 86 | + "accepted": {chess.Move.from_uci(uci) for uci in info.get("accepted", ())}, | |
| 75 | 87 | } |
| 76 | 88 | self._changed() |
| 77 | 89 | self._refresh() |
| 78 | - GLib.timeout_add(OPPONENT_DELAY_MS, self._puzzle_reply, self.gen, last, False) | |
| 90 | + if last is not None: | |
| 91 | + GLib.timeout_add(OPPONENT_DELAY_MS, self._puzzle_reply, self.gen, last, False) | |
| 79 | 92 | |
| 80 | 93 | def _puzzle_reply(self, gen, move, counts=True): |
| 81 | 94 | """Gegnerzug (der Ausgangszug oder eine Antwort aus der Lösung).""" |
| @@ -99,8 +112,9 @@ class PuzzleMixin: | ||
| 99 | 112 | self.view.animate_move(self.board, move) |
| 100 | 113 | self.board.push(move) |
| 101 | 114 | self.browse_ply = None |
| 102 | - # Wie auf Lichess: Ein anderes Matt im letzten Zug gilt auch | |
| 103 | - correct = move == expected or self.board.is_checkmate() | |
| 115 | + # Wie auf Lichess: Ein anderes Matt im letzten Zug gilt auch; beim eigenen Fehler jeder | |
| 116 | + # Zug, der fast so gut ist wie der beste | |
| 117 | + correct = move == expected or self.board.is_checkmate() or (p["index"] == 0 and move in p["accepted"]) | |
| 104 | 118 | if correct: |
| 105 | 119 | p["index"] += 1 |
| 106 | 120 | self._changed() |
| @@ -111,7 +125,10 @@ class PuzzleMixin: | ||
| 111 | 125 | GLib.timeout_add(OPPONENT_DELAY_MS, self._puzzle_reply, self.gen, reply) |
| 112 | 126 | self._refresh() |
| 113 | 127 | return |
| 114 | - p["errors"] += 1 | |
| 128 | + if move == p["played"]: | |
| 129 | + p["blunders"] += 1 # derselbe Fehler wie in der Partie | |
| 130 | + else: | |
| 131 | + p["errors"] += 1 | |
| 115 | 132 | self._puzzle_fail() |
| 116 | 133 | self.symbols[ply] = "?" |
| 117 | 134 | self.badge_ply = ply |
| @@ -156,9 +173,11 @@ class PuzzleMixin: | ||
| 156 | 173 | if p["review"]: |
| 157 | 174 | # Hinweis Stufe 1 (Figur) wie ein halber Fehler, Stufe 2 (ganzer Zug) sofort Nochmal |
| 158 | 175 | hints = repetition.hint_weight(p["hints"], p["reveals"]) |
| 159 | - grade = repetition.grade(p["errors"], hints, 0, p["reveals"]) | |
| 176 | + grade = repetition.grade(p["errors"], hints, p["blunders"], p["reveals"]) | |
| 160 | 177 | days = self._puzzle_record(grade) |
| 161 | 178 | lead = "Gelöst!" if grade == repetition.GOOD else "Geschafft." |
| 179 | + if p["played_san"]: | |
| 180 | + lead += f" In deiner Partie kam hier {p['played_san']}." | |
| 162 | 181 | if days is not None: |
| 163 | 182 | lead += " " + repetition.next_text(days, grade, puzzle=True) |
| 164 | 183 | self.final_text = lead |
| @@ -206,7 +225,8 @@ class PuzzleMixin: | ||
| 206 | 225 | self.puzzle_recent = p["id"] |
| 207 | 226 | duration = int((time.monotonic() - p["started"]) * 1000) |
| 208 | 227 | hints = repetition.hint_weight(p["hints"], p["reveals"]) |
| 209 | - return progress.record_puzzle(p["id"], grade, errors=p["errors"], hints=hints, | |
| 228 | + card = p["card"] or (repetition.KIND_PUZZLE, repetition.PUZZLE_SOURCE, str(p["id"])) | |
| 229 | + return progress.record_puzzle(card, grade, errors=p["errors"], hints=hints, blunders=p["blunders"], | |
| 210 | 230 | duration_ms=duration) |
| 211 | 231 | |
| 212 | 232 | def _puzzle_report(self, win): |
| @@ -241,9 +261,12 @@ class PuzzleMixin: | ||
| 241 | 261 | if p is None: |
| 242 | 262 | return "Rätsel wird geladen …" if self.final_text is None else "Rätsel" |
| 243 | 263 | side = "Weiß" if self.human == chess.WHITE else "Schwarz" |
| 244 | - parts = [f"Rätsel {p['rating']}" if p.get("rating") else "Rätsel"] | |
| 245 | - if p["review"]: | |
| 246 | - parts.insert(0, "Wiederholung") | |
| 264 | + if p["played"] is not None: | |
| 265 | + parts = ["Aus deiner Partie"] | |
| 266 | + else: | |
| 267 | + parts = [f"Rätsel {p['rating']}" if p.get("rating") else "Rätsel"] | |
| 268 | + if p["review"]: | |
| 269 | + parts.insert(0, "Wiederholung") | |
| 247 | 270 | if p["rating_diff"] is not None: |
| 248 | 271 | parts.append(f"deine Rätselwertung {p['rating_diff']:+d}") |
| 249 | 272 | elif not p["done"]: |
modified schach/repetition.py +36 −15
| @@ -34,6 +34,9 @@ KIND_LINE = "course_line" # früher: eine Karte pro Linie; wird beim Öffnen des Kurses umgewandelt | ||
| 34 | 34 | KIND_LINE_DONE = "course_line_done" # umgewandelte Linienkarte, bleibt mit ihrem Protokoll erhalten |
| 35 | 35 | KIND_PUZZLE = "lichess_puzzle" # falsch gelöstes Lichess-Rätsel, Schlüssel: Rätsel-ID |
| 36 | 36 | PUZZLE_SOURCE = "lichess" |
| 37 | +KIND_MISTAKE = "own_mistake" # eigener Fehler (? oder ??) aus einer Partie, Schlüssel: Stellung davor | |
| 38 | +MISTAKE_SOURCE = "partie" | |
| 39 | +PUZZLE_KINDS = ((KIND_PUZZLE, PUZZLE_SOURCE), (KIND_MISTAKE, MISTAKE_SOURCE)) # unter „Rätsel“ | |
| 37 | 40 | MAX_DAYS = 60 # länger nicht: sonst merkt man sich eher die Stellung als das Muster |
| 38 | 41 | RETENTION = {"relaxed": 0.80, "balanced": 0.85, "thorough": 0.92} # Einstellung „Wiederholen“ |
| 39 | 42 | DEFAULT_RETENTION = "balanced" |
| @@ -448,35 +451,53 @@ class Progress: | ||
| 448 | 451 | return self._review(KIND_PUZZLE, PUZZLE_SOURCE, str(puzzle["id"]), content, AGAIN, now, |
| 449 | 452 | errors, hints, again_today=False) |
| 450 | 453 | |
| 451 | - def due_puzzle(self, today=None, skip=()): | |
| 452 | - """Das dringendste fällige Rätsel als dict (wie bei ``save_puzzle``) – oder None. | |
| 454 | + def add_mistake(self, key, content, now=None): | |
| 455 | + """Eigenen Fehler aus einer Partie als neue Karte anlegen, gleich fällig. False, wenn es | |
| 456 | + die Stellung schon gibt (dieselbe Eröffnung, derselbe Fehler).""" | |
| 457 | + now = now or datetime.datetime.now() | |
| 458 | + card = fsrs.Card(due=_utc(now)) | |
| 459 | + values = (int(card.state), card.step, card.stability, card.difficulty, card.due.isoformat(), | |
| 460 | + None, None) | |
| 461 | + cursor = self.db.execute( | |
| 462 | + "INSERT OR IGNORE INTO cards (kind, source, key, created, content, " + ", ".join(STATE_COLUMNS) | |
| 463 | + + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", | |
| 464 | + (KIND_MISTAKE, MISTAKE_SOURCE, key, now.date().isoformat(), json.dumps(content)) + values, | |
| 465 | + ) | |
| 466 | + self.db.commit() | |
| 467 | + return cursor.rowcount > 0 | |
| 453 | 468 | |
| 454 | - Zuerst nach Termin; was heute schon „Nochmal“ hatte, kommt nach den anderen. ``skip``: | |
| 455 | - IDs, die gerade dran waren. | |
| 469 | + def _puzzle_rows(self): | |
| 470 | + for kind, source in PUZZLE_KINDS: | |
| 471 | + yield from self.db.execute("SELECT * FROM cards WHERE kind = ? AND source = ?", (kind, source)) | |
| 472 | + | |
| 473 | + def due_puzzle(self, today=None, skip=()): | |
| 474 | + """Das dringendste fällige Rätsel als dict (wie bei ``save_puzzle`` bzw. ``add_mistake``) | |
| 475 | + mit ``id`` (Schlüssel) und ``card`` (für ``record_puzzle``) – oder None. | |
| 476 | + | |
| 477 | + Aufgehobene Lichess-Rätsel und eigene Fehler gemeinsam, zuerst nach Termin; was heute schon | |
| 478 | + „Nochmal“ hatte, kommt nach den anderen. ``skip``: Schlüssel, die gerade dran waren. | |
| 456 | 479 | """ |
| 457 | 480 | today = today or datetime.date.today() |
| 458 | 481 | due = [] |
| 459 | - for row in self.db.execute("SELECT * FROM cards WHERE kind = ? AND source = ?", | |
| 460 | - (KIND_PUZZLE, PUZZLE_SOURCE)): | |
| 482 | + for row in self._puzzle_rows(): | |
| 461 | 483 | if row["key"] in skip or self._due_day(row, today) > today: |
| 462 | 484 | continue |
| 463 | 485 | due.append((row["again_day"] == today.isoformat(), row["due"], row)) |
| 464 | 486 | if not due: |
| 465 | 487 | return None |
| 466 | 488 | row = min(due, key=lambda item: item[:2])[2] |
| 467 | - return dict(json.loads(row["content"]), id=row["key"]) | |
| 489 | + return dict(json.loads(row["content"]), id=row["key"], card=(row["kind"], row["source"], row["key"])) | |
| 468 | 490 | |
| 469 | 491 | def puzzles_due(self, today=None): |
| 470 | - """Wie viele aufgehobene Rätsel heute dran sind.""" | |
| 492 | + """Wie viele Rätsel (aufgehobene und eigene Fehler) heute dran sind.""" | |
| 471 | 493 | today = today or datetime.date.today() |
| 472 | - rows = self.db.execute("SELECT * FROM cards WHERE kind = ? AND source = ?", | |
| 473 | - (KIND_PUZZLE, PUZZLE_SOURCE)) | |
| 474 | - return sum(1 for row in rows if self._due_day(row, today) <= today) | |
| 494 | + return sum(1 for row in self._puzzle_rows() if self._due_day(row, today) <= today) | |
| 475 | 495 | |
| 476 | - def record_puzzle(self, puzzle_id, grade, now=None, errors=None, hints=None, duration_ms=None): | |
| 477 | - """Wiederholung eines aufgehobenen Rätsels eintragen; Tage bis zum nächsten Termin.""" | |
| 478 | - return self._review(KIND_PUZZLE, PUZZLE_SOURCE, str(puzzle_id), None, grade, now, errors, | |
| 479 | - hints, duration_ms=duration_ms) | |
| 496 | + def record_puzzle(self, card, grade, now=None, errors=None, hints=None, blunders=None, | |
| 497 | + duration_ms=None): | |
| 498 | + """Wiederholung eintragen; ``card`` aus ``due_puzzle``. Tage bis zum nächsten Termin.""" | |
| 499 | + kind, source, key = card | |
| 500 | + return self._review(kind, source, key, None, grade, now, errors, hints, blunders, duration_ms) | |
| 480 | 501 | |
| 481 | 502 | |
| 482 | 503 | def hint_weight(hints, reveals): |
added tests/test_mistakes.py +181 −0
| @@ -0,0 +1,181 @@ | ||
| 1 | +"""Aus Fehlern lernen: eigene ? und ?? aus Partien gegen Maia werden Übungen unter „Rätsel“.""" | |
| 2 | + | |
| 3 | +import unittest | |
| 4 | +from unittest import mock | |
| 5 | + | |
| 6 | +import chess | |
| 7 | +import chess.engine | |
| 8 | + | |
| 9 | +from schach import mistakes, puzzles, repetition, training | |
| 10 | + | |
| 11 | +# 1. e4 e5 2. Sf3 Sc6 3. Lc4 Sd4 4. Sxe5? (Halbzug 6) Dg5 | |
| 12 | +GAME = ["e2e4", "e7e5", "g1f3", "b8c6", "f1c4", "c6d4", "f3e5", "d8g5"] | |
| 13 | +CP = {"f3d4": 80, "e1g1": 75, "c2c3": 10, "f3e5": -150} # Bewertung nach Weiß, Stellung nach 3… Sd4 | |
| 14 | + | |
| 15 | + | |
| 16 | +def _game(): | |
| 17 | + board = chess.Board() | |
| 18 | + for uci in GAME: | |
| 19 | + board.push_uci(uci) | |
| 20 | + return board | |
| 21 | + | |
| 22 | + | |
| 23 | +class _Engine: | |
| 24 | + """Stockfish-Ersatz: kennt nur die Stellung nach 3… Sd4.""" | |
| 25 | + | |
| 26 | + def analyse(self, board, _limit, multipv=1): | |
| 27 | + infos = [] | |
| 28 | + for uci, cp in sorted(CP.items(), key=lambda item: -item[1]): | |
| 29 | + score = chess.engine.PovScore(chess.engine.Cp(cp), chess.WHITE) | |
| 30 | + infos.append({"pv": [chess.Move.from_uci(uci)], "score": score, "depth": 16}) | |
| 31 | + return infos[:multipv] | |
| 32 | + | |
| 33 | + | |
| 34 | +class _Worker: | |
| 35 | + """Engine-Warteschlange, die sofort rechnet und zurückruft.""" | |
| 36 | + | |
| 37 | + def submit(self, fn, callback): | |
| 38 | + callback(fn(_Engine()), None) | |
| 39 | + | |
| 40 | + | |
| 41 | +class LogicTest(unittest.TestCase): | |
| 42 | + def test_candidates_only_own_and_worst_first(self): | |
| 43 | + board = _game() | |
| 44 | + symbols = {0: "?", 2: "??", 4: "?!", 6: "?", 1: "??", 5: "?"} # ungerade: Schwarz | |
| 45 | + self.assertEqual(mistakes.candidates(board, chess.WHITE, symbols), [0, 2, 6]) | |
| 46 | + symbols[3] = "??" # jetzt hat Weiß vier, die ?? gehen vor | |
| 47 | + symbols[4] = "??" | |
| 48 | + self.assertEqual(mistakes.candidates(board, chess.WHITE, symbols), [0, 2, 4]) # 0 ist das frühere ? | |
| 49 | + self.assertEqual(mistakes.candidates(board, chess.BLACK, symbols), [1, 3, 5]) | |
| 50 | + | |
| 51 | + def test_position_before_the_mistake(self): | |
| 52 | + (item,) = mistakes.positions(_game(), [6], {6: "?"}) | |
| 53 | + self.assertEqual(item["last"], chess.Move.from_uci("c6d4")) | |
| 54 | + self.assertEqual(item["played"], chess.Move.from_uci("f3e5")) | |
| 55 | + self.assertEqual(item["before"].turn, chess.WHITE) | |
| 56 | + self.assertEqual(item["start"].turn, chess.BLACK) | |
| 57 | + | |
| 58 | + def test_almost_as_good_counts(self): | |
| 59 | + scores = {chess.Move.from_uci(u): v for u, v in {"a2a3": 60.0, "b2b3": 58.5, "c2c3": 57.0}.items()} | |
| 60 | + best, good = mistakes.accepted(scores, chess.Move.from_uci("c2c3")) | |
| 61 | + self.assertEqual(best.uci(), "a2a3") | |
| 62 | + self.assertEqual([m.uci() for m in good], ["a2a3", "b2b3"]) | |
| 63 | + | |
| 64 | + def test_cards_job(self): | |
| 65 | + found = mistakes.positions(_game(), [6], {6: "?"}) | |
| 66 | + ((key, content),) = mistakes.cards_job(found)(_Engine()) | |
| 67 | + self.assertEqual(content["solution"], ["f3d4"]) | |
| 68 | + self.assertEqual(content["accepted"], ["f3d4", "e1g1"]) # Rochade fast genauso gut, c3 nicht | |
| 69 | + self.assertEqual((content["last"], content["played"]), ("c6d4", "f3e5")) | |
| 70 | + self.assertEqual(key, repetition.position_key(found[0]["before"])) | |
| 71 | + | |
| 72 | + | |
| 73 | +class _Toasts: | |
| 74 | + def __init__(self): | |
| 75 | + self.titles = [] | |
| 76 | + | |
| 77 | + def add_toast(self, toast): | |
| 78 | + self.titles.append(toast.get_title()) | |
| 79 | + | |
| 80 | + | |
| 81 | +class _View: | |
| 82 | + flipped = False | |
| 83 | + | |
| 84 | + def animate_move(self, _board, _move): | |
| 85 | + pass | |
| 86 | + | |
| 87 | + | |
| 88 | +class _App: | |
| 89 | + lichess_client = None | |
| 90 | + | |
| 91 | + | |
| 92 | +class FakeWindow(mistakes.MistakesMixin, puzzles.PuzzleMixin): | |
| 93 | + def __init__(self): | |
| 94 | + self.mode = "maia" | |
| 95 | + self.board = _game() | |
| 96 | + self.human = chess.WHITE | |
| 97 | + self.symbols = {6: "?", 7: "??"} # 7: Maias Fehler zählt nicht | |
| 98 | + self.settings = {} | |
| 99 | + self.names = [] | |
| 100 | + self.stockfish = _Worker() | |
| 101 | + self.toasts = _Toasts() | |
| 102 | + self.view = _View() | |
| 103 | + self.gen = 0 | |
| 104 | + self.puzzle = None | |
| 105 | + self.badge_ply = self.browse_ply = self.hint_move = self.final_text = None | |
| 106 | + | |
| 107 | + def _foreign(self): | |
| 108 | + return False | |
| 109 | + | |
| 110 | + def _notation(self): | |
| 111 | + return "de" | |
| 112 | + | |
| 113 | + def get_application(self): | |
| 114 | + return _App() | |
| 115 | + | |
| 116 | + def _leave_special(self): | |
| 117 | + self._puzzle_leave() | |
| 118 | + | |
| 119 | + def _reset_game_tables(self): | |
| 120 | + self.symbols = {} | |
| 121 | + | |
| 122 | + def _changed(self): | |
| 123 | + self.gen += 1 | |
| 124 | + | |
| 125 | + def _refresh(self): | |
| 126 | + pass | |
| 127 | + | |
| 128 | + | |
| 129 | +class ScanTest(unittest.TestCase): | |
| 130 | + def setUp(self): | |
| 131 | + self.progress = repetition.Progress(fuzz=False) | |
| 132 | + patches = [ | |
| 133 | + mock.patch.object(training, "progress", lambda: self.progress), | |
| 134 | + mock.patch.object(puzzles.GLib, "timeout_add", lambda _ms, fn, *a: fn(*a)), | |
| 135 | + mock.patch.object(puzzles.lichess, "_background", mock.Mock()), | |
| 136 | + ] | |
| 137 | + for patch in patches: | |
| 138 | + patch.start() | |
| 139 | + self.addCleanup(patch.stop) | |
| 140 | + self.window = FakeWindow() | |
| 141 | + | |
| 142 | + def test_game_end_keeps_own_mistake_silently(self): | |
| 143 | + self.window._mistakes_scan() | |
| 144 | + self.assertEqual(self.progress.puzzles_due(), 1) # gleich zu üben | |
| 145 | + self.assertEqual(self.window.toasts.titles, ["Aus dieser Partie: 1 Stellung zum Üben – unter „Rätsel“"]) | |
| 146 | + self.window._mistakes_scan() # dieselbe Partie noch einmal: nichts doppelt | |
| 147 | + self.assertEqual(self.progress.puzzles_due(), 1) | |
| 148 | + self.assertEqual(len(self.window.toasts.titles), 1) | |
| 149 | + | |
| 150 | + def test_switched_off(self): | |
| 151 | + self.window.settings["scan_mistakes"] = False | |
| 152 | + self.window._mistakes_scan() | |
| 153 | + self.assertEqual(self.progress.puzzles_due(), 0) | |
| 154 | + | |
| 155 | + def test_only_games_against_maia(self): | |
| 156 | + self.window.mode = "duo" | |
| 157 | + self.window._mistakes_scan() | |
| 158 | + self.assertEqual(self.progress.puzzles_due(), 0) | |
| 159 | + | |
| 160 | + def _practise(self): | |
| 161 | + self.window._mistakes_scan() | |
| 162 | + self.window.start_puzzle() | |
| 163 | + self.assertEqual(self.window.board.peek(), chess.Move.from_uci("c6d4")) # Maias Zug vorgespielt | |
| 164 | + self.assertEqual(self.window._puzzle_subtitle(), "Aus deiner Partie · Weiß am Zug") | |
| 165 | + | |
| 166 | + def test_good_alternative_solves_it(self): | |
| 167 | + self._practise() | |
| 168 | + self.window._puzzle_play(chess.Move.from_uci("e1g1")) # nicht der beste, aber fast so gut | |
| 169 | + self.assertTrue(self.window.final_text.startswith("Gelöst! In deiner Partie kam hier 4. Sxe5?.")) | |
| 170 | + self.assertEqual(self.progress.puzzles_due(), 0) | |
| 171 | + | |
| 172 | + def test_same_mistake_again_is_again(self): | |
| 173 | + self._practise() | |
| 174 | + self.window._puzzle_play(chess.Move.from_uci("f3e5")) # wie in der Partie | |
| 175 | + self.window._puzzle_take_back(self.window.gen, 6) | |
| 176 | + self.window._puzzle_play(chess.Move.from_uci("f3d4")) | |
| 177 | + self.assertIn("Das Rätsel wiederholen wir gleich", self.window.final_text) | |
| 178 | + | |
| 179 | + | |
| 180 | +if __name__ == "__main__": | |
| 181 | + unittest.main() | |