Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(setup): build a position, then solve or analyse it

public

feat(setup): build a position, then solve or analyse it

Paper puzzles from Florian's club: pick a piece, click squares, drag
to move, right-click or eraser to remove. Castling rights follow from
the placement. Invalid positions explained in plain words.

- Lösen üben: play the side to move against Maia
- Analysieren: both sides by hand, glyphs for every move, no hint cap
- Ctrl+V with a FEN loads it into the editor, Ctrl+C copies the FEN

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

modified schach/app.py +26 −3

@@ -25,6 +25,7 @@ from .online import OnlineMixin # noqa:
2525
 from .puzzles import PuzzleMixin  # noqa: E402
2626
 from .training import OpeningMixin  # noqa: E402
2727
 from .duo import DuoMixin  # noqa: E402
28
+from .setup import SetupMixin  # noqa: E402
2829
 from .clock import TIME_CONTROLS, GameClock, time_control  # noqa: E402
2930
 
3031
 APP_ID = "app.schach.Schach"
@@ -116,7 +117,7 @@ def outcome_text(board, human, opponent=
116117
     }.get(outcome.termination, "Remis.")
117118
 
118119
 
119
-class Window(OnlineMixin, PuzzleMixin, OpeningMixin, DuoMixin, Adw.ApplicationWindow):
120
+class Window(OnlineMixin, PuzzleMixin, OpeningMixin, DuoMixin, SetupMixin, Adw.ApplicationWindow):
120121
     """Ein Brett. ``mode``: "maia" (Partie gegen Maia), "online" (Lichess-Partie, ohne Engine-Hilfe),
121122
     "puzzle" (Lichess-Rätsel), "opening" (Eröffnungstraining), "duo" (zwei Spieler an diesem Rechner),
122123
     "review" (fertige Partie ansehen und analysieren)."""
@@ -162,6 +163,7 @@ class Window(OnlineMixin, PuzzleMixin, O
162163
         self._online_init()
163164
         self._opening_init()
164165
         self._duo_init()
166
+        self._setup_init()
165167
         self.clock = None  # Schachuhr lokaler Partien (clock.GameClock)
166168
         self.clock_tick = 0
167169
 
@@ -199,6 +201,7 @@ class Window(OnlineMixin, PuzzleMixin, O
199201
         games.append_submenu("Rätsel-_Schwierigkeit", difficulty)
200202
         games.append("_Eröffnung üben …", "win.opening")
201203
         games.append("_Zwei Spieler an diesem Rechner …", "win.duo")
204
+        games.append("Stellung _aufbauen", "win.setup")
202205
         games.append("Aus der _Zwischenablage", "win.paste")
203206
         online = Gio.Menu()
204207
         online.append("Freund auf _Lichess herausfordern …", "win.challenge")
@@ -308,6 +311,7 @@ class Window(OnlineMixin, PuzzleMixin, O
308311
         box.append(self.banner)
309312
         box.append(self.view)
310313
         box.append(self._build_coach())
314
+        box.append(self._build_setup())
311315
 
312316
         self.movelist = MoveList()
313317
         self.movelist.notation = self._notation()
@@ -387,6 +391,7 @@ class Window(OnlineMixin, PuzzleMixin, O
387391
             ("preferences", self._preferences_dialog),
388392
             ("opening", self._opening_dialog),
389393
             ("duo", self._duo_dialog),
394
+            ("setup", self._setup_action),
390395
             ("duo-draw", self._duo_draw),
391396
             ("duo-resign", self._duo_resign),
392397
             ("opening-next", self._opening_again),
@@ -469,7 +474,7 @@ class Window(OnlineMixin, PuzzleMixin, O
469474
         return self._end_text() is not None
470475
 
471476
     def _human_to_move(self):
472
-        if self.mode == "review":
477
+        if self.mode in ("review", "setup"):
473478
             return False
474479
         if self.mode == "puzzle" and self.puzzle is None:
475480
             return False
@@ -493,6 +498,7 @@ class Window(OnlineMixin, PuzzleMixin, O
493498
         self._puzzle_leave()
494499
         self._opening_leave()
495500
         self._duo_leave()
501
+        self._setup_leave()
496502
         self._clock_clear()
497503
         self.mode = "maia"
498504
         self.opponent = ""
@@ -520,6 +526,9 @@ class Window(OnlineMixin, PuzzleMixin, O
520526
         return self.browse_ply is not None and self.browse_ply < len(self.board.move_stack) - 1
521527
 
522528
     def _refresh(self):
529
+        if self.mode == "setup":
530
+            self._setup_refresh()
531
+            return
523532
         v = self.view
524533
         v.human = self.human
525534
         if self._browsing():
@@ -581,6 +590,8 @@ class Window(OnlineMixin, PuzzleMixin, O
581590
             self.title.set_subtitle(self._opening_subtitle())
582591
         elif self.mode == "duo":
583592
             self.title.set_subtitle(self._duo_subtitle())
593
+        elif self.mode == "setup":
594
+            self.title.set_subtitle(self._setup_subtitle())
584595
         elif self.mode == "online":
585596
             if self.online_full is None:
586597
                 self.title.set_subtitle("Verbinde mit Lichess …")
@@ -606,7 +617,7 @@ class Window(OnlineMixin, PuzzleMixin, O
606617
             clock = f" · {self.clock_label}" if self.clock is not None else ""
607618
             self.title.set_subtitle(f"Maia {self.elo} · du spielst {side}{clock}")
608619
         default_title = {"puzzle": "Rätsel", "online": "Lichess", "opening": self._opening_title(),
609
-                         "duo": "Zwei Spieler"}.get(
620
+                         "duo": "Zwei Spieler", "setup": "Stellung aufbauen"}.get(
610621
             self.mode, "Schach")
611622
         self.title.set_title(self.save_name or default_title)
612623
         self._refresh_players()
@@ -1238,6 +1249,10 @@ class Window(OnlineMixin, PuzzleMixin, O
12381249
         """Klick aufs Brett beim Anschauen einer alten Stellung: zurück zum Spiel."""
12391250
         return self._end_browse() and self.view.interactive
12401251
 
1252
+    def _copy_setup_fen(self):
1253
+        self.get_clipboard().set(self._setup_fen())
1254
+        self.toasts.add_toast(Adw.Toast(title="FEN kopiert", timeout=2))
1255
+
12411256
     def _copy_fen(self, ply):
12421257
         fen = self._board_at(ply).fen()
12431258
         self.get_clipboard().set(fen)
@@ -1253,6 +1268,9 @@ class Window(OnlineMixin, PuzzleMixin, O
12531268
     def _copy_pgn(self, *_):
12541269
         if self._forward_clipboard("copy"):
12551270
             return
1271
+        if self.mode == "setup":
1272
+            self._copy_setup_fen()
1273
+            return
12561274
         if not self.board.move_stack:
12571275
             self._copy_fen(-1)  # noch keine Züge: wenigstens die Stellung
12581276
             return
@@ -1260,6 +1278,9 @@ class Window(OnlineMixin, PuzzleMixin, O
12601278
         self.toasts.add_toast(Adw.Toast(title="Partie als PGN kopiert", timeout=2))
12611279
 
12621280
     def _copy_shown_fen(self, *_):
1281
+        if self.mode == "setup":
1282
+            self._copy_setup_fen()
1283
+            return
12631284
         self._copy_fen(self.browse_ply if self._browsing() else len(self.board.move_stack) - 1)
12641285
 
12651286
     def _paste(self, *_):
@@ -1303,6 +1324,8 @@ class Window(OnlineMixin, PuzzleMixin, O
13031324
             self.toasts.add_toast(Adw.Toast(title=f"Keine Partie und keine Stellung {where}", timeout=3))
13041325
         elif pasted.kind == "lichess":
13051326
             self._fetch_lichess(pasted)
1327
+        elif self.mode == "setup" and pasted.kind == "fen":
1328
+            self._setup_set(pasted.state.board)  # beim Aufbauen: Stellung übernehmen und weiter bearbeiten
13061329
         else:
13071330
             self._place(pasted)
13081331
 

modified schach/board.py +29 −0

@@ -34,6 +34,11 @@ class BoardView(Gtk.DrawingArea, BoardPa
3434
         self.on_inactive_click = None  # callback() – Klick, während das Brett gesperrt ist
3535
         self._was_selected = False
3636
         self._dropped = None  # (von, nach) des letzten per Maus gezogenen Zugs
37
+        # Stellung aufbauen: Klick setzt, Ziehen verschiebt, Rechtsklick nimmt weg
38
+        self.on_edit_click = None  # callback(feld)
39
+        self.on_edit_move = None  # callback(von, nach oder None = vom Brett)
40
+        self.on_edit_erase = None  # callback(feld)
41
+        self._edit_start = None
3742
 
3843
         self.set_draw_func(lambda _area, cr, _w, _h: self.paint(cr))
3944
         drag = Gtk.GestureDrag()
@@ -41,6 +46,9 @@ class BoardView(Gtk.DrawingArea, BoardPa
4146
         drag.connect("drag-update", self._on_update)
4247
         drag.connect("drag-end", self._on_end)
4348
         self.add_controller(drag)
49
+        erase = Gtk.GestureClick(button=3)
50
+        erase.connect("pressed", self._on_erase)
51
+        self.add_controller(erase)
4452
 
4553
     def set_scheme(self, scheme):
4654
         self.scheme = scheme
@@ -120,7 +128,17 @@ class BoardView(Gtk.DrawingArea, BoardPa
120128
 
121129
     # --- Eingabe -----------------------------------------------------------
122130
 
131
+    def _on_erase(self, _gesture, _n, x, y):
132
+        s = self._square_at(x, y)
133
+        if self.on_edit_erase is not None and s is not None:
134
+            self.on_edit_erase(s)
135
+
123136
     def _on_begin(self, gesture, x, y):
137
+        if self.on_edit_click is not None:
138
+            s = self._edit_start = self._square_at(x, y)
139
+            if s is not None and self.board.piece_at(s):
140
+                self._drag_sq, self._drag_pos, self._drag_moved = s, (x, y), False
141
+            return
124142
         if not self.interactive:
125143
             if self.on_inactive_click and self.on_inactive_click():
126144
                 self._on_begin(gesture, x, y)  # wieder spielbar: Klick normal verarbeiten
@@ -150,6 +168,17 @@ class BoardView(Gtk.DrawingArea, BoardPa
150168
         self.queue_draw()
151169
 
152170
     def _on_end(self, gesture, dx, dy):
171
+        if self.on_edit_click is not None:
172
+            start, self._edit_start = self._edit_start, None
173
+            src, moved = self._drag_sq, self._drag_moved
174
+            self._drag_sq, self._drag_moved = None, False
175
+            if src is not None and moved:
176
+                _, sx, sy = gesture.get_start_point()
177
+                self.on_edit_move(src, self._square_at(sx + dx, sy + dy))
178
+            elif start is not None:
179
+                self.on_edit_click(start)
180
+            self.queue_draw()
181
+            return
153182
         if self._drag_sq is None:
154183
             return
155184
         _, sx, sy = gesture.get_start_point()

modified schach/diagram.py +3 −1

@@ -124,6 +124,7 @@ class BoardPainter:
124124
         self.clocks = None  # {Farbe: Millisekunden}
125125
         self.clock_running = None  # Farbe, deren Uhr gerade läuft
126126
         self.turn_marker = None  # Farbe, deren Name fett steht (wer am Zug ist, bei zwei Spielern)
127
+        self.editing = False  # Stellung aufbauen: keine geschlagenen Figuren anzeigen
127128
         self.eval_bar = None  # Gewinnchance Weiß in Prozent: Balken links neben dem Brett
128129
         self._drag_sq = None
129130
         self._drag_pos = None
@@ -245,7 +246,8 @@ class BoardPainter:
245246
             self._draw_arrow(cr, self.threat_from, self.threat_to, sq, THREAT)
246247
 
247248
         if self.strips:
248
-            self._draw_captures(cr, ox, oy, sq)
249
+            if not self.editing:
250
+                self._draw_captures(cr, ox, oy, sq)
249251
             self._draw_players(cr, ox, oy, sq)
250252
         if self.eval_bar is not None:
251253
             self._draw_eval_bar(cr, ox, oy, sq)

modified schach/duo.py +2 −1

@@ -168,7 +168,8 @@ class DuoMixin:
168168
         if self.duo is None:
169169
             return False
170170
         color = self.board.turn
171
-        return self.duo["used"][color] < self.duo["hints"][color]
171
+        budget = self.duo["hints"][color]
172
+        return budget is None or self.duo["used"][color] < budget  # None = ohne Grenze
172173
 
173174
     def _duo_spend_help(self):
174175
         self.duo["used"][self.board.turn] += 1

added schach/setup.py +288 −0

@@ -0,0 +1,288 @@
1
+"""Stellung aufbauen – z. B. ein Rätsel vom Papier – als Mixin für das Hauptfenster.
2
+
3
+Figur in der Leiste wählen, dann aufs Feld klicken (noch ein Klick mit derselben
4
+Figur nimmt sie wieder weg). Figuren auf dem Brett lassen sich verschieben; vom
5
+Brett gezogen oder mit Rechtsklick verschwinden sie. Rochaderechte ergeben sich
6
+aus der Aufstellung (König und Turm auf ihren Ausgangsfeldern).
7
+
8
+Danach: „Lösen üben“ gegen Maia oder „Analysieren“ – beide Seiten selbst ziehen,
9
+mit Zugzeichen für jeden Zug und Hinweisen ohne Grenze.
10
+"""
11
+
12
+import chess
13
+import gi
14
+
15
+gi.require_version("Gtk", "4.0")
16
+gi.require_version("Adw", "1")
17
+from gi.repository import Adw, Gtk  # noqa: E402
18
+
19
+from . import savegames  # noqa: E402
20
+
21
+COLOR_NAME = {chess.WHITE: "Weiß", chess.BLACK: "Schwarz"}
22
+PIECE_NAME = {chess.KING: "König", chess.QUEEN: "Dame", chess.ROOK: "Turm",
23
+              chess.BISHOP: "Läufer", chess.KNIGHT: "Springer", chess.PAWN: "Bauer"}
24
+PALETTE = "KQRBNP"
25
+
26
+
27
+# --- Logik (ohne GTK, getestet) ---------------------------------------------
28
+
29
+def finished(board):
30
+    """Die aufgebaute Stellung als spielbares Brett: Rochaderechte aus der Aufstellung."""
31
+    result = chess.Board(None)
32
+    result.set_piece_map(board.piece_map())
33
+    result.turn = board.turn
34
+    result.castling_rights = chess.BB_CORNERS
35
+    result.castling_rights = result.clean_castling_rights()
36
+    return result
37
+
38
+
39
+def problem(board):
40
+    """Warum die Stellung nicht spielbar ist, kindgerecht – oder None."""
41
+    b = finished(board)
42
+    status = b.status()
43
+    if not status:
44
+        return None
45
+    if status & chess.STATUS_EMPTY:
46
+        return "Das Brett ist leer."
47
+    if status & (chess.STATUS_NO_WHITE_KING | chess.STATUS_NO_BLACK_KING | chess.STATUS_TOO_MANY_KINGS):
48
+        missing = [COLOR_NAME[c] for c in (chess.WHITE, chess.BLACK) if b.king(c) is None]
49
+        if len(missing) == 1:
50
+            return f"{missing[0]} fehlt der König."
51
+        if len(missing) == 2:
52
+            return "Es fehlen noch beide Könige."
53
+        return "Jede Farbe braucht genau einen König."
54
+    if status & chess.STATUS_PAWNS_ON_BACKRANK:
55
+        return "Bauern können nicht auf der ersten oder achten Reihe stehen."
56
+    if status & (chess.STATUS_TOO_MANY_WHITE_PAWNS | chess.STATUS_TOO_MANY_BLACK_PAWNS):
57
+        return "Eine Farbe hat mehr als acht Bauern."
58
+    if status & (chess.STATUS_TOO_MANY_WHITE_PIECES | chess.STATUS_TOO_MANY_BLACK_PIECES):
59
+        return "Eine Farbe hat mehr als 16 Figuren."
60
+    if status & chess.STATUS_OPPOSITE_CHECK:
61
+        waiting = not b.turn
62
+        return f"{COLOR_NAME[waiting]} steht im Schach – dann muss {COLOR_NAME[waiting]} am Zug sein."
63
+    if status & (chess.STATUS_TOO_MANY_CHECKERS | chess.STATUS_IMPOSSIBLE_CHECK):
64
+        return "So ein Schach kann es nicht geben."
65
+    return "Diese Stellung kann es so nicht geben."
66
+
67
+
68
+def place(board, square, piece):
69
+    """Figur setzen; dieselbe Figur auf demselben Feld nimmt sie weg. Ein König zieht um."""
70
+    if piece is None or board.piece_at(square) == piece:
71
+        board.remove_piece_at(square)
72
+        return
73
+    if piece.piece_type == chess.KING:
74
+        old = board.king(piece.color)
75
+        if old is not None:
76
+            board.remove_piece_at(old)
77
+    board.set_piece_at(square, piece)
78
+
79
+
80
+def move(board, src, dst):
81
+    """Figur verschieben; ``dst`` None = vom Brett gezogen."""
82
+    piece = board.remove_piece_at(src)
83
+    if piece is not None and dst is not None:
84
+        board.set_piece_at(dst, piece)
85
+
86
+
87
+# --- Oberfläche --------------------------------------------------------------
88
+
89
+class SetupMixin:
90
+    def _setup_init(self):
91
+        self.setup = None  # {"board": chess.Board, "tool": chess.Piece | None (Radierer)}
92
+
93
+    def _build_setup(self):
94
+        """Figurenleiste und Knöpfe unter dem Brett; nur sichtbar beim Aufbauen."""
95
+        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10,
96
+                      margin_start=12, margin_end=12, margin_bottom=12)
97
+
98
+        grid = Gtk.Grid(column_spacing=4, row_spacing=4, halign=Gtk.Align.CENTER)
99
+        self.setup_tools = {}
100
+        group = None
101
+        for row, color in enumerate((chess.WHITE, chess.BLACK)):
102
+            for col, letter in enumerate(PALETTE):
103
+                piece = chess.Piece.from_symbol(letter if color == chess.WHITE else letter.lower())
104
+                area = Gtk.DrawingArea(content_width=36, content_height=36)
105
+                area.set_draw_func(self._setup_draw_tool, piece)
106
+                button = Gtk.ToggleButton(child=area, group=group,
107
+                                          tooltip_text=f"{PIECE_NAME[piece.piece_type]} ({COLOR_NAME[color]})")
108
+                button.add_css_class("flat")
109
+                group = group or button
110
+                button.connect("toggled", self._setup_tool_toggled, piece)
111
+                grid.attach(button, col, row, 1, 1)
112
+                self.setup_tools[piece.symbol()] = button
113
+        eraser = Gtk.ToggleButton(icon_name="edit-clear-symbolic", group=group,
114
+                                  tooltip_text="Figuren wegnehmen (auch: Rechtsklick)")
115
+        eraser.add_css_class("flat")
116
+        eraser.connect("toggled", self._setup_tool_toggled, None)
117
+        grid.attach(eraser, len(PALETTE), 0, 1, 2)
118
+        self.setup_tools["eraser"] = eraser
119
+        box.append(grid)
120
+
121
+        row = Gtk.Box(spacing=12, halign=Gtk.Align.CENTER)
122
+        turn = Gtk.Box(css_classes=["linked"])
123
+        self.setup_turn = {}
124
+        for color in (chess.WHITE, chess.BLACK):
125
+            button = Gtk.ToggleButton(label=f"{COLOR_NAME[color]} am Zug",
126
+                                      group=self.setup_turn.get(chess.WHITE))
127
+            button.connect("toggled", self._setup_turn_toggled, color)
128
+            turn.append(button)
129
+            self.setup_turn[color] = button
130
+        row.append(turn)
131
+        for label, handler, tip in (
132
+            ("Grundstellung", lambda *_: self._setup_set(chess.Board()), "Alle Figuren auf Anfang"),
133
+            ("Leeren", lambda *_: self._setup_set(chess.Board(None)), "Alle Figuren wegnehmen"),
134
+        ):
135
+            button = Gtk.Button(label=label, tooltip_text=tip)
136
+            button.connect("clicked", handler)
137
+            row.append(button)
138
+        box.append(row)
139
+
140
+        self.setup_problem = Gtk.Label(wrap=True, justify=Gtk.Justification.CENTER, css_classes=["error"])
141
+        box.append(self.setup_problem)
142
+
143
+        actions = Gtk.Box(spacing=12, halign=Gtk.Align.CENTER)
144
+        self.setup_analyze_btn = Gtk.Button(
145
+            label="Analysieren", css_classes=["pill"],
146
+            tooltip_text="Beide Seiten selbst ziehen – jeder Zug bekommt ein Zugzeichen",
147
+        )
148
+        self.setup_analyze_btn.connect("clicked", self._setup_analyze)
149
+        self.setup_play_btn = Gtk.Button(
150
+            label="Lösen üben", css_classes=["pill", "suggested-action"],
151
+            tooltip_text="Du ziehst für die Seite am Zug, Maia verteidigt",
152
+        )
153
+        self.setup_play_btn.connect("clicked", self._setup_play)
154
+        actions.append(self.setup_analyze_btn)
155
+        actions.append(self.setup_play_btn)
156
+        box.append(actions)
157
+
158
+        self.setup_revealer = Gtk.Revealer(child=Adw.Clamp(child=box, maximum_size=560))
159
+        return self.setup_revealer
160
+
161
+    def _setup_draw_tool(self, area, cr, width, height, piece):
162
+        self.view._draw_piece(cr, piece, 0, 0, min(width, height))
163
+
164
+    # --- Ablauf ------------------------------------------------------------
165
+
166
+    def _setup_action(self, *_):
167
+        if self._busy():
168
+            self.get_application().open_window(None, blank=True).start_setup()
169
+        else:
170
+            self.start_setup()
171
+
172
+    def start_setup(self, board=None):
173
+        self._leave_special()
174
+        self.mode = "setup"
175
+        self.board = chess.Board()  # die laufende Partie ist weg; aufgebaut wird in self.setup
176
+        self._reset_game_tables()
177
+        self._changed()
178
+        self.save_name = ""
179
+        self.save_path = ""
180
+        self.browse_ply = None
181
+        self.list_btn.set_active(False)
182
+        self.setup = {"board": chess.Board(None), "tool": chess.Piece(chess.PAWN, chess.WHITE)}
183
+        self.setup_tools["P"].set_active(True)
184
+        self.view.on_edit_click = self._setup_click
185
+        self.view.on_edit_move = self._setup_move
186
+        self.view.on_edit_erase = self._setup_erase
187
+        self.setup_revealer.set_reveal_child(True)
188
+        self._setup_set(board or chess.Board(None))
189
+
190
+    def _setup_leave(self):
191
+        if self.setup is None:
192
+            return
193
+        self.setup = None
194
+        self.view.on_edit_click = self.view.on_edit_move = self.view.on_edit_erase = None
195
+        self.view.editing = False
196
+        self.setup_revealer.set_reveal_child(False)
197
+
198
+    def _setup_set(self, board):
199
+        """Ganze Stellung ersetzen (Grundstellung, Leeren, eingefügte FEN)."""
200
+        if self.setup is None:
201
+            return
202
+        fresh = chess.Board(None)
203
+        fresh.set_piece_map(board.piece_map())
204
+        fresh.turn = board.turn
205
+        self.setup["board"] = fresh
206
+        self.setup_turn[fresh.turn].set_active(True)
207
+        self._refresh()
208
+
209
+    def _setup_tool_toggled(self, button, piece):
210
+        if button.get_active() and self.setup is not None:
211
+            self.setup["tool"] = piece
212
+
213
+    def _setup_turn_toggled(self, button, color):
214
+        if button.get_active() and self.setup is not None:
215
+            self.setup["board"].turn = color
216
+            self._refresh()
217
+
218
+    def _setup_click(self, square):
219
+        place(self.setup["board"], square, self.setup["tool"])
220
+        self._refresh()
221
+
222
+    def _setup_move(self, src, dst):
223
+        move(self.setup["board"], src, dst)
224
+        self._refresh()
225
+
226
+    def _setup_erase(self, square):
227
+        self.setup["board"].remove_piece_at(square)
228
+        self._refresh()
229
+
230
+    def _setup_refresh(self):
231
+        """Brett und Knöpfe beim Aufbauen; die Engines sehen die Stellung erst, wenn sie gültig ist."""
232
+        v = self.view
233
+        v.board = self.setup["board"]
234
+        v.editing = True
235
+        v.interactive = False
236
+        v.selected = None
237
+        v.last_move = None
238
+        v.badge = v.turn_marker = None
239
+        v.hint_from = v.hint_to = v.threat_from = v.threat_to = None
240
+        v.names = None
241
+        v.clocks = v.clock_running = None
242
+        reason = problem(self.setup["board"])
243
+        self.setup_problem.set_label(reason or "")
244
+        self.setup_problem.set_visible(reason is not None)
245
+        self.setup_play_btn.set_sensitive(reason is None)
246
+        self.setup_analyze_btn.set_sensitive(reason is None)
247
+        v.queue_draw()
248
+        self._refresh_chrome()
249
+
250
+    def _setup_subtitle(self):
251
+        board = self.setup["board"]
252
+        return f"{COLOR_NAME[board.turn]} am Zug"
253
+
254
+    def _setup_fen(self):
255
+        return finished(self.setup["board"]).fen()
256
+
257
+    def _setup_ready(self):
258
+        if self.setup is None or problem(self.setup["board"]):
259
+            return None
260
+        return finished(self.setup["board"])
261
+
262
+    def _setup_play(self, *_):
263
+        board = self._setup_ready()
264
+        if board is None:
265
+            return
266
+        flipped = self.view.flipped
267
+        state = savegames.GameState(board=board, human=board.turn, elo=self.elo or int(self.settings["elo"]),
268
+                                    name="Aufgebaute Stellung")
269
+        self.load_state(state)
270
+        self.view.flipped = flipped
271
+        self.view.queue_draw()
272
+        self.toasts.add_toast(Adw.Toast(
273
+            title=f"Du spielst {COLOR_NAME[board.turn]} – Maia {self.elo} verteidigt", timeout=3))
274
+
275
+    def _setup_analyze(self, *_):
276
+        board = self._setup_ready()
277
+        if board is None:
278
+            return
279
+        flipped = self.view.flipped
280
+        self.start_duo({
281
+            "time": "Ohne Uhr",
282
+            "hints": {chess.WHITE: None, chess.BLACK: None},  # None = ohne Grenze
283
+            "glyphs": {chess.WHITE: "all", chess.BLACK: "all"},
284
+            "flip": False,
285
+        }, board=board)
286
+        self.save_name = "Aufgebaute Stellung"
287
+        self.view.flipped = flipped
288
+        self._refresh()

added tests/test_setup.py +73 −0

@@ -0,0 +1,73 @@
1
+import unittest
2
+
3
+import chess
4
+
5
+from schach import setup
6
+
7
+
8
+def board(fen):
9
+    return chess.Board(fen)
10
+
11
+
12
+class ProblemTest(unittest.TestCase):
13
+    def test_valid_position(self):
14
+        self.assertIsNone(setup.problem(board("4k3/8/8/8/8/8/8/4K2R w - - 0 1")))
15
+
16
+    def test_empty_and_kings(self):
17
+        self.assertEqual(setup.problem(chess.Board(None)), "Das Brett ist leer.")
18
+        self.assertEqual(setup.problem(board("8/8/8/8/8/8/8/4K3 w - - 0 1")), "Schwarz fehlt der König.")
19
+        self.assertIn("genau einen König", setup.problem(board("4k3/8/8/8/8/8/8/K3K3 w - - 0 1")))
20
+
21
+    def test_pawns_on_back_rank(self):
22
+        self.assertIn("Bauern", setup.problem(board("P3k3/8/8/8/8/8/8/4K3 w - - 0 1")))
23
+
24
+    def test_side_not_to_move_in_check(self):
25
+        # Schwarz steht im Schach durch den Turm, aber Weiß ist am Zug
26
+        self.assertEqual(
27
+            setup.problem(board("4k3/8/8/8/8/8/8/4R1K1 w - - 0 1")),
28
+            "Schwarz steht im Schach – dann muss Schwarz am Zug sein.",
29
+        )
30
+        self.assertIsNone(setup.problem(board("4k3/8/8/8/8/8/8/4R1K1 b - - 0 1")))
31
+
32
+
33
+class FinishedTest(unittest.TestCase):
34
+    def test_castling_from_placement(self):
35
+        b = setup.finished(board("r3k2r/8/8/8/8/8/8/4K2R w - - 0 1"))
36
+        self.assertEqual(b.castling_xfen(), "Kkq")
37
+        self.assertEqual(b.fullmove_number, 1)
38
+
39
+    def test_no_castling_when_king_moved(self):
40
+        self.assertEqual(setup.finished(board("r4k1r/8/8/8/8/8/8/R2K3R w - - 0 1")).castling_xfen(), "-")
41
+
42
+
43
+class EditTest(unittest.TestCase):
44
+    def test_place_toggles_and_replaces(self):
45
+        b = chess.Board(None)
46
+        knight = chess.Piece(chess.KNIGHT, chess.WHITE)
47
+        setup.place(b, chess.E4, knight)
48
+        self.assertEqual(b.piece_at(chess.E4), knight)
49
+        setup.place(b, chess.E4, chess.Piece(chess.BISHOP, chess.BLACK))
50
+        self.assertEqual(b.piece_at(chess.E4).symbol(), "b")
51
+        setup.place(b, chess.E4, chess.Piece(chess.BISHOP, chess.BLACK))
52
+        self.assertIsNone(b.piece_at(chess.E4))
53
+
54
+    def test_king_moves_instead_of_duplicating(self):
55
+        b = chess.Board(None)
56
+        king = chess.Piece(chess.KING, chess.WHITE)
57
+        setup.place(b, chess.E1, king)
58
+        setup.place(b, chess.G1, king)
59
+        self.assertEqual(b.king(chess.WHITE), chess.G1)
60
+        self.assertIsNone(b.piece_at(chess.E1))
61
+
62
+    def test_eraser_and_move(self):
63
+        b = chess.Board()
64
+        setup.place(b, chess.E2, None)
65
+        self.assertIsNone(b.piece_at(chess.E2))
66
+        setup.move(b, chess.D2, chess.D4)
67
+        self.assertEqual(b.piece_at(chess.D4).symbol(), "P")
68
+        setup.move(b, chess.D4, None)
69
+        self.assertIsNone(b.piece_at(chess.D4))
70
+
71
+
72
+if __name__ == "__main__":
73
+    unittest.main()