Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(savegames): ratings at game time and Maia's bars in the PGN

public

feat(savegames): ratings at game time and Maia's bars in the PGN

Saved games carry the known ratings as WhiteElo/BlackElo (only what is
known: without a Lichess login just Maia's side, two players nothing) and
Maia's win/draw/loss after each move as [%wdl ...]. On loading, the stored
ratings decide which Elo Maia's bars are for (missing sides: Maia's
strength), so an old game no longer changes with today's rating, a pasted
Lichess game uses its real ratings, and the stored bars appear at once;
Maia only computes what is missing.

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

modified schach/app.py +46 −2

@@ -169,6 +169,7 @@ class Window(OnlineMixin, PuzzleMixin, O
169169
         self._autosave_source = 0
170170
         self.evals = {}  # Halbzug-Index -> Gewinnchance Weiß (%) nach diesem Zug
171171
         self.maia_wdls = {}  # (FEN, Elo Weiß, Elo Schwarz) -> W/R/N von Maia aus Sicht von Weiß (Zugliste)
172
+        self.ratings = (None, None)  # bekannte Wertungen (Weiß, Schwarz) aus dem Spielstand, siehe _wdl_elos
172173
         self.maia_wdl_pending = None  # Schlüssel, den Maia gerade rechnet (immer nur einer, s. _wdl_for)
173174
         self.maia_wdl_failed = {}  # Schlüssel -> fehlgeschlagene Versuche (s. MAIA_WDL_TRIES)
174175
         self.times = {}  # Halbzug-Index -> Bedenkzeit für diesen Zug (ms), siehe _track_time
@@ -608,6 +609,7 @@ class Window(OnlineMixin, PuzzleMixin, O
608609
         self.final_text = None
609610
 
610611
     def _reset_game_tables(self):
612
+        self.ratings = (None, None)
611613
         self.symbols.clear()
612614
         self.analyses.clear()
613615
         self.pending_symbols.clear()
@@ -1654,14 +1656,52 @@ class Window(OnlineMixin, PuzzleMixin, O
16541656
         return None  # bis Maia antwortet: kein Stockfish-Balken, der dann umspränge
16551657
 
16561658
     def _wdl_elos(self):
1657
-        """(Elo Weiß, Elo Schwarz) für Maias Schätzung: Maia wie eingestellt; mit Lichess-Anmeldung zählt
1658
-        für die Seite des Menschen die eigene Lichess-Wertung für Partien, sonst beide wie Maia."""
1659
+        """(Elo Weiß, Elo Schwarz) für Maias Schätzung. Stehen im Spielstand Wertungen (PGN-Tags
1660
+        WhiteElo/BlackElo, zur Zeit der Partie), gelten sie; fehlende Seiten füllt Maias Stärke auf.
1661
+        Sonst: Maia wie eingestellt; mit Lichess-Anmeldung zählt für die Seite des Menschen die eigene
1662
+        Lichess-Wertung für Partien, sonst beide wie Maia."""
16591663
         maia = self._opponent_elo() or int(self.settings["elo"])
1664
+        if any(self.ratings):
1665
+            return tuple(rating or maia for rating in self.ratings)
16601666
         rating = lichess.game_rating(self.get_application().lichess_user)
16611667
         if rating is None or self.mode == "duo" or self.names:
16621668
             return maia, maia  # ohne Anmeldung, zu zweit am Brett oder fremde Partie: symmetrisch
16631669
         return (rating, maia) if self.human == chess.WHITE else (maia, rating)
16641670
 
1671
+    def _save_ratings(self):
1672
+        """Wertungen für den Spielstand: so, dass _wdl_elos beim Laden dieselben Elo-Zahlen ergibt wie
1673
+        jetzt (sonst passten die gespeicherten Balken nicht). Nur Bekanntes, nichts Erfundenes: ohne
1674
+        Lichess-Anmeldung steht nur Maias Seite da, zu zweit nichts."""
1675
+        if any(self.ratings):
1676
+            return tuple(self.ratings)
1677
+        if self.mode != "maia" or self.names:
1678
+            return None, None
1679
+        white, black = self._wdl_elos()
1680
+        mine = lichess.game_rating(self.get_application().lichess_user)
1681
+        if self.human == chess.WHITE:
1682
+            return mine, black
1683
+        return white, mine
1684
+
1685
+    def _save_wdls(self):
1686
+        """Maias Balken nach jedem Zug der Partie, soweit gerechnet: {Halbzug: (G, R, V)}."""
1687
+        elos, found, board = self._wdl_elos(), {}, self.board.root()
1688
+        for ply, move in enumerate(self.board.move_stack):
1689
+            board.push(move)
1690
+            value = self.maia_wdls.get((board.fen(), *elos))
1691
+            if value:
1692
+                found[ply] = tuple(value)
1693
+        return found
1694
+
1695
+    def _wdl_preload(self, wdls):
1696
+        """Gespeicherte Balken aus dem Spielstand übernehmen: Maia rechnet nur, was fehlt."""
1697
+        if not wdls:
1698
+            return
1699
+        elos, board = self._wdl_elos(), self.board.root()
1700
+        for ply, move in enumerate(self.board.move_stack):
1701
+            board.push(move)
1702
+            if ply in wdls:
1703
+                self.maia_wdls.setdefault((board.fen(), *elos), tuple(wdls[ply]))
1704
+
16651705
     def _evals_locked(self):
16661706
         """Während der Online-Partie bzw. vor der Lösung eines Rätsels keine Engine-Bewertung."""
16671707
         return not sicht.allowed(self.mode, "evals", self._over())
@@ -2271,6 +2311,8 @@ class Window(OnlineMixin, PuzzleMixin, O
22712311
             takebacks={p: list(v) for p, v in self.takebacks.items()},
22722312
             times=dict(self.times),
22732313
             shapes=self._game_shapes() if variations else {},
2314
+            ratings=self._save_ratings(),
2315
+            wdls=self._save_wdls(),
22742316
         )
22752317
 
22762318
     def load_state(self, state):
@@ -2283,6 +2325,8 @@ class Window(OnlineMixin, PuzzleMixin, O
22832325
         self.elo = state.elo or int(self.settings["elo"])
22842326
         self.board = state.board.copy()
22852327
         self._reset_game_tables()
2328
+        self.ratings = tuple(state.ratings)
2329
+        self._wdl_preload(state.wdls)
22862330
         self.eval_requested = set()
22872331
         self.symbols = dict(state.symbols)
22882332
         self.evals = dict(state.evals)

modified schach/clipboard.py +2 −1

@@ -105,12 +105,13 @@ def _pgn(text, elo, username):
105105
         state = savegames.GameState(
106106
             board=board, human=human, elo=elo, mode="review", opponent=opponent, final_text=final,
107107
             name=headers.get("Event", "") if headers.get("Event", "?") != "?" else "",
108
-            variations=variations, takebacks=takebacks,
108
+            variations=variations, takebacks=takebacks, ratings=savegames.read_ratings(headers),
109109
         )
110110
     else:
111111
         state = savegames.GameState(
112112
             board=board, human=chess.WHITE, elo=elo, mode="review", final_text=final,
113113
             names=(white, black), name=_title(headers), variations=variations, takebacks=takebacks,
114
+            ratings=savegames.read_ratings(headers),
114115
         )
115116
     if not moves:
116117
         # nur eine Stellung (PGN mit FEN-Kopf): gegen Maia weiterspielen

modified schach/savegames.py +30 −1

@@ -25,6 +25,7 @@ AUTOSAVE_PATH = os.path.join(DATA_DIR, "
2525
 
2626
 SYMBOL_FOR_NAG = {nag: symbol for symbol, nag in NAG.items()}
2727
 WP_RE = re.compile(r"\[%wp ([0-9.]+)\]")
28
+WDL_RE = re.compile(r"\[%wdl ([0-9.]+) ([0-9.]+) ([0-9.]+)\]")  # Maias Gewinn/Remis/Verlust aus Sicht von Weiß
2829
 
2930
 
3031
 @dataclasses.dataclass
@@ -50,6 +51,12 @@ class GameState:
5051
     times: dict = dataclasses.field(default_factory=dict)  # Halbzug-Index -> Bedenkzeit für diesen Zug (ms)
5152
     # Selbst gezeichnete Pfeile und Kreise an der Partie: {Halbzug: ((von, nach, Farbe), …)}, -1 = Anfang
5253
     shapes: dict = dataclasses.field(default_factory=dict)
54
+    # Bekannte Wertungen (Weiß, Schwarz) zur Zeit der Partie, PGN-Tags WhiteElo/BlackElo; None: unbekannt.
55
+    # Für Maias Balken maßgeblich, fehlende Seiten füllt Maias Stärke auf (Window._wdl_elos).
56
+    ratings: tuple = (None, None)
57
+    # Maias Balken nach jedem Zug der Partie: {Halbzug: (Gewinn, Remis, Verlust) aus Sicht von Weiß},
58
+    # gerechnet für die Elo-Zahlen aus ``ratings`` (im PGN als [%wdl …] am Zug)
59
+    wdls: dict = dataclasses.field(default_factory=dict)
5360
 
5461
     def truncated(self, ply):
5562
         """Kopie bis einschließlich Halbzug ``ply`` (für Abzweigungen)."""
@@ -95,6 +102,9 @@ def to_pgn(state):
95102
         game.headers["SchachOpponent"] = state.opponent
96103
     if state.final_text:
97104
         game.headers["SchachEnd"] = state.final_text
105
+    for tag, rating in zip(("WhiteElo", "BlackElo"), state.ratings):
106
+        if rating:
107
+            game.headers[tag] = str(rating)
98108
     root = state.board.root()
99109
     if root.fen() != chess.STARTING_FEN:
100110
         game.setup(root)
@@ -107,6 +117,9 @@ def to_pgn(state):
107117
             node.nags.add(NAG[state.symbols[ply]])
108118
         if ply in state.evals:
109119
             node.comment = f"[%wp {state.evals[ply]:.1f}]"
120
+        if state.wdls.get(ply):
121
+            node.comment = (node.comment + " " if node.comment else "") + "[%wdl {:.3f} {:.3f} {:.3f}]".format(
122
+                *state.wdls[ply])
110123
         if ply in state.times:
111124
             node.set_emt(round(state.times[ply] / 1000, 1))  # [%emt 0:00:03.5]
112125
     for ply, shapes in state.shapes.items():
@@ -275,7 +288,7 @@ def from_pgn(text, path=""):
275288
         raise ValueError("Keine Partie in der Datei")
276289
     headers = game.headers
277290
     board = game.board()
278
-    symbols, evals = {}, {}
291
+    symbols, evals, wdls = {}, {}, {}
279292
     times = read_times(game)
280293
     shapes = {-1: read_shapes(game)} if game.arrows() else {}
281294
     for ply, node in enumerate(game.mainline()):
@@ -288,6 +301,9 @@ def from_pgn(text, path=""):
288301
         match = WP_RE.search(node.comment or "")
289302
         if match:
290303
             evals[ply] = float(match.group(1))
304
+        match = WDL_RE.search(node.comment or "")
305
+        if match:
306
+            wdls[ply] = tuple(float(x) for x in match.groups())
291307
     human = chess.BLACK if headers.get("SchachHuman") == "black" else chess.WHITE
292308
     try:
293309
         elo = int(headers.get("SchachElo", "1200"))
@@ -305,9 +321,22 @@ def from_pgn(text, path=""):
305321
         takebacks=takebacks,
306322
         times=times,
307323
         shapes=shapes,
324
+        ratings=read_ratings(headers),
325
+        wdls=wdls,
308326
     )
309327
 
310328
 
329
+def read_ratings(headers):
330
+    """(Elo Weiß, Elo Schwarz) aus den PGN-Tags WhiteElo/BlackElo; None, wo sie fehlen oder „?“ sind."""
331
+    def rating(tag):
332
+        try:
333
+            value = int(headers.get(tag, ""))
334
+        except ValueError:
335
+            return None
336
+        return value if value > 0 else None
337
+    return rating("WhiteElo"), rating("BlackElo")
338
+
339
+
311340
 def _write(path, text):
312341
     os.makedirs(os.path.dirname(path), exist_ok=True)
313342
     tmp = path + ".tmp"

added tests/test_elo.py +101 −0

@@ -0,0 +1,101 @@
1
+"""Wertungen im Spielstand (PGN-Tags WhiteElo/BlackElo) und Maias Balken als [%wdl …]: Beim Laden
2
+gelten die Elo-Zahlen zur Zeit der Partie, und die gespeicherten Balken sind sofort da."""
3
+
4
+import unittest
5
+
6
+import chess
7
+
8
+from schach import app, clipboard, savegames
9
+
10
+WDL = (0.45, 0.30, 0.25)
11
+
12
+
13
+def played(*sans):
14
+    board = chess.Board()
15
+    for san in sans:
16
+        board.push_san(san)
17
+    return board
18
+
19
+
20
+class PgnTest(unittest.TestCase):
21
+    def test_ratings_and_bars_round_trip(self):
22
+        state = savegames.GameState(board=played("e4", "e5"), human=chess.WHITE, elo=1100,
23
+                                    ratings=(1640, 1100), wdls={0: WDL})
24
+        text = savegames.to_pgn(state)
25
+        self.assertIn('[WhiteElo "1640"]', text)
26
+        self.assertIn("[%wdl 0.450 0.300 0.250]", text)
27
+        loaded = savegames.from_pgn(text)
28
+        self.assertEqual(loaded.ratings, (1640, 1100))
29
+        self.assertEqual(loaded.wdls, {0: WDL})
30
+
31
+    def test_unknown_side_is_not_written(self):
32
+        state = savegames.GameState(board=played("e4"), human=chess.WHITE, elo=1100, ratings=(None, 1100))
33
+        text = savegames.to_pgn(state)
34
+        self.assertNotIn("WhiteElo", text)
35
+        self.assertEqual(savegames.from_pgn(text).ratings, (None, 1100))
36
+
37
+    def test_question_mark_is_unknown(self):
38
+        self.assertEqual(savegames.read_ratings({"WhiteElo": "?", "BlackElo": "1873"}), (None, 1873))
39
+
40
+    def test_pasted_lichess_game_keeps_its_ratings(self):
41
+        pasted = clipboard.parse('[White "anna"]\n[Black "ben"]\n[WhiteElo "1520"]\n[BlackElo "1610"]\n\n1. e4 e5 *')
42
+        self.assertEqual(pasted.state.ratings, (1520, 1610))
43
+
44
+
45
+class FakeApp:
46
+    lichess_user = None
47
+
48
+
49
+class Window:
50
+    """Die echten Methoden aus app.Window auf einer Attrappe."""
51
+    _wdl_elos = app.Window._wdl_elos
52
+    _save_ratings = app.Window._save_ratings
53
+    _save_wdls = app.Window._save_wdls
54
+    _wdl_preload = app.Window._wdl_preload
55
+
56
+    def __init__(self, board, mode="maia", names=(), ratings=(None, None), user=None):
57
+        self.board, self.mode, self.names, self.ratings = board, mode, names, ratings
58
+        self.human, self.elo, self.settings, self.maia_wdls = chess.WHITE, 1100, {"elo": 1100}, {}
59
+        self.app = FakeApp()
60
+        self.app.lichess_user = user
61
+
62
+    def _opponent_elo(self):
63
+        return self.elo
64
+
65
+    def get_application(self):
66
+        return self.app
67
+
68
+
69
+class WindowTest(unittest.TestCase):
70
+    def test_stored_ratings_win_over_todays_rating(self):
71
+        today = {"perfs": {"rapid": {"rating": 1900, "games": 40}}}
72
+        self.assertEqual(Window(played("e4"), user=today)._wdl_elos(), (1900, 1100))  # ohne Tags: heute
73
+        self.assertEqual(Window(played("e4"), ratings=(1500, 1100), user=today)._wdl_elos(), (1500, 1100))
74
+
75
+    def test_missing_side_filled_with_maia(self):
76
+        self.assertEqual(Window(played("e4"), ratings=(None, 1300))._wdl_elos(), (1100, 1300))
77
+
78
+    def test_saved_ratings_give_back_the_same_elos(self):
79
+        """Ohne Lichess-Anmeldung rechnet Maia mit (Maia, Maia); gespeichert wird nur Maias Seite,
80
+        beim Laden ergibt sich wieder (Maia, Maia)."""
81
+        win = Window(played("e4"))
82
+        before = win._wdl_elos()
83
+        ratings = win._save_ratings()
84
+        self.assertEqual(ratings, (None, 1100))
85
+        self.assertEqual(Window(played("e4"), ratings=ratings)._wdl_elos(), before)
86
+
87
+    def test_two_players_write_nothing(self):
88
+        self.assertEqual(Window(played("e4"), mode="duo")._save_ratings(), (None, None))
89
+
90
+    def test_bars_saved_and_preloaded(self):
91
+        win = Window(played("e4", "e5"), ratings=(1500, 1100))
92
+        after = played("e4").fen()
93
+        win.maia_wdls[(after, 1500, 1100)] = WDL
94
+        self.assertEqual(win._save_wdls(), {0: WDL})
95
+        fresh = Window(played("e4", "e5"), ratings=(1500, 1100))
96
+        fresh._wdl_preload({0: WDL})
97
+        self.assertEqual(fresh.maia_wdls, {(after, 1500, 1100): WDL})
98
+
99
+
100
+if __name__ == "__main__":
101
+    unittest.main()