Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

schach / tests / test_explain.py · 18.5 KB · at 3c63b1d52560 · raw

Outline: 53 definitions
1
import shutil
2
import unittest
3
4
import chess
5
import chess.engine
6
import chess.pgn
7
8
from schach import explain
9
10
11
def m(uci):
12
    return chess.Move.from_uci(uci)
13
14
15
class DescribeTest(unittest.TestCase):
16
    def test_knight_fork_on_king_and_rook(self):
17
        board = chess.Board("r3k3/8/8/8/8/8/3N4/4K3 w - - 0 1")
18
        sentences, shapes = explain.describe(board, m("d2c4"), chess.WHITE)
19
        self.assertFalse(any("Gabel" in s for s in sentences))  # c4 greift nichts an
20
        board = chess.Board("r3k3/8/8/3N4/8/8/8/4K3 w - - 0 1")
21
        sentences, shapes = explain.describe(board, m("d5c7"), chess.WHITE)
22
        self.assertTrue(any(s.startswith("Gabel: Der Springer") for s in sentences), sentences)
23
        self.assertIn("Schach!", sentences)
24
        self.assertEqual({s[0] for s in shapes}, {chess.E8, chess.A8})
25
26
    def test_capture_names_victim(self):
27
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
28
        sentences, _ = explain.describe(board, m("c3d5"), chess.WHITE)
29
        self.assertEqual(sentences[0], "Du schlägst die Dame auf d5.")
30
31
    def test_opponent_capture_uses_color(self):
32
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 b - - 0 1")
33
        sentences, _ = explain.describe(board, m("d5c3"), chess.WHITE)
34
        self.assertEqual(sentences[0], "Schwarz schlägt den Springer auf c3.")
35
36
    def test_pin_against_king(self):
37
        board = chess.Board("4k3/8/2n5/8/8/8/8/4KB2 w - - 0 1")
38
        sentences, shapes = explain.describe(board, m("f1b5"), chess.WHITE)
39
        self.assertTrue(any(s.startswith("Fesselung: Der Springer auf c6") for s in sentences), sentences)
40
        self.assertIn((chess.C6, chess.C6, "red"), shapes)
41
42
    def test_mate(self):
43
        board = chess.Board("6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1")
44
        sentences, _ = explain.describe(board, m("a1a8"), chess.WHITE)
45
        self.assertEqual(sentences, ["Schachmatt!"])
46
47
48
class TrimTest(unittest.TestCase):
49
    def test_attack_with_checks_runs_on(self):
50
        board = chess.Board()
51
        for san in "e4 g6 Nf3 g5 h3 f6".split():
52
            board.push_san(san)
53
        pv = [m(u) for u in "f3g5 e7e6 d1h5 e8e7 h5f7 e7d6 g5h7 f8h6".split()]
54
        self.assertEqual(explain.trim(board, pv), pv[:7])  # bis Sxh7, nicht schon nach Sxg5 e6
55
56
    def test_stops_after_exchange_settles(self):
57
        # Sxd5, danach ruhige Züge: nach der Antwort ist der Gewinn eingefahren
58
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
59
        pv = [m("c3d5"), m("e8d7"), m("d5f4"), m("d7d6"), m("e1e2"), m("d6d5")]
60
        self.assertEqual(explain.trim(board, pv), pv[:2])
61
62
    def test_quiet_line_is_short(self):
63
        board = chess.Board()
64
        pv = [m(u) for u in ("e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6", "b5a4")]
65
        self.assertEqual(len(explain.trim(board, pv)), explain.QUIET_PLIES)
66
67
    def test_line_goes_on_to_mate_after_exchange(self):
68
        # 10. dxe4 Sxe4 11. Dd8#: nach dem Tausch kommt noch das Matt
69
        board = chess.Board(AFTER_DXE4)
70
        pv = [m("d3e4"), m("f6e4"), m("d1d8")]
71
        self.assertEqual(explain.trim(board, pv), pv)
72
73
    def test_mate_ends_line(self):
74
        board = chess.Board("6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1")
75
        self.assertEqual(explain.trim(board, [m("a1a8"), m("g8h8")]), [m("a1a8")])
76
77
78
class BuildStepsTest(unittest.TestCase):
79
    def test_parried_threat_and_result(self):
80
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
81
        steps = explain.build_steps(board, [m("c3d5"), m("e8d7")])
82
        self.assertEqual(len(steps), 1)  # Kd7 ist ruhig: nur Sxd5 mit Ergebnis
83
        self.assertIn("Ergebnis: Du gewinnst die Dame.", steps[-1][1])
84
85
    def test_threat_mentioned_when_not_replayed(self):
86
        board = chess.Board("r1bqkbnr/pppp1ppp/2n5/4p2Q/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 3 3")
87
        steps = explain.build_steps(board, [m("g7g6"), m("h5f3")], threat=m("h5f7"))
88
        self.assertIn("Das wehrt die Drohung Dxf7# ab.", steps[0][1])
89
        self.assertIn((chess.H5, chess.F7, "threat"), steps[0][2])
90
91
    def test_quiet_continuation_is_dropped(self):
92
        # Lb3 weicht dem Bauern aus; danach passiert nichts mehr, was zum Zug gehört
93
        board = chess.Board("rn1qkb1r/5ppp/2pp1n2/1p2p3/2B1P1b1/3P1N2/PPP2PPP/RNBQR1K1 w kq - 0 7")
94
        pv = [m("c4b3"), m("a7a6"), m("h2h3"), m("g4h5")]
95
        steps = explain.build_steps(board, pv, threat=m("b5c4"))
96
        self.assertEqual([s[0] for s in steps], [m("c4b3")])
97
        self.assertIn("stand in Gefahr", steps[0][1])
98
99
100
AFTER_DXE4 = "rn2kb1r/p4ppp/2p2n2/Bp2p3/4p1b1/1B1P1N2/PPP2PPP/RN1QR1K1 w kq - 0 10"  # vor 10. dxe4
101
102
103
class MateThreatTest(unittest.TestCase):
104
    def test_missed_mate_threat(self):
105
        tree = explain.comment(explain.line(chess.Board(AFTER_DXE4), [m("d3e4"), m("f6e4"), m("d1d8")]))
106
        first = tree.first()
107
        self.assertIn("Du drohst Dd8#.", first.comment)
108
        self.assertIn("Das übersieht Dd8#.", first.variations[0].comment)
109
        self.assertIn((chess.D1, chess.D8, "hint"), tree.shapes(first.variations[0]))
110
111
    def test_parried_mate_threat(self):
112
        tree = explain.comment(explain.line(chess.Board(AFTER_DXE4), [m("d3e4"), m("b8d7")]))
113
        self.assertIn("Das wehrt Dd8# ab.", tree.first().variations[0].comment)
114
115
116
QUEEN_UP = "4k3/p7/8/3q4/8/2N5/P7/4K3 w - - 0 1"
117
118
119
class FakeEngine:
120
    """Stockfish-Ersatz: Bewertung je erstem Zug (Weiß, Centipawns), Fortsetzung ein Königszug."""
121
122
    def __init__(self, scores, pv):
123
        self.scores, self.pv = scores, pv
124
125
    def analyse(self, board, limit, root_moves=None, multipv=None):
126
        move = root_moves[0] if root_moves else next(iter(board.legal_moves))
127
        value = self.scores.get(move.uci(), 0)
128
        score = chess.engine.Mate(int(value[1:])) if isinstance(value, str) else chess.engine.Cp(value)
129
        info = {"score": chess.engine.PovScore(score, chess.WHITE),
130
                "pv": [move] + self.pv.get(move.uci(), [])}
131
        return [info] if multipv else info
132
133
134
class TreeTest(unittest.TestCase):
135
    def grow(self, scores):
136
        engine = FakeEngine(scores, {"c3d5": [m("e8f7")], "e8d7": [m("e1e2")], "e8d8": [m("e1e2")],
137
                                     "e8f7": [m("e1e2")]})
138
        maia = lambda board: [(m("e8d7"), 0.6), (m("e8d8"), 0.3), (m("e8f8"), 0.05)]  # noqa: E731
139
        return explain.grow(chess.Board(QUEEN_UP), m("c3d5"), engine, maia, "Maia 600")
140
141
    def test_opponent_fork_from_maia_and_stockfish(self):
142
        tree = self.grow({"c3d5": 900, "e8d7": 900, "e8d8": 900, "e8f7": 900})
143
        replies = tree.first().variations
144
        self.assertEqual([r.move for r in replies], [m("e8d7"), m("e8d8"), m("e8f7")])  # Maia zuerst
145
        self.assertEqual(tree.label(replies[0]), "Maia 600 · meistens")
146
        self.assertEqual(tree.label(replies[1]), "Maia 600 · oft")
147
        self.assertEqual(tree.label(replies[2]), "Bester Zug")
148
        self.assertEqual(replies[0].variations[0].move, m("e1e2"))  # Hauptlinie geht weiter
149
150
    def test_prune_keeps_only_forks_that_matter(self):
151
        tree = explain.prune(self.grow({"c3d5": 900, "e8d7": 900, "e8d8": 910, "e8f7": 300}))
152
        replies = tree.first().variations
153
        self.assertEqual([r.move for r in replies], [m("e8d7"), m("e8f7")])  # d8 ist wie d7: weg
154
155
    def test_prune_keeps_fork_between_mate_and_no_mate(self):
156
        # Gewinnchance 97 % gegen Matt: kaum Abstand in Prozent, aber ein echter Unterschied
157
        tree = explain.prune(self.grow({"c3d5": 900, "e8d7": "#3", "e8d8": 900, "e8f7": 900}))
158
        self.assertEqual([r.move for r in tree.first().variations], [m("e8d7"), m("e8d8"), m("e8f7")])
159
160
    def test_comment_names_maia_and_best_defence(self):
161
        tree = explain.comment(explain.prune(self.grow({"c3d5": 900, "e8d7": 900, "e8f7": 300})))
162
        replies = tree.first().variations
163
        self.assertIn("So spielt Maia 600 meistens.", replies[0].comment)
164
        self.assertIn("Die beste Verteidigung.", replies[-1].comment)
165
        self.assertIn("Ergebnis: Du gewinnst die Dame.", replies[0].comment)
166
167
    def test_from_steps_keeps_course_comments(self):
168
        board = chess.Board()
169
        tree = explain.from_steps(board.fen(), [(m("e2e4"), "Zentrum", ((12, 28, "green"),)), (m("e7e5"), "", ())])
170
        self.assertEqual([n.move for n in tree.game.mainline()], [m("e2e4"), m("e7e5")])
171
        self.assertEqual(tree.first().comment, "Zentrum")
172
        self.assertEqual(tree.shapes(tree.first()), ((12, 28, "green"),))
173
174
175
class OwnMoveTest(unittest.TestCase):
176
    def test_opponent_move_is_answered_for_hero(self):
177
        board = chess.Board(QUEEN_UP.replace(" w ", " b "))
178
        engine = FakeEngine({"e8d7": 900}, {"e8d7": [m("c3d5")]})
179
        tree = explain.grow(board, m("e8d7"), engine, hero=chess.WHITE)
180
        self.assertEqual(tree.hero, chess.WHITE)
181
        self.assertEqual(tree.first().variations[0].move, m("c3d5"))
182
        explain.comment(tree)
183
        self.assertIn("Diesen Zug hast du ausprobiert.", tree.first().comment)
184
        self.assertIn("Du schlägst die Dame", tree.first().variations[0].comment)
185
186
    def test_better_move_is_named(self):
187
        tree = explain.comment(explain.line(chess.Board(QUEEN_UP), [m("e1e2")]), better=m("c3d5"))
188
        self.assertIn("Besser war Sxd5.", tree.first().comment)
189
        self.assertNotIn("besten Zug", tree.first().comment)
190
191
    def test_graft_copies_moves_comments_and_meta(self):
192
        tree = explain.line(chess.Board(QUEEN_UP), [m("c3d5")])
193
        sub = explain.comment(explain.line(tree.first().board(), [m("e8d7"), m("d5f4")]))
194
        sub.info(sub.first())["label"] = "Maia 600 · oft"
195
        child = explain.graft(tree, tree.first(), sub)
196
        self.assertIs(child, tree.first().variations[0])
197
        self.assertEqual(child.variations[0].move, m("d5f4"))
198
        self.assertEqual(tree.label(child), "Maia 600 · oft")
199
        self.assertEqual(child.comment, sub.first().comment)
200
201
    def test_merge_reuses_existing_moves_and_names_new_branches(self):
202
        # Partie: 1. Sxd5 Kd7, dazu eine Erklärung mit 1. Sxd5 Kd7 2. Sf4 und 1. Sxd5 Ke7
203
        game = explain.line(chess.Board(QUEEN_UP), [m("c3d5"), m("e8d7")])
204
        played = game.first()
205
        game.info(played)["label"] = "Partie"
206
        played.comment = "gespielt"
207
        sub = explain.line(chess.Board(QUEEN_UP), [m("c3d5"), m("e8d7"), m("d5f4")])
208
        sub.first().add_variation(m("e8e7"), comment="auch möglich")
209
        sub.first().comment = "aus der Erklärung"
210
        sub.info(sub.first().variations[1])["label"] = "Bester Zug"
211
        found = explain.merge(game, game.game, sub, sub.game.variations, "Warum nicht?")
212
        self.assertIs(found[sub.first()], played)  # vorhandener Zug: weiterbenutzt
213
        self.assertEqual(played.comment, "gespielt")  # … mit seinem Kommentar
214
        self.assertEqual(game.label(played), "Partie")
215
        reply = played.variations[0]
216
        self.assertEqual([c.move for c in reply.variations], [m("d5f4")])
217
        self.assertEqual(reply.variations[0].starting_comment, "Warum nicht?")  # zweigt an Vorhandenem ab
218
        side = played.variations[1]
219
        self.assertEqual((side.move, side.comment, side.starting_comment), (m("e8e7"), "auch möglich", "Warum nicht?"))
220
        self.assertEqual(game.label(side), "Bester Zug")
221
        # noch einmal gemischt: nichts doppelt
222
        explain.merge(game, game.game, sub, sub.game.variations, "Warum nicht?")
223
        self.assertEqual(len(played.variations), 2)
224
        self.assertEqual(len(reply.variations), 1)
225
226
    def test_merge_names_only_where_the_branch_leaves_the_tree(self):
227
        game = explain.line(chess.Board(QUEEN_UP), [m("c3d5")])
228
        sub = explain.line(chess.Board(QUEEN_UP), [m("e1e2"), m("e8d7"), m("c3d5")])
229
        found = explain.merge(game, game.game, sub, sub.game.variations, "Hinweis")
230
        first = found[sub.first()]
231
        self.assertEqual(first.starting_comment, "Hinweis")
232
        self.assertEqual(first.variations[0].starting_comment, "")
233
        self.assertEqual(first.variations[0].variations[0].starting_comment, "")
234
235
236
@unittest.skipUnless(shutil.which("stockfish"), "stockfish nicht installiert")
237
class ExplainJobTest(unittest.TestCase):
238
    def test_job_explains_given_move(self):
239
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
240
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
241
        try:
242
            demo = explain.explain_job(board, m("c3d5"), chess.engine.Limit(depth=10))(engine)
243
        finally:
244
            engine.quit()
245
        self.assertEqual(demo.first().move, m("c3d5"))
246
        self.assertEqual(demo.game.board().fen(), board.fen())
247
248
    def test_why_not_shows_played_and_best_move(self):
249
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
250
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
251
        try:
252
            tree = explain.why_not_job(board, m("e1e2"), limit=chess.engine.Limit(depth=10))(engine)
253
        finally:
254
            engine.quit()
255
        self.assertEqual([n.move for n in tree.game.variations], [m("e1e2"), m("c3d5")])
256
        self.assertEqual(tree.label(tree.first()), "Gespielt")
257
        self.assertIn("Besser war Sxd5: Damit gewinnst du die Dame.", tree.first().comment)
258
259
    def test_why_not_for_the_game_tree_puts_the_reason_on_the_best_move(self):
260
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
261
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
262
        try:
263
            tree = explain.why_not_job(board, m("e1e2"), limit=chess.engine.Limit(depth=10),
264
                                       variation=True)(engine)
265
        finally:
266
            engine.quit()
267
        best = tree.game.variations[1]
268
        self.assertTrue(best.comment.startswith("Besser als Ke2. Damit gewinnst du die Dame."), best.comment)
269
        self.assertNotIn("Ausgangsstellung", best.comment)  # kein Wegweiser zur Vorführung
270
271
    def test_why_not_says_when_the_played_move_is_still_fine(self):
272
        # 10. Sf4 (statt 10. d4): Weiß steht danach weiter besser, d4 bringt nur mehr
273
        board = chess.Board()
274
        for san in "e4 d5 exd5 Qxd5 Nc3 Qa5 Bc4 c6 d3 Nf6 Ne2 Bg4 O-O e5 h3 Bh5 Qe1 Bc5".split():
275
            board.push_san(san)
276
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
277
        try:
278
            tree = explain.why_not_job(board, m("e2f4"), limit=chess.engine.Limit(depth=14),
279
                                       variation=True)(engine)
280
        finally:
281
            engine.quit()
282
        best = tree.game.variations[1]
283
        self.assertTrue(best.comment.startswith("Besser als Sf4. Sf4 ist in Ordnung, du stehst damit "
284
                                                "weiter besser. d4 holt aber mehr heraus"), best.comment)
285
286
    def test_hint_that_is_not_stockfishs_best_says_so(self):
287
        board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1")
288
        engine = chess.engine.SimpleEngine.popen_uci("stockfish")
289
        try:
290
            tree = explain.explain_job(board, m("e1e2"), limit=chess.engine.Limit(depth=10))(engine)
291
        finally:
292
            engine.quit()
293
        self.assertIn("Stockfish findet Sxd5 besser.", tree.first().comment)
294
        # beim Hovern über „Sxd5“ zeigt der Pfeil vom Springer auf c3, auch wenn er schon gezogen hat
295
        self.assertIn((chess.D5, chess.KNIGHT, chess.C3, chess.Piece(chess.KNIGHT, chess.WHITE)),
296
                      tree.refs(tree.first()))
297
298
299
class TradeTextTest(unittest.TestCase):
300
    def test_piece_for_pawn_is_named_not_netted(self):
301
        before = chess.Board("4k3/8/8/6p1/8/5N2/8/4K3 w - - 0 1")
302
        after = chess.Board("4k3/8/8/8/8/8/8/4K3 w - - 0 1")  # Sxg5 … und der Springer ist weg
303
        self.assertEqual(explain.trade_text(before, after, chess.WHITE),
304
                         "Du gibst einen Springer und bekommst einen Bauern")
305
306
    def test_plain_gain_and_exchange(self):
307
        before = chess.Board("3qk3/8/8/8/8/8/8/3QK1N1 w - - 0 1")
308
        self.assertEqual(explain.trade_text(before, chess.Board("4k3/8/8/8/8/8/8/3QK1N1 w - - 0 1"),
309
                                            chess.WHITE), "Du gewinnst die Dame")
310
        self.assertEqual(explain.trade_text(before, chess.Board("4k3/8/8/8/8/8/8/4K1N1 w - - 0 1"),
311
                                            chess.WHITE), "ein Abtausch, das Material bleibt gleich")
312
313
    def test_pieces_text_lists_most_valuable_first(self):
314
        self.assertEqual(explain.pieces_text({chess.PAWN: 2, chess.ROOK: 1}), "einen Turm und zwei Bauern")
315
316
317
class PawnAttackTest(unittest.TestCase):
318
    def test_piece_dodging_a_pawn_push_is_explained(self):
319
        board = chess.Board("rnbqkbnr/p3p3/1ppp1p2/6pp/2B1P3/2PP1N1P/PP3PP1/RNBQ1RK1 w kq - 0 8")
320
        text, shapes = explain.describe(board, m("f3h2"), chess.WHITE)
321
        self.assertEqual(text, ["Der Springer geht dem Angriff g4 aus dem Weg."])
322
        self.assertIn((chess.G5, chess.G4, "threat"), shapes)
323
324
    def test_no_dodge_when_the_pawn_would_just_be_taken(self):
325
        board = chess.Board("4k3/8/8/6p1/8/5N2/8/4K1R1 w - - 0 1")  # den Bauern auf g4 nähme der Turm
326
        self.assertIsNone(explain._pawn_attack(board, chess.F3))
327
328
329
if __name__ == "__main__":
330
    unittest.main()
331
332
333
class SuggestionTest(unittest.TestCase):
334
    """Nachspielen: nur der eigene Zug kommt in den Baum, Antworten bleiben anklickbare Vorschläge."""
335
336
    def sub_tree(self):
337
        board = chess.Board()
338
        game = chess.pgn.Game()
339
        e4 = game.add_variation(chess.Move.from_uci("e2e4"), comment="Du ziehst e4.")
340
        e5 = e4.add_variation(chess.Move.from_uci("e7e5"))
341
        c5 = e4.add_variation(chess.Move.from_uci("c7c5"))
342
        e5.add_variation(chess.Move.from_uci("g1f3"))
343
        sub = explain.Tree(game, start=board, hero=chess.WHITE)
344
        sub.info(e5).update(maia=0.6)
345
        sub.info(c5).update(maia=0.1)
346
        return sub
347
348
    def test_only_own_move_is_grafted(self):
349
        game = chess.pgn.Game()
350
        tree = explain.Tree(game, start=chess.Board(), hero=chess.WHITE)
351
        child = explain.graft_move(tree, game, self.sub_tree())
352
        self.assertEqual(child.move, chess.Move.from_uci("e2e4"))
353
        self.assertEqual(child.comment, "Du ziehst e4.")
354
        self.assertEqual(child.variations, [])
355
        self.assertEqual(explain.suggestions(tree, child),
356
                         [(chess.Move.from_uci("e7e5"), "Maia meistens"), (chess.Move.from_uci("c7c5"), "Maia selten")])
357
358
    def test_taking_a_suggestion_offers_the_next(self):
359
        game = chess.pgn.Game()
360
        tree = explain.Tree(game, start=chess.Board(), hero=chess.WHITE)
361
        child = explain.graft_move(tree, game, self.sub_tree())
362
        reply = explain.take_suggestion(tree, child, chess.Move.from_uci("e7e5"))
363
        self.assertEqual([c.move for c in child.variations], [chess.Move.from_uci("e7e5")])
364
        self.assertEqual(explain.suggestions(tree, child), [(chess.Move.from_uci("c7c5"), "Maia selten")])
365
        self.assertEqual([m for m, _ in explain.suggestions(tree, reply)], [chess.Move.from_uci("g1f3")])