Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(training): spaced repetition per course line

public

feat(training): spaced repetition per course line

One card per line from start to variation end. Opponent follows the
line that is due; clean runs climb 1/3/7/14/30/60/120 days, an error
or hint makes the line due again after the other due lines. At most
3 new lines per course and day. Course dialog shows what is due
today. Stored in training.json.

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

modified ROADMAP.md +11 −7

@@ -375,11 +375,15 @@ Erklärung:
375375
 
376376
 ### Später
377377
 
378
-- **Wiederholung nach Fehlern:** Linien mit Fehlern kommen früher wieder dran,
379
-  nach dem Lernkarten-Prinzip wie bei Anki. Die „Karte“ ist eine Kurslinie, also
380
-  ein Weg vom Start bis zum Ende einer Variante. Bei einem Fehler oder Hinweis
381
-  kommt sie schon morgen wieder dran. Sonst wächst der Abstand (1, 3, 7, 14 Tage
382
-  …). „Nächste Linie“ nimmt die fälligste. Speicherort
378
+- **Wiederholung nach Fehlern** (umgesetzt 20.11.2026, `schach/repetition.py`):
379
+  Lernkarten wie bei Anki, eine Karte pro Kurslinie (Weg vom Start bis zum Ende
380
+  einer Variante). Der Gegner antwortet entlang der Linie, die heute dran ist.
381
+  Fehlerfrei und ohne Hinweis wächst der Abstand (1, 3, 7, 14, 30, 60, 120 Tage),
382
+  mit Fehler oder Hinweis ist die Linie sofort wieder fällig, nach den anderen
383
+  fälligen. Reihenfolge: fällige, dann neue (höchstens 3 pro Kurs und Tag, wie das
384
+  Tageslimit bei Anki), danach freiwilliges Weiterüben. Der Kursdialog zeigt
385
+  „Heute dran: 2 zum Wiederholen und 5 neu (von 13 Linien)“, das Ende einer Linie
386
+  „Diese Linie kommt in 3 Tagen wieder.“ Gespeichert in
383387
   `~/.local/share/schach/training.json`.
384388
 - **Eröffnung in eigenen Partien:** Nach einer Partie gegen Maia steht in der
385389
   Zugliste „Buch bis Zug 6, dann Abweichung: Kurs empfiehlt …“. So merkt Florian
@@ -592,5 +596,5 @@ Zeichenroutine wie das Fenster (`schach/
592596
 
593597
 ## Offene Fragen
594598
 
595
-- Sollen Hinweise beim Eröffnungstraining gezählt werden, z. B. für eine
596
-  Fortschrittsanzeige pro Linie?
599
+- ~~Sollen Hinweise beim Eröffnungstraining gezählt werden?~~ Ja: Ein Hinweis
600
+  zählt für die Wiederholung wie ein Fehler.

added schach/repetition.py +161 −0

@@ -0,0 +1,161 @@
1
+"""Wiederholung nach Fehlern – Lernkarten wie bei Anki, eine Karte pro Kurslinie.
2
+
3
+Eine Linie ist ein Weg durch den Kurs vom Start bis zum Ende einer Variante.
4
+Fehlerfrei und ohne Hinweis gespielt, wächst der Abstand bis zur nächsten
5
+Wiederholung (1, 3, 7, 14 … Tage). Mit Fehler oder Hinweis ist sie sofort wieder
6
+fällig – kommt aber erst nach den anderen fälligen Linien dran.
7
+
8
+Reine Logik ohne GTK. Gespeichert wird als JSON, pro Kurs (Titel) und Linie
9
+(UCI-Züge, mit Leerzeichen getrennt).
10
+"""
11
+
12
+import datetime
13
+import json
14
+import os
15
+
16
+from . import opening
17
+
18
+LADDER = [1, 3, 7, 14, 30, 60, 120]  # Tage bis zur nächsten Wiederholung, Stufe für Stufe
19
+NEW_PER_DAY = 3  # neue Linien pro Kurs und Tag – Wiederholungen kommen immer dran
20
+
21
+
22
+def lines(course):
23
+    """Alle Linien des Kurses: [(id, [Zug, …])], Hauptvariante zuerst."""
24
+    found = []
25
+
26
+    def walk(board, path, seen):
27
+        options = course.options(board)
28
+        here = opening.key(board)
29
+        if not options or here in seen:
30
+            found.append((" ".join(m.uci() for m in path), list(path)))
31
+            return
32
+        for option in options:
33
+            board.push(option.move)
34
+            walk(board, path + [option.move], seen | {here})
35
+            board.pop()
36
+
37
+    walk(course.start(), [], set())
38
+    return found
39
+
40
+
41
+def _date(text):
42
+    try:
43
+        return datetime.date.fromisoformat(text)
44
+    except (TypeError, ValueError):
45
+        return None
46
+
47
+
48
+class Progress:
49
+    """Lernstand aller Kurse; ``path`` None = nur im Speicher (Tests)."""
50
+
51
+    def __init__(self, path=None):
52
+        self.path = path
53
+        self.data = {}
54
+        if path and os.path.exists(path):
55
+            try:
56
+                with open(path) as fh:
57
+                    loaded = json.load(fh)
58
+                if isinstance(loaded, dict):
59
+                    self.data = loaded
60
+            except (OSError, ValueError):
61
+                self.data = {}
62
+
63
+    def save(self):
64
+        if not self.path:
65
+            return
66
+        os.makedirs(os.path.dirname(self.path), exist_ok=True)
67
+        tmp = self.path + ".tmp"
68
+        with open(tmp, "w") as fh:
69
+            json.dump(self.data, fh, indent=1, sort_keys=True)
70
+        os.replace(tmp, self.path)
71
+
72
+    def card(self, course, line_id):
73
+        return self.data.get(course.title, {}).get(line_id)
74
+
75
+    def _order(self, course, today):
76
+        """Linien nach Dringlichkeit.
77
+
78
+        Gruppen: 0 fällig, 1 neu (bis zum Tageslimit), 2 noch nicht fällig, 3 neu über dem Limit.
79
+        Gruppe 2 und 3 sind freiwilliges Weiterüben, wenn für heute alles geschafft ist.
80
+        """
81
+        cards = self.data.get(course.title, {})
82
+        started = sum(1 for c in cards.values() if c.get("first") == today.isoformat())
83
+        allowance = max(0, NEW_PER_DAY - started)
84
+        ranked = []
85
+        for index, (line_id, moves) in enumerate(lines(course)):
86
+            card = cards.get(line_id)
87
+            if card is None:
88
+                group = 1 if allowance > 0 else 3
89
+                allowance -= group == 1
90
+                ranked.append(((group, datetime.date.min, "", index), line_id, moves))
91
+                continue
92
+            due = _date(card.get("due")) or today
93
+            group = 0 if due <= today else 2
94
+            ranked.append(((group, due, card.get("seen", ""), index), line_id, moves))
95
+        ranked.sort(key=lambda item: item[0])
96
+        return ranked
97
+
98
+    def pick(self, course, today=None):
99
+        """Die fälligste Linie: (id, Züge)."""
100
+        today = today or datetime.date.today()
101
+        _rank, line_id, moves = self._order(course, today)[0]
102
+        return line_id, moves
103
+
104
+    def summary(self, course, today=None):
105
+        """(fällig, neu heute, gesamt) für die Kursauswahl."""
106
+        today = today or datetime.date.today()
107
+        due = new = 0
108
+        ranked = self._order(course, today)
109
+        for rank, _id, _moves in ranked:
110
+            due += rank[0] == 0
111
+            new += rank[0] == 1
112
+        return due, new, len(ranked)
113
+
114
+    def record(self, course, line_id, success, now=None):
115
+        """Ergebnis eintragen; gibt die Tage bis zur nächsten Wiederholung zurück (0 = gleich wieder)."""
116
+        now = now or datetime.datetime.now()
117
+        cards = self.data.setdefault(course.title, {})
118
+        card = cards.setdefault(line_id, {"step": -1, "lapses": 0, "first": now.date().isoformat()})
119
+        if success:
120
+            card["step"] = min(card.get("step", -1) + 1, len(LADDER) - 1)
121
+            days = LADDER[card["step"]]
122
+        else:
123
+            card["step"] = -1
124
+            card["lapses"] = card.get("lapses", 0) + 1
125
+            days = 0
126
+        card["due"] = (now.date() + datetime.timedelta(days=days)).isoformat()
127
+        card["seen"] = now.isoformat(timespec="seconds")
128
+        self.save()
129
+        return days
130
+
131
+
132
+def played_line(course, moves, target=None):
133
+    """Zu welcher Linie gehört eine gespielte Zugfolge? Bevorzugt die Ziellinie."""
134
+    played = " ".join(m.uci() for m in moves)
135
+    all_lines = lines(course)
136
+    ids = [line_id for line_id, _m in all_lines]
137
+    if played in ids:
138
+        return played
139
+    # Zugumstellung: Linie mit derselben Endstellung
140
+    board = course.start()
141
+    for move in moves:
142
+        board.push(move)
143
+    end = opening.key(board)
144
+    matches = []
145
+    for line_id, line_moves in all_lines:
146
+        probe = course.start()
147
+        for move in line_moves:
148
+            probe.push(move)
149
+        if opening.key(probe) == end:
150
+            matches.append(line_id)
151
+    if target in matches or not matches:
152
+        return target
153
+    return matches[0]
154
+
155
+
156
+def next_text(days):
157
+    if days == 0:
158
+        return "Diese Linie kommt bald noch einmal dran."
159
+    if days == 1:
160
+        return "Diese Linie kommt morgen wieder."
161
+    return f"Diese Linie kommt in {days} Tagen wieder."

modified schach/training.py +49 −2

@@ -6,6 +6,7 @@ die dir wirklich begegnen, am häufigsten). Andere Züge werden erklärt und
66
 zurückgenommen: spielbarer Buchzug, kein Buchzug aber in Ordnung, oder Fehler.
77
 """
88
 
9
+import os
910
 import random
1011
 
1112
 import chess
@@ -15,7 +16,7 @@ gi.require_version("Gtk", "4.0")
1516
 gi.require_version("Adw", "1")
1617
 from gi.repository import Adw, GLib, Gtk  # noqa: E402
1718
 
18
-from . import annotate, notation, opening  # noqa: E402
19
+from . import annotate, notation, opening, repetition  # noqa: E402
1920
 from .engines import maia_candidates  # noqa: E402
2021
 
2122
 OPPONENT_DELAY_MS = 650
@@ -36,6 +37,15 @@ def _names():
3637
     return _resources["names"]
3738
 
3839
 
40
+PROGRESS_PATH = os.path.join(GLib.get_user_data_dir(), "schach", "training.json")
41
+
42
+
43
+def progress():
44
+    if "progress" not in _resources:
45
+        _resources["progress"] = repetition.Progress(PROGRESS_PATH)
46
+    return _resources["progress"]
47
+
48
+
3949
 def courses():
4050
     if "courses" not in _resources:
4151
         _resources["courses"] = opening.load_courses()
@@ -46,10 +56,24 @@ def _escape(text):
4656
     return GLib.markup_escape_text(text or "")
4757
 
4858
 
59
+def _due_text(course):
60
+    due, new, total = progress().summary(course)
61
+    if due == 0 and new == 0:
62
+        return f"Für heute geschafft! Du kannst trotzdem weiterüben ({total} Linien im Kurs)."
63
+    parts = []
64
+    if due:
65
+        parts.append(f"{due} zum Wiederholen")
66
+    if new:
67
+        parts.append(f"{new} neu")
68
+    return f"Heute dran: {' und '.join(parts)} (von {total} Linien)."
69
+
70
+
4971
 class OpeningMixin:
5072
     def _opening_init(self):
5173
         self.course = None
5274
         self.course_stats = {"errors": 0, "hints": 0}
75
+        self.course_line = None  # (id, Züge): die Linie, die heute dran ist (Lernkarte)
76
+        self.course_recorded = False
5377
         self.opening_busy = False  # wartet auf Gegnerzug, Bewertung oder Zurücknahme
5478
         self._name_cache = {}
5579
         self.coach_log = []  # Rückmeldungen: {"ply": Halbzug der zugehörigen Stellung, "markup": Text}
@@ -174,7 +198,7 @@ class OpeningMixin:
174198
                 return
175199
             course = shown[row.get_selected()]
176200
             side = "Weiß" if course.color == chess.WHITE else "Schwarz"
177
-            intro.set_label(f"Du spielst {side}. {course.intro}")
201
+            intro.set_label(f"Du spielst {side}. {course.intro}\n\n{_due_text(course)}")
178202
 
179203
         def fill_courses(*_, select=None):
180204
             side = sides[side_row.get_selected()]
@@ -216,6 +240,8 @@ class OpeningMixin:
216240
         self.mode = "opening"
217241
         self.course = course
218242
         self.course_stats = {"errors": 0, "hints": 0}
243
+        self.course_line = progress().pick(course)
244
+        self.course_recorded = False
219245
         self.human = course.color
220246
         self.board = course.start()
221247
         self._reset_game_tables()
@@ -250,6 +276,11 @@ class OpeningMixin:
250276
         gen = self.gen
251277
         board = self.board.copy()
252278
 
279
+        target = self._opening_target(options)
280
+        if target is not None:  # die Linie, die heute dran ist
281
+            GLib.timeout_add(OPPONENT_DELAY_MS, self._opening_reply, gen, target)
282
+            return
283
+
253284
         def pick(moves, _error):
254285
             if gen != self.gen or self.mode != "opening":
255286
                 return
@@ -264,6 +295,15 @@ class OpeningMixin:
264295
 
265296
         self.maia.submit(maia_candidates(board, self.elo, count=8), pick)
266297
 
298
+    def _opening_target(self, options):
299
+        """Kursantwort entlang der heutigen Linie – solange die Partie noch auf ihr ist."""
300
+        if self.course_line is None:
301
+            return None
302
+        played, line = self.board.move_stack, self.course_line[1]
303
+        if len(played) >= len(line) or line[:len(played)] != played:
304
+            return None
305
+        return next((o for o in options if o.move == line[len(played)]), None)
306
+
267307
     def _opening_reply(self, gen, option):
268308
         if gen != self.gen or self.mode != "opening" or option.move not in self.board.legal_moves:
269309
             return False
@@ -368,6 +408,13 @@ class OpeningMixin:
368408
             if hints:
369409
                 parts.append(f"{hints} Hinweis" + ("e" if hints > 1 else ""))
370410
             summary = f"Ziel erreicht – mit {' und '.join(parts)}."
411
+        if not self.course_recorded and self.course is not None:
412
+            self.course_recorded = True  # nach Zurücknehmen und erneutem Ende nicht doppelt zählen
413
+            target = self.course_line[0] if self.course_line else None
414
+            line = repetition.played_line(self.course, self.board.move_stack, target)
415
+            if line is not None:
416
+                days = progress().record(self.course, line, errors == 0 and hints == 0)
417
+                summary = f"{summary} {repetition.next_text(days)}"
371418
         self.final_text = summary
372419
         self._refresh()
373420
         self._coach_show()

added tests/test_repetition.py +96 −0

@@ -0,0 +1,96 @@
1
+import datetime
2
+import os
3
+import tempfile
4
+import unittest
5
+
6
+import chess
7
+
8
+from schach import opening, repetition
9
+
10
+COURSE = """[Event "Mini"]
11
+[SchachColor "white"]
12
+
13
+1. e4 e5 (1... c5 2. Nf3) 2. Nf3 Nc6 (2... d6 3. d4) 3. Bc4 *
14
+"""
15
+
16
+TODAY = datetime.date(2026, 11, 20)
17
+
18
+
19
+def at(day_offset):
20
+    return datetime.datetime.combine(TODAY + datetime.timedelta(days=day_offset), datetime.time(12))
21
+
22
+
23
+class LinesTest(unittest.TestCase):
24
+    def setUp(self):
25
+        self.course = opening.parse_course(COURSE)
26
+
27
+    def test_lines_main_first(self):
28
+        ids = [line_id for line_id, _m in repetition.lines(self.course)]
29
+        self.assertEqual(ids, ["e2e4 e7e5 g1f3 b8c6 f1c4", "e2e4 e7e5 g1f3 d7d6 d2d4", "e2e4 c7c5 g1f3"])
30
+
31
+    def test_real_courses_have_lines(self):
32
+        for course in opening.load_courses():
33
+            self.assertGreater(len(repetition.lines(course)), 1, course.title)
34
+
35
+    def test_played_line_prefers_exact_then_target(self):
36
+        moves = [chess.Move.from_uci(u) for u in "e2e4 c7c5 g1f3".split()]
37
+        self.assertEqual(repetition.played_line(self.course, moves, "x"), "e2e4 c7c5 g1f3")
38
+        self.assertEqual(repetition.played_line(self.course, [], "target"), "target")
39
+
40
+
41
+class ProgressTest(unittest.TestCase):
42
+    def setUp(self):
43
+        self.course = opening.parse_course(COURSE)
44
+        self.progress = repetition.Progress()
45
+        self.main, self.second, self.third = [i for i, _m in repetition.lines(self.course)]
46
+
47
+    def test_new_lines_in_course_order(self):
48
+        self.assertEqual(self.progress.pick(self.course, TODAY)[0], self.main)
49
+        self.assertEqual(self.progress.summary(self.course, TODAY), (0, 3, 3))
50
+
51
+    def test_success_moves_up_the_ladder(self):
52
+        self.assertEqual(self.progress.record(self.course, self.main, True, at(0)), 1)
53
+        self.assertEqual(self.progress.pick(self.course, TODAY)[0], self.second)  # main erst morgen
54
+        self.assertEqual(self.progress.record(self.course, self.main, True, at(1)), 3)
55
+        self.assertEqual(self.progress.record(self.course, self.main, True, at(4)), 7)
56
+
57
+    def test_failure_is_due_again_but_after_other_due_lines(self):
58
+        self.progress.record(self.course, self.second, True, at(-3))  # war vorgestern fällig
59
+        self.assertEqual(self.progress.record(self.course, self.main, False, at(0)), 0)
60
+        self.assertEqual(self.progress.pick(self.course, TODAY)[0], self.second)
61
+        self.progress.record(self.course, self.second, True, at(0))
62
+        self.assertEqual(self.progress.pick(self.course, TODAY)[0], self.main)  # vor neuen Linien
63
+        self.assertEqual(self.progress.summary(self.course, TODAY), (1, 1, 3))
64
+
65
+    def test_failure_resets_ladder(self):
66
+        for day in (0, 1, 4):
67
+            self.progress.record(self.course, self.main, True, at(day))
68
+        self.progress.record(self.course, self.main, False, at(11))
69
+        self.assertEqual(self.progress.record(self.course, self.main, True, at(11)), 1)
70
+        self.assertEqual(self.progress.card(self.course, self.main)["lapses"], 1)
71
+
72
+    def test_new_lines_limited_per_day(self):
73
+        course = opening.load_courses()[0]
74
+        progress = repetition.Progress()
75
+        ids = [i for i, _m in repetition.lines(course)]
76
+        self.assertGreater(len(ids), repetition.NEW_PER_DAY)
77
+        self.assertEqual(progress.summary(course, TODAY)[1], repetition.NEW_PER_DAY)
78
+        for line_id in ids[:repetition.NEW_PER_DAY]:
79
+            progress.record(course, line_id, True, at(0))
80
+        due, new, _total = progress.summary(course, TODAY)
81
+        self.assertEqual((due, new), (0, 0))  # für heute geschafft
82
+        self.assertIn(progress.pick(course, TODAY)[0], ids[:repetition.NEW_PER_DAY])  # weiterüben: Bekanntes
83
+        self.assertEqual(progress.summary(course, TODAY + datetime.timedelta(days=1))[:2],
84
+                         (repetition.NEW_PER_DAY, repetition.NEW_PER_DAY))
85
+
86
+    def test_saved_and_loaded(self):
87
+        with tempfile.TemporaryDirectory() as tmp:
88
+            path = os.path.join(tmp, "sub", "training.json")
89
+            progress = repetition.Progress(path)
90
+            progress.record(self.course, self.main, True, at(0))
91
+            again = repetition.Progress(path)
92
+            self.assertEqual(again.card(self.course, self.main)["due"], "2026-11-21")
93
+
94
+
95
+if __name__ == "__main__":
96
+    unittest.main()