Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(coach): hovered square names light up on the board

public

feat(coach): hovered square names light up on the board

Square names in coach text get a pale gold box; hovering one lights
its file and rank faintly and the square itself strongly, so a
beginner learns to read coordinates.

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

modified schach/diagram.py +12 −0

@@ -62,6 +62,7 @@ DEFAULT_SCHEME = "holz"
6262
 HINT = (0.21, 0.52, 0.89)
6363
 THREAT = (0.91, 0.36, 0.11)
6464
 CHECK = (0.88, 0.11, 0.14)
65
+SPOTLIGHT = (0.96, 0.76, 0.10)  # Feld, dessen Name im Kommentar unter der Maus liegt
6566
 # Farben der Kurs-Pfeile ([%cal]/[%csl]), wie bei Lichess
6667
 SHAPE_COLORS = {"green": (0.08, 0.55, 0.20), "red": (0.80, 0.13, 0.13),
6768
                 "blue": (0.10, 0.35, 0.80), "yellow": (0.90, 0.60, 0.0)}
@@ -150,6 +151,7 @@ class BoardPainter:
150151
         self.clocks = None  # {Farbe: Millisekunden}
151152
         self.clock_running = None  # Farbe, deren Uhr gerade läuft
152153
         self.turn_marker = None  # Farbe, deren Name fett steht (wer am Zug ist, bei zwei Spielern)
154
+        self.spotlight = None  # Feld, das gerade im Text gezeigt wird (Maus über „e4“)
153155
         self.shapes = ()  # Pfeile und Felder aus Kurskommentaren: ((von, nach, Farbe), …)
154156
         self.preview = None  # Zug, der halb durchsichtig gezeigt wird (Explorer: Maus über einer Zeile)
155157
         self.editing = False  # Stellung aufbauen: keine geschlagenen Figuren anzeigen
@@ -242,6 +244,16 @@ class BoardPainter:
242244
         for s in (self.threat_from, self.threat_to):
243245
             if s is not None:
244246
                 self._mark(cr, s, sq, THREAT)
247
+        if self.spotlight is not None:
248
+            # Spalte und Zeile blass, das Feld im Schnittpunkt kräftig: so liest man Koordinaten
249
+            file, rank = chess.square_file(self.spotlight), chess.square_rank(self.spotlight)
250
+            cr.set_source_rgba(*SPOTLIGHT, 0.22)
251
+            for s in chess.SQUARES:
252
+                if s != self.spotlight and (chess.square_file(s) == file or chess.square_rank(s) == rank):
253
+                    x, y = self._square_origin(s)
254
+                    cr.rectangle(x, y, sq, sq)
255
+            cr.fill()
256
+            self._mark(cr, self.spotlight, sq, SPOTLIGHT)
245257
 
246258
         self._draw_coordinates(cr, sq)
247259
 

modified schach/training.py +61 −4

@@ -8,13 +8,14 @@ zurückgenommen: spielbarer Buchzug, kein Buchzug aber in Ordnung, oder Fehler.
88
 
99
 import os
1010
 import random
11
+import re
1112
 
1213
 import chess
1314
 import gi
1415
 
1516
 gi.require_version("Gtk", "4.0")
1617
 gi.require_version("Adw", "1")
17
-from gi.repository import Adw, Gio, GLib, Gtk  # noqa: E402
18
+from gi.repository import Adw, Gio, GLib, Gtk, Pango  # noqa: E402
1819
 
1920
 from . import annotate, notation, opening, repetition  # noqa: E402
2021
 from .engines import maia_candidates  # noqa: E402
@@ -77,6 +78,52 @@ def _due_text(course):
7778
     return f"Heute dran: {' und '.join(parts)} (von {total} Linien)."
7879
 
7980
 
81
+PIECE_LETTERS = "KQRBNDTLS"  # deutsch und englisch
82
+SQUARE_RE = re.compile(r"[a-h][1-8](?![0-9A-Za-zäöüß])")
83
+
84
+
85
+def squares_in(text):
86
+    """Feldnamen im Text: [(Anfang, Ende, Feld)]. „e4“, „Lc4“, „Sxe5“, „Sbd2“ – aber nicht „Ende4“."""
87
+    found = []
88
+    for match in SQUARE_RE.finditer(text):
89
+        start = match.start()
90
+        before = text[start - 1] if start else " "
91
+        if before in "abcdefgh":  # nur als Zusatz wie in „Sbd2“: davor muss eine Figur stehen
92
+            if start < 2 or text[start - 2] not in PIECE_LETTERS:
93
+                continue
94
+        elif before.isalnum() and before not in PIECE_LETTERS + "x":
95
+            continue
96
+        found.append((match.start(), match.end(), chess.parse_square(match.group())))
97
+    return found
98
+
99
+
100
+TAG_RE = re.compile(r"(<[^>]*>)")
101
+
102
+
103
+def mark_squares(markup):
104
+    """Feldnamen im Pango-Markup blassgelb hinterlegen – wie das goldene Leuchten auf dem Brett."""
105
+    parts = TAG_RE.split(markup)
106
+    for i in range(0, len(parts), 2):  # gerade Stellen sind Text, ungerade Tags
107
+        text = parts[i]
108
+        for start, end, _sq in reversed(squares_in(text)):
109
+            text = (f"{text[:start]}<span bgcolor='#f5c219' bgalpha='35%'>{text[start:end]}</span>"
110
+                    f"{text[end:]}")
111
+        parts[i] = text
112
+    return "".join(parts)
113
+
114
+
115
+def square_at(label, x, y):
116
+    """Feld, dessen Name im Label an der Stelle (x, y) steht – oder None."""
117
+    layout = label.get_layout()
118
+    ox, oy = label.get_layout_offsets()
119
+    inside, index, _trailing = layout.xy_to_index(int((x - ox) * Pango.SCALE), int((y - oy) * Pango.SCALE))
120
+    if not inside:
121
+        return None
122
+    text = layout.get_text()
123
+    char = len(text.encode()[:index].decode(errors="ignore"))
124
+    return next((square for start, end, square in squares_in(text) if start <= char < end), None)
125
+
126
+
80127
 class OpeningMixin:
81128
     def _opening_init(self):
82129
         self.course = None
@@ -101,6 +148,11 @@ class OpeningMixin:
101148
         three_lines = self.coach_label.create_pango_layout("Ag\nAg\nAg").get_pixel_size()[1]
102149
         self.coach_label.set_size_request(-1, three_lines)
103150
         self.coach_label.set_valign(Gtk.Align.CENTER)
151
+        # Maus über einem Feldnamen („e4“, auch in „Lc4“): das Feld leuchtet auf dem Brett
152
+        motion = Gtk.EventControllerMotion()
153
+        motion.connect("motion", lambda _c, x, y: self._coach_spotlight(square_at(self.coach_label, x, y)))
154
+        motion.connect("leave", lambda _c: self._coach_spotlight(None))
155
+        self.coach_label.add_controller(motion)
104156
         self.coach_button = Gtk.Button(
105157
             label="Gegen Maia weiterspielen", valign=Gtk.Align.CENTER, visible=False, margin_end=10,
106158
         )
@@ -139,6 +191,11 @@ class OpeningMixin:
139191
         self.coach = Gtk.Revealer(child=card, transition_type=Gtk.RevealerTransitionType.SLIDE_UP)
140192
         return self.coach
141193
 
194
+    def _coach_spotlight(self, square):
195
+        if self.view.spotlight != square:
196
+            self.view.spotlight = square
197
+            self.view.queue_draw()
198
+
142199
     def _coach(self, markup, ply=None, replace=False, shapes=(), demos=()):
143200
         """Neue Rückmeldung zur Stellung nach Halbzug ``ply`` (Standard: aktuelle Stellung).
144201
 
@@ -167,7 +224,7 @@ class OpeningMixin:
167224
             return
168225
         last = len(self.coach_log) - 1
169226
         index = last if self.coach_index is None else self.coach_index
170
-        self.coach_label.set_markup(self.coach_log[index]["markup"])
227
+        self.coach_label.set_markup(mark_squares(self.coach_log[index]["markup"]))
171228
         self.view.shapes = self.coach_log[index].get("shapes", ())
172229
         self.view.queue_draw()
173230
         self.coach_nav.set_visible(last > 0)
@@ -282,9 +339,9 @@ class OpeningMixin:
282339
         before = demo.board_at(index - 1)
283340
         label = _escape(notation.label(before, move, self._notation()))
284341
         text = _escape(notation.text(comment, self._notation()))
285
-        self.coach_label.set_markup(
342
+        self.coach_label.set_markup(mark_squares(
286343
             f"<span alpha='70%'>{_escape(self.demo['label'])} · {index + 1}/{len(demo.steps)}</span>\n"
287
-            f"<b>{label}</b>" + (f" – {text}" if text else ""))
344
+            f"<b>{label}</b>" + (f" – {text}" if text else "")))
288345
         self.coach_nav.set_visible(True)
289346
         self.coach_prev.set_sensitive(index > 0)
290347
         self.coach_next.set_sensitive(index < len(demo.steps) - 1)

modified tests/test_opening.py +16 −0

@@ -201,3 +201,19 @@ class BooksTest(unittest.TestCase):
201201
         self.assertEqual(books.books, [])
202202
         self.assertEqual(books.moves(chess.Board()), [])
203203
         self.assertFalse(books.contains(chess.Board(), self.e4))
204
+
205
+
206
+class SquareNamesTest(unittest.TestCase):
207
+    def test_squares_in_comment(self):
208
+        from schach.training import squares_in
209
+        text = "Lc4 zielt auf f7. Sxe5, Sbd2 und e4 – aber nicht Ende4 oder a10. Die f7-Schwäche!"
210
+        found = [(text[a:b], chess.square_name(sq)) for a, b, sq in squares_in(text)]
211
+        self.assertEqual(found, [("c4", "c4"), ("f7", "f7"), ("e5", "e5"), ("d2", "d2"), ("e4", "e4"),
212
+                                 ("f7", "f7")])
213
+
214
+    def test_mark_squares_leaves_tags_alone(self):
215
+        from schach.training import mark_squares
216
+        out = mark_squares("<span alpha='70%'>Warum?</span>\n<b>3. Lc4</b> – auf f7")
217
+        self.assertIn("<span alpha='70%'>Warum?</span>", out)
218
+        self.assertEqual(out.count("bgcolor"), 2)
219
+        self.assertIn(">c4</span></b>", out)