Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(training): draw [%cal]/[%csl] arrows from course comments

public

feat(training): draw [%cal]/[%csl] arrows from course comments

Arrows show while their coach comment is visible, also when paging
back. Commands are stripped from the displayed text.

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

modified schach/diagram.py +19 −0

@@ -50,6 +50,9 @@ DEFAULT_SCHEME = "holz"
5050
 HINT = (0.21, 0.52, 0.89)
5151
 THREAT = (0.91, 0.36, 0.11)
5252
 CHECK = (0.88, 0.11, 0.14)
53
+# Farben der Kurs-Pfeile ([%cal]/[%csl]), wie bei Lichess
54
+SHAPE_COLORS = {"green": (0.08, 0.55, 0.20), "red": (0.80, 0.13, 0.13),
55
+                "blue": (0.10, 0.35, 0.80), "yellow": (0.90, 0.60, 0.0)}
5356
 BADGE = {
5457
     "!!": (0.10, 0.62, 0.55),
5558
     "!": (0.30, 0.52, 0.80),
@@ -124,6 +127,7 @@ class BoardPainter:
124127
         self.clocks = None  # {Farbe: Millisekunden}
125128
         self.clock_running = None  # Farbe, deren Uhr gerade läuft
126129
         self.turn_marker = None  # Farbe, deren Name fett steht (wer am Zug ist, bei zwei Spielern)
130
+        self.shapes = ()  # Pfeile und Felder aus Kurskommentaren: ((von, nach, Farbe), …)
127131
         self.preview = None  # Zug, der halb durchsichtig gezeigt wird (Explorer: Maus über einer Zeile)
128132
         self.editing = False  # Stellung aufbauen: keine geschlagenen Figuren anzeigen
129133
         self.eval_bar = None  # Gewinnchance Weiß in Prozent: Balken links neben dem Brett
@@ -253,6 +257,12 @@ class BoardPainter:
253257
 
254258
         if self.threat_from is not None and self.threat_to is not None:
255259
             self._draw_arrow(cr, self.threat_from, self.threat_to, sq, THREAT)
260
+        for tail, head, color in self.shapes:
261
+            rgb = SHAPE_COLORS.get(color, SHAPE_COLORS["green"])
262
+            if tail == head:
263
+                self._ring(cr, tail, sq, rgb)
264
+            else:
265
+                self._draw_arrow(cr, tail, head, sq, rgb)
256266
 
257267
         if self.strips:
258268
             if not self.editing:
@@ -294,6 +304,15 @@ class BoardPainter:
294304
         cr.rectangle(x + inset, y + inset, sq - 2 * inset, sq - 2 * inset)
295305
         cr.stroke()
296306
 
307
+    def _ring(self, cr, square, sq, rgb):
308
+        """Markiertes Feld: Kreis wie bei Lichess."""
309
+        x, y = self._square_origin(square)
310
+        cr.new_path()
311
+        cr.set_source_rgba(*rgb, 0.85)
312
+        cr.set_line_width(sq * 0.08)
313
+        cr.arc(x + sq / 2, y + sq / 2, sq * 0.42, 0, 2 * math.pi)
314
+        cr.stroke()
315
+
297316
     def _draw_arrow(self, cr, src, dst, sq, rgb):
298317
         x0, y0 = self._square_origin(src)
299318
         x1, y1 = self._square_origin(dst)

modified schach/opening.py +20 −4

@@ -32,6 +32,7 @@ class Option:
3232
     move: chess.Move
3333
     comment: str
3434
     main: bool  # Hauptvariante (sonst Nebenvariante)
35
+    shapes: tuple = ()  # Pfeile und Felder aus [%cal]/[%csl]: ((von, nach, Farbe), …), Feld: von == nach
3536
 
3637
 
3738
 @dataclasses.dataclass
@@ -39,11 +40,12 @@ class Course:
3940
     title: str
4041
     color: bool
4142
     intro: str
42
-    welcome: str  # Kommentar vor dem ersten Zug
43
+    welcome: str  # Kommentar vor dem ersten Zug (ohne [%cal]/[%csl])
4344
     start_fen: str
4445
     positions: dict  # Stellungs-Hash -> [Option], Hauptvariante zuerst
4546
     reached: set  # alle Stellungs-Hashes, die im Kurs vorkommen (auch Endstellungen)
4647
     path: str = ""
48
+    welcome_shapes: tuple = ()
4749
 
4850
     def start(self):
4951
         return chess.Board(self.start_fen)
@@ -58,6 +60,18 @@ class Course:
5860
         return key(board) in self.reached
5961
 
6062
 
63
+COMMAND_RE = re.compile(r"\[%[^\]]*\]")
64
+
65
+
66
+def clean_comment(text):
67
+    """Kommentar ohne PGN-Befehle wie [%cal Gc4f7], Leerraum zusammengefasst."""
68
+    return " ".join(COMMAND_RE.sub(" ", text or "").split())
69
+
70
+
71
+def shapes(node):
72
+    return tuple((a.tail, a.head, a.color) for a in node.arrows())
73
+
74
+
6175
 def parse_course(text, path=""):
6276
     game = chess.pgn.read_game(io.StringIO(text))
6377
     if game is None:
@@ -73,11 +87,12 @@ def parse_course(text, path=""):
7387
         for index, child in enumerate(node.variations):
7488
             options = positions.setdefault(key(board), [])
7589
             existing = next((o for o in options if o.move == child.move), None)
76
-            comment = " ".join(child.comment.split())
90
+            comment = clean_comment(child.comment)
7791
             if existing is None:
78
-                options.append(Option(child.move, comment, index == 0))
92
+                options.append(Option(child.move, comment, index == 0, shapes(child)))
7993
             elif not existing.comment:
8094
                 existing.comment = comment
95
+                existing.shapes = shapes(child)
8196
             walk(child)
8297
 
8398
     walk(game)
@@ -88,7 +103,8 @@ def parse_course(text, path=""):
88103
         title=headers.get("Event", "Kurs"),
89104
         color=color,
90105
         intro=headers.get("SchachIntro", ""),
91
-        welcome=" ".join(game.comment.split()),
106
+        welcome=clean_comment(game.comment),
107
+        welcome_shapes=shapes(game),
92108
         start_fen=game.board().fen(),
93109
         positions=positions,
94110
         reached=reached,

modified schach/training.py +15 −6

@@ -116,9 +116,13 @@ class OpeningMixin:
116116
         self.coach = Gtk.Revealer(child=card, transition_type=Gtk.RevealerTransitionType.SLIDE_UP)
117117
         return self.coach
118118
 
119
-    def _coach(self, markup, ply=None, replace=False):
120
-        """Neue Rückmeldung zur Stellung nach Halbzug ``ply`` (Standard: aktuelle Stellung)."""
121
-        entry = {"ply": len(self.board.move_stack) - 1 if ply is None else ply, "markup": markup}
119
+    def _coach(self, markup, ply=None, replace=False, shapes=()):
120
+        """Neue Rückmeldung zur Stellung nach Halbzug ``ply`` (Standard: aktuelle Stellung).
121
+
122
+        ``shapes``: Pfeile und Felder aus dem Kurskommentar, solange diese Rückmeldung zu sehen ist.
123
+        """
124
+        entry = {"ply": len(self.board.move_stack) - 1 if ply is None else ply, "markup": markup,
125
+                 "shapes": tuple(shapes)}
122126
         if replace and self.coach_log:
123127
             self.coach_log[-1] = entry
124128
         else:
@@ -130,10 +134,13 @@ class OpeningMixin:
130134
     def _coach_show(self):
131135
         if not self.coach_log:
132136
             self.coach.set_reveal_child(False)
137
+            self.view.shapes = ()
133138
             return
134139
         last = len(self.coach_log) - 1
135140
         index = last if self.coach_index is None else self.coach_index
136141
         self.coach_label.set_markup(self.coach_log[index]["markup"])
142
+        self.view.shapes = self.coach_log[index].get("shapes", ())
143
+        self.view.queue_draw()
137144
         self.coach_nav.set_visible(last > 0)
138145
         self.coach_prev.set_sensitive(index > 0)
139146
         self.coach_next.set_sensitive(index < last)
@@ -255,7 +262,7 @@ class OpeningMixin:
255262
         self.list_btn.set_active(False)
256263
         self.coach_log = []
257264
         welcome = _escape(notation.text(course.welcome or course.intro, self._notation()))
258
-        self._coach(f"{welcome}\n<b>{_escape(self._opening_line_text())}</b>")
265
+        self._coach(f"{welcome}\n<b>{_escape(self._opening_line_text())}</b>", shapes=course.welcome_shapes)
259266
         self._changed()
260267
         self._refresh()
261268
         self._opening_next_step()
@@ -265,6 +272,7 @@ class OpeningMixin:
265272
         self.opening_busy = False
266273
         self.coach_log = []
267274
         self.coach_index = None
275
+        self.view.shapes = ()
268276
         self.coach.set_reveal_child(False)
269277
         self.coach_button.set_visible(False)
270278
 
@@ -331,7 +339,7 @@ class OpeningMixin:
331339
         self.opening_busy = False
332340
         self._changed()
333341
         comment = f" – {_escape(notation.text(option.comment, self._notation()))}" if option.comment else ""
334
-        self._coach(f"<b>{_escape(label)}</b>{comment}")
342
+        self._coach(f"<b>{_escape(label)}</b>{comment}", shapes=option.shapes)
335343
         self._refresh()
336344
         if not self.course.options(self.board):
337345
             self._opening_finished()
@@ -352,7 +360,8 @@ class OpeningMixin:
352360
                 comment = verdict.option.comment or "Genau so."
353361
             else:
354362
                 comment = "Zugumstellung – auch so kommst du zu unserem Ziel."
355
-            self._coach(f"✓ <b>{label}</b> – {_escape(notation.text(comment, self._notation()))}")
363
+            self._coach(f"✓ <b>{label}</b> – {_escape(notation.text(comment, self._notation()))}",
364
+                        shapes=verdict.option.shapes if verdict.option else ())
356365
             self._refresh()
357366
             self._opening_next_step()
358367
             return

modified tests/test_opening.py +9 −0

@@ -34,6 +34,15 @@ class CourseTest(unittest.TestCase):
3434
         for course in self.courses.values():
3535
             self.assertIn(opening.key(course.start()), course.positions)
3636
 
37
+    def test_arrows_parsed_and_hidden_from_text(self):
38
+        course = opening.parse_course(
39
+            '[Event "T"]\n\n{ Start [%csl Re4] } 1. e4 { Zentrum! [%cal Gd1h5,Gf1c4] } *')
40
+        option = course.options(chess.Board())[0]
41
+        self.assertEqual(option.comment, "Zentrum!")
42
+        self.assertEqual(option.shapes, ((chess.D1, chess.H5, "green"), (chess.F1, chess.C4, "green")))
43
+        self.assertEqual(course.welcome, "Start")
44
+        self.assertEqual(course.welcome_shapes, ((chess.E4, chess.E4, "red"),))
45
+
3746
     def test_options_main_first(self):
3847
         italian = self.courses["Italienisch"]
3948
         options = italian.options(play("e4", "e5", "Nf3", "Nc6", "Bc4"))