Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(lichess): odds challenges (material handicap)

public

feat(lichess): odds challenges (material handicap)

Challenge dialog offers odds (without f-pawn, knight, rook or queen)
and who gives them; sent as a custom start position (fromPosition,
always unrated). Incoming fromPosition challenges are accepted and
describe the odds; the game subtitle shows them too.
Lichess time control setting moves to its own key: the shared
'time_control' key would have crashed the dialog once a local time
control was saved.

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

modified README.md +3 −1

@@ -29,7 +29,9 @@ Schlichtes GNOME-Schachprogramm (Python,
2929
   wie auf Lichess nur dann als gelöst, wenn kein falscher Zug und kein Hinweis dabei war.
3030
 - **Lichess** (Einstellungen → Lichess): anmelden per Browser (OAuth, kein Passwort im Programm;
3131
   der Zugriffsschlüssel liegt im GNOME-Schlüsselbund). Dann: Freunde herausfordern (Pfeil neben `+`) bzw.
32
-  Herausforderungen annehmen und online spielen – ohne Hinweise, Zeichen und Bewertung
32
+  Herausforderungen annehmen und online spielen – auch mit Vorgabe: Der Stärkere beginnt
33
+  ohne Bauer f, Springer, Turm oder Dame (Lichess-Partie mit eigener Startstellung, nie
34
+  gewertet; ein Handicap ohne Engine-Hilfe) – ohne Hinweise, Zeichen und Bewertung
3335
   (Fair Play). Strg+Z fragt beim Gegner eine Rücknahme an; bis zur Antwort sind beide
3436
   Bretter gesperrt, ohne Antwort gilt sie nach 20 s als abgelehnt. Bricht die Verbindung
3537
   ab, zeigt ein Banner das an, bis sie wieder steht. Nach der Partie wird sie gespeichert

modified ROADMAP.md +4 −0

@@ -531,6 +531,10 @@ Die Oberfläche ist heute fest auf Deutsch. Für weitere Sprachen:
531531
 
532532
 ## 10. Vorgabe-Partie auf Lichess
533533
 
534
+**Status:** umgesetzt (20.11.2026). Eingehende Vorgabe-Herausforderungen lassen sich
535
+annehmen und zeigen die Vorgabe an, ebenso der Untertitel der laufenden Partie.
536
+Nicht live mit einem echten Gegner getestet.
537
+
534538
 Lichess erlaubt Herausforderungen mit eigener Startstellung (Parameter `fen`,
535539
 Variante standard/fromPosition; solche Partien sind nie gewertet). Damit geht ein
536540
 Handicap, das Fair Play nicht verletzt: Der Stärkere spielt ohne Bauer f, ohne

modified schach/app.py +10 −2

@@ -58,9 +58,14 @@ DEFAULTS = {
5858
 def load_settings():
5959
     try:
6060
         with open(SETTINGS_PATH) as fh:
61
-            return {**DEFAULTS, **json.load(fh)}
61
+            settings = {**DEFAULTS, **json.load(fh)}
6262
     except (OSError, ValueError):
6363
         return dict(DEFAULTS)
64
+    if isinstance(settings.get("time_control"), int):
65
+        # früher: Index der Lichess-Bedenkzeit; jetzt eigener Schlüssel, "time_control" = lokale Uhr
66
+        settings["lichess_time_control"] = settings["time_control"]
67
+        settings["time_control"] = DEFAULTS["time_control"]
68
+    return settings
6469
 
6570
 
6671
 def save_settings(settings):
@@ -554,7 +559,10 @@ class Window(OnlineMixin, PuzzleMixin, O
554559
                                          "increment": clock["increment"] // 1000}) if clock
555560
                       else time_control_text({"type": "correspondence", "daysPerTurn": full.get("daysPerTurn", 1)}))
556561
                 rated = "gewertet" if full.get("rated") else "ungewertet"
557
-                self.title.set_subtitle(f"gegen {self.opponent} · {tc} · {rated}")
562
+                from .odds import describe
563
+                start = describe(full.get("initialFen"))
564
+                extra = f" · {start}" if start else ""
565
+                self.title.set_subtitle(f"gegen {self.opponent} · {tc} · {rated}{extra}")
558566
         elif self.mode == "review" and self.names:
559567
             self.title.set_subtitle("Analyse")
560568
         elif self.mode == "review":

modified schach/lichess.py +5 −1

@@ -218,13 +218,17 @@ class Client:
218218
         self.session.delete(HOST + "/api/token", timeout=10)
219219
 
220220
     # Herausforderungen
221
-    def challenge(self, username, minutes, increment, color, rated, on_created, stop):
221
+    def challenge(self, username, minutes, increment, color, rated, on_created, stop, fen=None):
222222
         """Fordert heraus und hält die Herausforderung offen, bis sie angenommen/abgelehnt wird.
223223
 
224224
         on_created(id) kommt im GTK-Thread, sobald Lichess die Herausforderung angelegt hat;
225225
         Rückgabe: {"id": …, "done": "accepted" | "declined" | "canceled" | …}.
226226
         """
227227
         data = {"rated": "true" if rated else "false", "color": color, "keepAliveStream": "true"}
228
+        if fen:
229
+            data["fen"] = fen  # eigene Startstellung (Vorgabe); solche Partien sind nie gewertet
230
+            data["variant"] = "fromPosition"
231
+            data["rated"] = "false"
228232
         if minutes is None:
229233
             data["days"] = increment
230234
         else:

added schach/odds.py +59 −0

@@ -0,0 +1,59 @@
1
+"""Materialvorgabe: Startstellung, in der eine Seite ohne eine Figur beginnt.
2
+
3
+Klassische Vorgaben: Bauer f, Damenspringer (b1/b8), Damenturm (a1/a8, dann ohne
4
+lange Rochade) oder Dame. Auf Lichess als Herausforderung mit eigener Startstellung
5
+(nie gewertet) – ein Handicap ohne Engine-Hilfe, also Fair Play.
6
+"""
7
+
8
+import chess
9
+
10
+ODDS = [("none", "Keine"), ("pawn", "Bauer f"), ("knight", "Springer"), ("rook", "Turm"), ("queen", "Dame")]
11
+_SQUARES = {
12
+    "pawn": (chess.F2, chess.F7),
13
+    "knight": (chess.B1, chess.B8),
14
+    "rook": (chess.A1, chess.A8),
15
+    "queen": (chess.D1, chess.D8),
16
+}
17
+_PIECE_NAMES = {
18
+    chess.PAWN: ("Bauer", "Bauern"), chess.KNIGHT: ("Springer", "Springer"),
19
+    chess.BISHOP: ("Läufer", "Läufer"), chess.ROOK: ("Turm", "Türme"), chess.QUEEN: ("Dame", "Damen"),
20
+}
21
+COLOR_NAME = {chess.WHITE: "Weiß", chess.BLACK: "Schwarz"}
22
+
23
+
24
+def odds_fen(giver, key):
25
+    """FEN der Startstellung, in der ``giver`` ohne die Figur ``key`` spielt; None ohne Vorgabe."""
26
+    if key not in _SQUARES:
27
+        return None
28
+    board = chess.Board()
29
+    square = _SQUARES[key][0 if giver == chess.WHITE else 1]
30
+    board.remove_piece_at(square)
31
+    if key == "rook":
32
+        board.castling_rights &= ~chess.BB_SQUARES[square]  # ohne Turm keine lange Rochade
33
+    return board.fen()
34
+
35
+
36
+def describe(fen):
37
+    """Kurzbeschreibung einer Startstellung: 'Weiß spielt ohne Springer' oder 'eigene Startstellung'."""
38
+    if not fen or fen in ("startpos", chess.STARTING_FEN):
39
+        return None
40
+    try:
41
+        board = chess.Board(fen)
42
+    except ValueError:
43
+        return "eigene Startstellung"
44
+    start = chess.Board()
45
+    missing = {chess.WHITE: [], chess.BLACK: []}
46
+    for color in (chess.WHITE, chess.BLACK):
47
+        for piece_type in _PIECE_NAMES:
48
+            diff = len(start.pieces(piece_type, color)) - len(board.pieces(piece_type, color))
49
+            if diff < 0:
50
+                return "eigene Startstellung"
51
+            if diff:
52
+                singular, plural = _PIECE_NAMES[piece_type]
53
+                missing[color].append(singular if diff == 1 else f"{diff} {plural}")
54
+    # nur Figuren weggenommen, sonst alles wie in der Grundstellung?
55
+    for square, piece in board.piece_map().items():
56
+        if start.piece_at(square) != piece:
57
+            return "eigene Startstellung"
58
+    parts = [f"{COLOR_NAME[c]} spielt ohne {' und '.join(m)}" for c, m in missing.items() if m]
59
+    return ", ".join(parts) if parts else None

modified schach/online.py +44 −9

@@ -6,6 +6,7 @@ Nach dem Ende wird die Partie gespeicher
66
 """
77
 
88
 import datetime
9
+import random
910
 import threading
1011
 import time
1112
 
@@ -15,7 +16,7 @@ import gi
1516
 gi.require_version("Adw", "1")
1617
 from gi.repository import Adw, GLib, Gtk  # noqa: E402
1718
 
18
-from . import lichess, savegames  # noqa: E402
19
+from . import lichess, odds, savegames  # noqa: E402
1920
 
2021
 
2122
 TAKEBACK_TIMEOUT_S = 20  # ohne Antwort gilt eine Rücknahme-Anfrage als abgelehnt
@@ -415,30 +416,62 @@ class OnlineMixin:
415416
         name_row = Adw.EntryRow(title="Lichess-Name", text=self.settings.get("friend", ""))
416417
         group.add(name_row)
417418
         tc_row = Adw.ComboRow(title="Bedenkzeit", model=Gtk.StringList.new([t[0] for t in lichess.TIME_CONTROLS]))
418
-        tc_row.set_selected(min(self.settings.get("time_control", 0), len(lichess.TIME_CONTROLS) - 1))
419
+        saved_tc = self.settings.get("lichess_time_control", 0)
420
+        tc_row.set_selected(min(saved_tc if isinstance(saved_tc, int) else 0, len(lichess.TIME_CONTROLS) - 1))
419421
         group.add(tc_row)
420422
         colors = ["random", "white", "black"]
421423
         color_row = Adw.ComboRow(title="Deine Farbe", model=Gtk.StringList.new(["Zufällig", "Weiß", "Schwarz"]))
422424
         group.add(color_row)
423425
         rated_row = Adw.SwitchRow(title="Gewertet", subtitle="Verändert die Lichess-Wertung")
424426
         group.add(rated_row)
425
-        dialog.set_extra_child(group)
427
+
428
+        # Vorgabe: der Stärkere spielt ohne eine Figur – ein Handicap, das auf Lichess erlaubt ist
429
+        handicap = Adw.PreferencesGroup(
430
+            title="Vorgabe", description="Der Stärkere beginnt ohne eine Figur. Solche Partien sind nie gewertet.",
431
+        )
432
+        odds_row = Adw.ComboRow(title="Ohne", model=Gtk.StringList.new([label for _k, label in odds.ODDS]))
433
+        giver_row = Adw.ComboRow(title="Wer gibt vor?", model=Gtk.StringList.new(["Ich", "Mein Gegner"]))
434
+        handicap.add(odds_row)
435
+        handicap.add(giver_row)
436
+
437
+        def on_odds(*_):
438
+            active = odds_row.get_selected() != 0
439
+            giver_row.set_sensitive(active)
440
+            rated_row.set_sensitive(not active)
441
+            if active:
442
+                rated_row.set_active(False)
443
+
444
+        odds_row.connect("notify::selected", on_odds)
445
+        on_odds()
446
+        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12, width_request=340)
447
+        box.append(group)
448
+        box.append(handicap)
449
+        dialog.set_extra_child(box)
426450
 
427451
         def on_response(_d, response):
428452
             name = name_row.get_text().strip()
429453
             if response != "send" or not name:
430454
                 return
431
-            self.settings.update(friend=name, time_control=tc_row.get_selected())
455
+            self.settings.update(friend=name, lichess_time_control=tc_row.get_selected())
432456
             from .app import save_settings
433457
             save_settings(self.settings)
434458
             _label, minutes, inc = lichess.TIME_CONTROLS[tc_row.get_selected()]
435
-            self._send_challenge(name, minutes, inc, colors[color_row.get_selected()], rated_row.get_active())
459
+            color = colors[color_row.get_selected()]
460
+            key = odds.ODDS[odds_row.get_selected()][0]
461
+            fen = None
462
+            if key != "none":
463
+                if color == "random":
464
+                    color = random.choice(["white", "black"])  # die Stellung hängt an der Farbe
465
+                mine = chess.WHITE if color == "white" else chess.BLACK
466
+                giver = mine if giver_row.get_selected() == 0 else not mine
467
+                fen = odds.odds_fen(giver, key)
468
+            self._send_challenge(name, minutes, inc, color, rated_row.get_active() and fen is None, fen)
436469
 
437470
         dialog.connect("response", on_response)
438471
         dialog.present(self)
439472
         name_row.grab_focus()
440473
 
441
-    def _send_challenge(self, name, minutes, inc, color, rated):
474
+    def _send_challenge(self, name, minutes, inc, color, rated, fen=None):
442475
         app = self.get_application()
443476
         stop = threading.Event()
444477
         created = {}
@@ -479,7 +512,7 @@ class OnlineMixin:
479512
         waiting.connect("response", on_withdraw)
480513
         waiting.present(self)
481514
         lichess._background(
482
-            lambda: app.lichess_client.challenge(name, minutes, inc, color, rated, on_created, stop), on_done
515
+            lambda: app.lichess_client.challenge(name, minutes, inc, color, rated, on_created, stop, fen), on_done
483516
         )
484517
 
485518
     def incoming_challenge(self, challenge):
@@ -492,11 +525,13 @@ class OnlineMixin:
492525
         mine = {"white": "Schwarz", "black": "Weiß"}.get(their, "zufällige Farbe")
493526
         variant = (challenge.get("variant") or {}).get("key", "standard")
494527
         speed = challenge.get("speed")
495
-        supported = variant == "standard" and speed not in ("bullet", "ultraBullet")
528
+        supported = variant in ("standard", "fromPosition") and speed not in ("bullet", "ultraBullet")
529
+        start = odds.describe(challenge.get("initialFen")) if variant == "fromPosition" else None
496530
 
497531
         dialog = Adw.AlertDialog(heading=f"{who} fordert dich heraus")
498532
         if supported:
499
-            dialog.set_body(f"{tc}, {rated} – du spielst {mine}.")
533
+            extra = f" Vorgabe: {start}." if start else ""
534
+            dialog.set_body(f"{tc}, {rated} – du spielst {mine}.{extra}")
500535
             dialog.add_response("decline", "Ablehnen")
501536
             dialog.add_response("accept", "Annehmen")
502537
             dialog.set_response_appearance("accept", Adw.ResponseAppearance.SUGGESTED)

added tests/test_odds.py +65 −0

@@ -0,0 +1,65 @@
1
+import unittest
2
+
3
+import chess
4
+
5
+from schach import odds
6
+
7
+
8
+class OddsTest(unittest.TestCase):
9
+    def test_none(self):
10
+        self.assertIsNone(odds.odds_fen(chess.WHITE, "none"))
11
+        self.assertIsNone(odds.describe(chess.STARTING_FEN))
12
+
13
+    def test_knight_odds(self):
14
+        fen = odds.odds_fen(chess.WHITE, "knight")
15
+        board = chess.Board(fen)
16
+        self.assertIsNone(board.piece_at(chess.B1))
17
+        self.assertTrue(board.is_valid())
18
+        self.assertEqual(odds.describe(fen), "Weiß spielt ohne Springer")
19
+
20
+    def test_rook_odds_drop_long_castling(self):
21
+        board = chess.Board(odds.odds_fen(chess.BLACK, "rook"))
22
+        self.assertIsNone(board.piece_at(chess.A8))
23
+        self.assertFalse(board.has_queenside_castling_rights(chess.BLACK))
24
+        self.assertTrue(board.has_kingside_castling_rights(chess.BLACK))
25
+        self.assertTrue(board.has_queenside_castling_rights(chess.WHITE))
26
+        self.assertEqual(odds.describe(board.fen()), "Schwarz spielt ohne Turm")
27
+
28
+    def test_pawn_and_queen(self):
29
+        self.assertEqual(odds.describe(odds.odds_fen(chess.WHITE, "pawn")), "Weiß spielt ohne Bauer")
30
+        self.assertEqual(odds.describe(odds.odds_fen(chess.BLACK, "queen")), "Schwarz spielt ohne Dame")
31
+
32
+    def test_other_positions(self):
33
+        self.assertEqual(odds.describe("8/8/8/4k3/8/8/8/4K2R w K - 0 1"), "eigene Startstellung")
34
+        moved = chess.Board()
35
+        moved.push_san("e4")
36
+        self.assertEqual(odds.describe(moved.fen()), "eigene Startstellung")
37
+
38
+
39
+class ChallengeRequestTest(unittest.TestCase):
40
+    def test_fen_forces_unrated_from_position(self):
41
+        from schach import lichess
42
+
43
+        client = lichess.Client()
44
+        captured = {}
45
+        client._stream = lambda method, path, on_line, stop, data: captured.update(path=path, data=data)
46
+        fen = odds.odds_fen(chess.WHITE, "knight")
47
+        client.challenge("max", 10, 5, "white", True, lambda _id: None, None, fen=fen)
48
+        self.assertEqual(captured["path"], "/api/challenge/max")
49
+        self.assertEqual(captured["data"]["fen"], fen)
50
+        self.assertEqual(captured["data"]["variant"], "fromPosition")
51
+        self.assertEqual(captured["data"]["rated"], "false")
52
+
53
+    def test_without_fen_unchanged(self):
54
+        from schach import lichess
55
+
56
+        client = lichess.Client()
57
+        captured = {}
58
+        client._stream = lambda method, path, on_line, stop, data: captured.update(data=data)
59
+        client.challenge("max", 10, 5, "random", True, lambda _id: None, None)
60
+        self.assertNotIn("fen", captured["data"])
61
+        self.assertEqual(captured["data"]["rated"], "true")
62
+
63
+
64
+if __name__ == "__main__":
65
+    unittest.main()