Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

chore: import existing app, add roadmap and AGPL license

public

chore: import existing app, add roadmap and AGPL license

AGPL-3.0-or-later matches Maia-3 (AGPL-3) and Stockfish (GPL-3).

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

added .hgignore +3 −0

@@ -0,0 +1,3 @@
1
+syntax: glob
2
+__pycache__/
3
+*.pyc

added LICENSE +661 −0

@@ -0,0 +1,661 @@
1
+                    GNU AFFERO GENERAL PUBLIC LICENSE
2
+                       Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+                            Preamble
9
+
10
+  The GNU Affero General Public License is a free, copyleft license for
11
+software and other kinds of works, specifically designed to ensure
12
+cooperation with the community in the case of network server software.
13
+
14
+  The licenses for most software and other practical works are designed
15
+to take away your freedom to share and change the works.  By contrast,
16
+our General Public Licenses are intended to guarantee your freedom to
17
+share and change all versions of a program--to make sure it remains free
18
+software for all its users.
19
+
20
+  When we speak of free software, we are referring to freedom, not
21
+price.  Our General Public Licenses are designed to make sure that you
22
+have the freedom to distribute copies of free software (and charge for
23
+them if you wish), that you receive source code or can get it if you
24
+want it, that you can change the software or use pieces of it in new
25
+free programs, and that you know you can do these things.
26
+
27
+  Developers that use our General Public Licenses protect your rights
28
+with two steps: (1) assert copyright on the software, and (2) offer
29
+you this License which gives you legal permission to copy, distribute
30
+and/or modify the software.
31
+
32
+  A secondary benefit of defending all users' freedom is that
33
+improvements made in alternate versions of the program, if they
34
+receive widespread use, become available for other developers to
35
+incorporate.  Many developers of free software are heartened and
36
+encouraged by the resulting cooperation.  However, in the case of
37
+software used on network servers, this result may fail to come about.
38
+The GNU General Public License permits making a modified version and
39
+letting the public access it on a server without ever releasing its
40
+source code to the public.
41
+
42
+  The GNU Affero General Public License is designed specifically to
43
+ensure that, in such cases, the modified source code becomes available
44
+to the community.  It requires the operator of a network server to
45
+provide the source code of the modified version running there to the
46
+users of that server.  Therefore, public use of a modified version, on
47
+a publicly accessible server, gives the public access to the source
48
+code of the modified version.
49
+
50
+  An older license, called the Affero General Public License and
51
+published by Affero, was designed to accomplish similar goals.  This is
52
+a different license, not a version of the Affero GPL, but Affero has
53
+released a new version of the Affero GPL which permits relicensing under
54
+this license.
55
+
56
+  The precise terms and conditions for copying, distribution and
57
+modification follow.
58
+
59
+                       TERMS AND CONDITIONS
60
+
61
+  0. Definitions.
62
+
63
+  "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+  "Copyright" also means copyright-like laws that apply to other kinds of
66
+works, such as semiconductor masks.
67
+
68
+  "The Program" refers to any copyrightable work licensed under this
69
+License.  Each licensee is addressed as "you".  "Licensees" and
70
+"recipients" may be individuals or organizations.
71
+
72
+  To "modify" a work means to copy from or adapt all or part of the work
73
+in a fashion requiring copyright permission, other than the making of an
74
+exact copy.  The resulting work is called a "modified version" of the
75
+earlier work or a work "based on" the earlier work.
76
+
77
+  A "covered work" means either the unmodified Program or a work based
78
+on the Program.
79
+
80
+  To "propagate" a work means to do anything with it that, without
81
+permission, would make you directly or secondarily liable for
82
+infringement under applicable copyright law, except executing it on a
83
+computer or modifying a private copy.  Propagation includes copying,
84
+distribution (with or without modification), making available to the
85
+public, and in some countries other activities as well.
86
+
87
+  To "convey" a work means any kind of propagation that enables other
88
+parties to make or receive copies.  Mere interaction with a user through
89
+a computer network, with no transfer of a copy, is not conveying.
90
+
91
+  An interactive user interface displays "Appropriate Legal Notices"
92
+to the extent that it includes a convenient and prominently visible
93
+feature that (1) displays an appropriate copyright notice, and (2)
94
+tells the user that there is no warranty for the work (except to the
95
+extent that warranties are provided), that licensees may convey the
96
+work under this License, and how to view a copy of this License.  If
97
+the interface presents a list of user commands or options, such as a
98
+menu, a prominent item in the list meets this criterion.
99
+
100
+  1. Source Code.
101
+
102
+  The "source code" for a work means the preferred form of the work
103
+for making modifications to it.  "Object code" means any non-source
104
+form of a work.
105
+
106
+  A "Standard Interface" means an interface that either is an official
107
+standard defined by a recognized standards body, or, in the case of
108
+interfaces specified for a particular programming language, one that
109
+is widely used among developers working in that language.
110
+
111
+  The "System Libraries" of an executable work include anything, other
112
+than the work as a whole, that (a) is included in the normal form of
113
+packaging a Major Component, but which is not part of that Major
114
+Component, and (b) serves only to enable use of the work with that
115
+Major Component, or to implement a Standard Interface for which an
116
+implementation is available to the public in source code form.  A
117
+"Major Component", in this context, means a major essential component
118
+(kernel, window system, and so on) of the specific operating system
119
+(if any) on which the executable work runs, or a compiler used to
120
+produce the work, or an object code interpreter used to run it.
121
+
122
+  The "Corresponding Source" for a work in object code form means all
123
+the source code needed to generate, install, and (for an executable
124
+work) run the object code and to modify the work, including scripts to
125
+control those activities.  However, it does not include the work's
126
+System Libraries, or general-purpose tools or generally available free
127
+programs which are used unmodified in performing those activities but
128
+which are not part of the work.  For example, Corresponding Source
129
+includes interface definition files associated with source files for
130
+the work, and the source code for shared libraries and dynamically
131
+linked subprograms that the work is specifically designed to require,
132
+such as by intimate data communication or control flow between those
133
+subprograms and other parts of the work.
134
+
135
+  The Corresponding Source need not include anything that users
136
+can regenerate automatically from other parts of the Corresponding
137
+Source.
138
+
139
+  The Corresponding Source for a work in source code form is that
140
+same work.
141
+
142
+  2. Basic Permissions.
143
+
144
+  All rights granted under this License are granted for the term of
145
+copyright on the Program, and are irrevocable provided the stated
146
+conditions are met.  This License explicitly affirms your unlimited
147
+permission to run the unmodified Program.  The output from running a
148
+covered work is covered by this License only if the output, given its
149
+content, constitutes a covered work.  This License acknowledges your
150
+rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+  You may make, run and propagate covered works that you do not
153
+convey, without conditions so long as your license otherwise remains
154
+in force.  You may convey covered works to others for the sole purpose
155
+of having them make modifications exclusively for you, or provide you
156
+with facilities for running those works, provided that you comply with
157
+the terms of this License in conveying all material for which you do
158
+not control copyright.  Those thus making or running the covered works
159
+for you must do so exclusively on your behalf, under your direction
160
+and control, on terms that prohibit them from making any copies of
161
+your copyrighted material outside their relationship with you.
162
+
163
+  Conveying under any other circumstances is permitted solely under
164
+the conditions stated below.  Sublicensing is not allowed; section 10
165
+makes it unnecessary.
166
+
167
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+  No covered work shall be deemed part of an effective technological
170
+measure under any applicable law fulfilling obligations under article
171
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+similar laws prohibiting or restricting circumvention of such
173
+measures.
174
+
175
+  When you convey a covered work, you waive any legal power to forbid
176
+circumvention of technological measures to the extent such circumvention
177
+is effected by exercising rights under this License with respect to
178
+the covered work, and you disclaim any intention to limit operation or
179
+modification of the work as a means of enforcing, against the work's
180
+users, your or third parties' legal rights to forbid circumvention of
181
+technological measures.
182
+
183
+  4. Conveying Verbatim Copies.
184
+
185
+  You may convey verbatim copies of the Program's source code as you
186
+receive it, in any medium, provided that you conspicuously and
187
+appropriately publish on each copy an appropriate copyright notice;
188
+keep intact all notices stating that this License and any
189
+non-permissive terms added in accord with section 7 apply to the code;
190
+keep intact all notices of the absence of any warranty; and give all
191
+recipients a copy of this License along with the Program.
192
+
193
+  You may charge any price or no price for each copy that you convey,
194
+and you may offer support or warranty protection for a fee.
195
+
196
+  5. Conveying Modified Source Versions.
197
+
198
+  You may convey a work based on the Program, or the modifications to
199
+produce it from the Program, in the form of source code under the
200
+terms of section 4, provided that you also meet all of these conditions:
201
+
202
+    a) The work must carry prominent notices stating that you modified
203
+    it, and giving a relevant date.
204
+
205
+    b) The work must carry prominent notices stating that it is
206
+    released under this License and any conditions added under section
207
+    7.  This requirement modifies the requirement in section 4 to
208
+    "keep intact all notices".
209
+
210
+    c) You must license the entire work, as a whole, under this
211
+    License to anyone who comes into possession of a copy.  This
212
+    License will therefore apply, along with any applicable section 7
213
+    additional terms, to the whole of the work, and all its parts,
214
+    regardless of how they are packaged.  This License gives no
215
+    permission to license the work in any other way, but it does not
216
+    invalidate such permission if you have separately received it.
217
+
218
+    d) If the work has interactive user interfaces, each must display
219
+    Appropriate Legal Notices; however, if the Program has interactive
220
+    interfaces that do not display Appropriate Legal Notices, your
221
+    work need not make them do so.
222
+
223
+  A compilation of a covered work with other separate and independent
224
+works, which are not by their nature extensions of the covered work,
225
+and which are not combined with it such as to form a larger program,
226
+in or on a volume of a storage or distribution medium, is called an
227
+"aggregate" if the compilation and its resulting copyright are not
228
+used to limit the access or legal rights of the compilation's users
229
+beyond what the individual works permit.  Inclusion of a covered work
230
+in an aggregate does not cause this License to apply to the other
231
+parts of the aggregate.
232
+
233
+  6. Conveying Non-Source Forms.
234
+
235
+  You may convey a covered work in object code form under the terms
236
+of sections 4 and 5, provided that you also convey the
237
+machine-readable Corresponding Source under the terms of this License,
238
+in one of these ways:
239
+
240
+    a) Convey the object code in, or embodied in, a physical product
241
+    (including a physical distribution medium), accompanied by the
242
+    Corresponding Source fixed on a durable physical medium
243
+    customarily used for software interchange.
244
+
245
+    b) Convey the object code in, or embodied in, a physical product
246
+    (including a physical distribution medium), accompanied by a
247
+    written offer, valid for at least three years and valid for as
248
+    long as you offer spare parts or customer support for that product
249
+    model, to give anyone who possesses the object code either (1) a
250
+    copy of the Corresponding Source for all the software in the
251
+    product that is covered by this License, on a durable physical
252
+    medium customarily used for software interchange, for a price no
253
+    more than your reasonable cost of physically performing this
254
+    conveying of source, or (2) access to copy the
255
+    Corresponding Source from a network server at no charge.
256
+
257
+    c) Convey individual copies of the object code with a copy of the
258
+    written offer to provide the Corresponding Source.  This
259
+    alternative is allowed only occasionally and noncommercially, and
260
+    only if you received the object code with such an offer, in accord
261
+    with subsection 6b.
262
+
263
+    d) Convey the object code by offering access from a designated
264
+    place (gratis or for a charge), and offer equivalent access to the
265
+    Corresponding Source in the same way through the same place at no
266
+    further charge.  You need not require recipients to copy the
267
+    Corresponding Source along with the object code.  If the place to
268
+    copy the object code is a network server, the Corresponding Source
269
+    may be on a different server (operated by you or a third party)
270
+    that supports equivalent copying facilities, provided you maintain
271
+    clear directions next to the object code saying where to find the
272
+    Corresponding Source.  Regardless of what server hosts the
273
+    Corresponding Source, you remain obligated to ensure that it is
274
+    available for as long as needed to satisfy these requirements.
275
+
276
+    e) Convey the object code using peer-to-peer transmission, provided
277
+    you inform other peers where the object code and Corresponding
278
+    Source of the work are being offered to the general public at no
279
+    charge under subsection 6d.
280
+
281
+  A separable portion of the object code, whose source code is excluded
282
+from the Corresponding Source as a System Library, need not be
283
+included in conveying the object code work.
284
+
285
+  A "User Product" is either (1) a "consumer product", which means any
286
+tangible personal property which is normally used for personal, family,
287
+or household purposes, or (2) anything designed or sold for incorporation
288
+into a dwelling.  In determining whether a product is a consumer product,
289
+doubtful cases shall be resolved in favor of coverage.  For a particular
290
+product received by a particular user, "normally used" refers to a
291
+typical or common use of that class of product, regardless of the status
292
+of the particular user or of the way in which the particular user
293
+actually uses, or expects or is expected to use, the product.  A product
294
+is a consumer product regardless of whether the product has substantial
295
+commercial, industrial or non-consumer uses, unless such uses represent
296
+the only significant mode of use of the product.
297
+
298
+  "Installation Information" for a User Product means any methods,
299
+procedures, authorization keys, or other information required to install
300
+and execute modified versions of a covered work in that User Product from
301
+a modified version of its Corresponding Source.  The information must
302
+suffice to ensure that the continued functioning of the modified object
303
+code is in no case prevented or interfered with solely because
304
+modification has been made.
305
+
306
+  If you convey an object code work under this section in, or with, or
307
+specifically for use in, a User Product, and the conveying occurs as
308
+part of a transaction in which the right of possession and use of the
309
+User Product is transferred to the recipient in perpetuity or for a
310
+fixed term (regardless of how the transaction is characterized), the
311
+Corresponding Source conveyed under this section must be accompanied
312
+by the Installation Information.  But this requirement does not apply
313
+if neither you nor any third party retains the ability to install
314
+modified object code on the User Product (for example, the work has
315
+been installed in ROM).
316
+
317
+  The requirement to provide Installation Information does not include a
318
+requirement to continue to provide support service, warranty, or updates
319
+for a work that has been modified or installed by the recipient, or for
320
+the User Product in which it has been modified or installed.  Access to a
321
+network may be denied when the modification itself materially and
322
+adversely affects the operation of the network or violates the rules and
323
+protocols for communication across the network.
324
+
325
+  Corresponding Source conveyed, and Installation Information provided,
326
+in accord with this section must be in a format that is publicly
327
+documented (and with an implementation available to the public in
328
+source code form), and must require no special password or key for
329
+unpacking, reading or copying.
330
+
331
+  7. Additional Terms.
332
+
333
+  "Additional permissions" are terms that supplement the terms of this
334
+License by making exceptions from one or more of its conditions.
335
+Additional permissions that are applicable to the entire Program shall
336
+be treated as though they were included in this License, to the extent
337
+that they are valid under applicable law.  If additional permissions
338
+apply only to part of the Program, that part may be used separately
339
+under those permissions, but the entire Program remains governed by
340
+this License without regard to the additional permissions.
341
+
342
+  When you convey a copy of a covered work, you may at your option
343
+remove any additional permissions from that copy, or from any part of
344
+it.  (Additional permissions may be written to require their own
345
+removal in certain cases when you modify the work.)  You may place
346
+additional permissions on material, added by you to a covered work,
347
+for which you have or can give appropriate copyright permission.
348
+
349
+  Notwithstanding any other provision of this License, for material you
350
+add to a covered work, you may (if authorized by the copyright holders of
351
+that material) supplement the terms of this License with terms:
352
+
353
+    a) Disclaiming warranty or limiting liability differently from the
354
+    terms of sections 15 and 16 of this License; or
355
+
356
+    b) Requiring preservation of specified reasonable legal notices or
357
+    author attributions in that material or in the Appropriate Legal
358
+    Notices displayed by works containing it; or
359
+
360
+    c) Prohibiting misrepresentation of the origin of that material, or
361
+    requiring that modified versions of such material be marked in
362
+    reasonable ways as different from the original version; or
363
+
364
+    d) Limiting the use for publicity purposes of names of licensors or
365
+    authors of the material; or
366
+
367
+    e) Declining to grant rights under trademark law for use of some
368
+    trade names, trademarks, or service marks; or
369
+
370
+    f) Requiring indemnification of licensors and authors of that
371
+    material by anyone who conveys the material (or modified versions of
372
+    it) with contractual assumptions of liability to the recipient, for
373
+    any liability that these contractual assumptions directly impose on
374
+    those licensors and authors.
375
+
376
+  All other non-permissive additional terms are considered "further
377
+restrictions" within the meaning of section 10.  If the Program as you
378
+received it, or any part of it, contains a notice stating that it is
379
+governed by this License along with a term that is a further
380
+restriction, you may remove that term.  If a license document contains
381
+a further restriction but permits relicensing or conveying under this
382
+License, you may add to a covered work material governed by the terms
383
+of that license document, provided that the further restriction does
384
+not survive such relicensing or conveying.
385
+
386
+  If you add terms to a covered work in accord with this section, you
387
+must place, in the relevant source files, a statement of the
388
+additional terms that apply to those files, or a notice indicating
389
+where to find the applicable terms.
390
+
391
+  Additional terms, permissive or non-permissive, may be stated in the
392
+form of a separately written license, or stated as exceptions;
393
+the above requirements apply either way.
394
+
395
+  8. Termination.
396
+
397
+  You may not propagate or modify a covered work except as expressly
398
+provided under this License.  Any attempt otherwise to propagate or
399
+modify it is void, and will automatically terminate your rights under
400
+this License (including any patent licenses granted under the third
401
+paragraph of section 11).
402
+
403
+  However, if you cease all violation of this License, then your
404
+license from a particular copyright holder is reinstated (a)
405
+provisionally, unless and until the copyright holder explicitly and
406
+finally terminates your license, and (b) permanently, if the copyright
407
+holder fails to notify you of the violation by some reasonable means
408
+prior to 60 days after the cessation.
409
+
410
+  Moreover, your license from a particular copyright holder is
411
+reinstated permanently if the copyright holder notifies you of the
412
+violation by some reasonable means, this is the first time you have
413
+received notice of violation of this License (for any work) from that
414
+copyright holder, and you cure the violation prior to 30 days after
415
+your receipt of the notice.
416
+
417
+  Termination of your rights under this section does not terminate the
418
+licenses of parties who have received copies or rights from you under
419
+this License.  If your rights have been terminated and not permanently
420
+reinstated, you do not qualify to receive new licenses for the same
421
+material under section 10.
422
+
423
+  9. Acceptance Not Required for Having Copies.
424
+
425
+  You are not required to accept this License in order to receive or
426
+run a copy of the Program.  Ancillary propagation of a covered work
427
+occurring solely as a consequence of using peer-to-peer transmission
428
+to receive a copy likewise does not require acceptance.  However,
429
+nothing other than this License grants you permission to propagate or
430
+modify any covered work.  These actions infringe copyright if you do
431
+not accept this License.  Therefore, by modifying or propagating a
432
+covered work, you indicate your acceptance of this License to do so.
433
+
434
+  10. Automatic Licensing of Downstream Recipients.
435
+
436
+  Each time you convey a covered work, the recipient automatically
437
+receives a license from the original licensors, to run, modify and
438
+propagate that work, subject to this License.  You are not responsible
439
+for enforcing compliance by third parties with this License.
440
+
441
+  An "entity transaction" is a transaction transferring control of an
442
+organization, or substantially all assets of one, or subdividing an
443
+organization, or merging organizations.  If propagation of a covered
444
+work results from an entity transaction, each party to that
445
+transaction who receives a copy of the work also receives whatever
446
+licenses to the work the party's predecessor in interest had or could
447
+give under the previous paragraph, plus a right to possession of the
448
+Corresponding Source of the work from the predecessor in interest, if
449
+the predecessor has it or can get it with reasonable efforts.
450
+
451
+  You may not impose any further restrictions on the exercise of the
452
+rights granted or affirmed under this License.  For example, you may
453
+not impose a license fee, royalty, or other charge for exercise of
454
+rights granted under this License, and you may not initiate litigation
455
+(including a cross-claim or counterclaim in a lawsuit) alleging that
456
+any patent claim is infringed by making, using, selling, offering for
457
+sale, or importing the Program or any portion of it.
458
+
459
+  11. Patents.
460
+
461
+  A "contributor" is a copyright holder who authorizes use under this
462
+License of the Program or a work on which the Program is based.  The
463
+work thus licensed is called the contributor's "contributor version".
464
+
465
+  A contributor's "essential patent claims" are all patent claims
466
+owned or controlled by the contributor, whether already acquired or
467
+hereafter acquired, that would be infringed by some manner, permitted
468
+by this License, of making, using, or selling its contributor version,
469
+but do not include claims that would be infringed only as a
470
+consequence of further modification of the contributor version.  For
471
+purposes of this definition, "control" includes the right to grant
472
+patent sublicenses in a manner consistent with the requirements of
473
+this License.
474
+
475
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+patent license under the contributor's essential patent claims, to
477
+make, use, sell, offer for sale, import and otherwise run, modify and
478
+propagate the contents of its contributor version.
479
+
480
+  In the following three paragraphs, a "patent license" is any express
481
+agreement or commitment, however denominated, not to enforce a patent
482
+(such as an express permission to practice a patent or covenant not to
483
+sue for patent infringement).  To "grant" such a patent license to a
484
+party means to make such an agreement or commitment not to enforce a
485
+patent against the party.
486
+
487
+  If you convey a covered work, knowingly relying on a patent license,
488
+and the Corresponding Source of the work is not available for anyone
489
+to copy, free of charge and under the terms of this License, through a
490
+publicly available network server or other readily accessible means,
491
+then you must either (1) cause the Corresponding Source to be so
492
+available, or (2) arrange to deprive yourself of the benefit of the
493
+patent license for this particular work, or (3) arrange, in a manner
494
+consistent with the requirements of this License, to extend the patent
495
+license to downstream recipients.  "Knowingly relying" means you have
496
+actual knowledge that, but for the patent license, your conveying the
497
+covered work in a country, or your recipient's use of the covered work
498
+in a country, would infringe one or more identifiable patents in that
499
+country that you have reason to believe are valid.
500
+
501
+  If, pursuant to or in connection with a single transaction or
502
+arrangement, you convey, or propagate by procuring conveyance of, a
503
+covered work, and grant a patent license to some of the parties
504
+receiving the covered work authorizing them to use, propagate, modify
505
+or convey a specific copy of the covered work, then the patent license
506
+you grant is automatically extended to all recipients of the covered
507
+work and works based on it.
508
+
509
+  A patent license is "discriminatory" if it does not include within
510
+the scope of its coverage, prohibits the exercise of, or is
511
+conditioned on the non-exercise of one or more of the rights that are
512
+specifically granted under this License.  You may not convey a covered
513
+work if you are a party to an arrangement with a third party that is
514
+in the business of distributing software, under which you make payment
515
+to the third party based on the extent of your activity of conveying
516
+the work, and under which the third party grants, to any of the
517
+parties who would receive the covered work from you, a discriminatory
518
+patent license (a) in connection with copies of the covered work
519
+conveyed by you (or copies made from those copies), or (b) primarily
520
+for and in connection with specific products or compilations that
521
+contain the covered work, unless you entered into that arrangement,
522
+or that patent license was granted, prior to 28 March 2007.
523
+
524
+  Nothing in this License shall be construed as excluding or limiting
525
+any implied license or other defenses to infringement that may
526
+otherwise be available to you under applicable patent law.
527
+
528
+  12. No Surrender of Others' Freedom.
529
+
530
+  If conditions are imposed on you (whether by court order, agreement or
531
+otherwise) that contradict the conditions of this License, they do not
532
+excuse you from the conditions of this License.  If you cannot convey a
533
+covered work so as to satisfy simultaneously your obligations under this
534
+License and any other pertinent obligations, then as a consequence you may
535
+not convey it at all.  For example, if you agree to terms that obligate you
536
+to collect a royalty for further conveying from those to whom you convey
537
+the Program, the only way you could satisfy both those terms and this
538
+License would be to refrain entirely from conveying the Program.
539
+
540
+  13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+  Notwithstanding any other provision of this License, if you modify the
543
+Program, your modified version must prominently offer all users
544
+interacting with it remotely through a computer network (if your version
545
+supports such interaction) an opportunity to receive the Corresponding
546
+Source of your version by providing access to the Corresponding Source
547
+from a network server at no charge, through some standard or customary
548
+means of facilitating copying of software.  This Corresponding Source
549
+shall include the Corresponding Source for any work covered by version 3
550
+of the GNU General Public License that is incorporated pursuant to the
551
+following paragraph.
552
+
553
+  Notwithstanding any other provision of this License, you have
554
+permission to link or combine any covered work with a work licensed
555
+under version 3 of the GNU General Public License into a single
556
+combined work, and to convey the resulting work.  The terms of this
557
+License will continue to apply to the part which is the covered work,
558
+but the work with which it is combined will remain governed by version
559
+3 of the GNU General Public License.
560
+
561
+  14. Revised Versions of this License.
562
+
563
+  The Free Software Foundation may publish revised and/or new versions of
564
+the GNU Affero General Public License from time to time.  Such new versions
565
+will be similar in spirit to the present version, but may differ in detail to
566
+address new problems or concerns.
567
+
568
+  Each version is given a distinguishing version number.  If the
569
+Program specifies that a certain numbered version of the GNU Affero General
570
+Public License "or any later version" applies to it, you have the
571
+option of following the terms and conditions either of that numbered
572
+version or of any later version published by the Free Software
573
+Foundation.  If the Program does not specify a version number of the
574
+GNU Affero General Public License, you may choose any version ever published
575
+by the Free Software Foundation.
576
+
577
+  If the Program specifies that a proxy can decide which future
578
+versions of the GNU Affero General Public License can be used, that proxy's
579
+public statement of acceptance of a version permanently authorizes you
580
+to choose that version for the Program.
581
+
582
+  Later license versions may give you additional or different
583
+permissions.  However, no additional obligations are imposed on any
584
+author or copyright holder as a result of your choosing to follow a
585
+later version.
586
+
587
+  15. Disclaimer of Warranty.
588
+
589
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+  16. Limitation of Liability.
599
+
600
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+SUCH DAMAGES.
609
+
610
+  17. Interpretation of Sections 15 and 16.
611
+
612
+  If the disclaimer of warranty and limitation of liability provided
613
+above cannot be given local legal effect according to their terms,
614
+reviewing courts shall apply local law that most closely approximates
615
+an absolute waiver of all civil liability in connection with the
616
+Program, unless a warranty or assumption of liability accompanies a
617
+copy of the Program in return for a fee.
618
+
619
+                     END OF TERMS AND CONDITIONS
620
+
621
+            How to Apply These Terms to Your New Programs
622
+
623
+  If you develop a new program, and you want it to be of the greatest
624
+possible use to the public, the best way to achieve this is to make it
625
+free software which everyone can redistribute and change under these terms.
626
+
627
+  To do so, attach the following notices to the program.  It is safest
628
+to attach them to the start of each source file to most effectively
629
+state the exclusion of warranty; and each file should have at least
630
+the "copyright" line and a pointer to where the full notice is found.
631
+
632
+    <one line to give the program's name and a brief idea of what it does.>
633
+    Copyright (C) <year>  <name of author>
634
+
635
+    This program is free software: you can redistribute it and/or modify
636
+    it under the terms of the GNU Affero General Public License as published
637
+    by the Free Software Foundation, either version 3 of the License, or
638
+    (at your option) any later version.
639
+
640
+    This program is distributed in the hope that it will be useful,
641
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
643
+    GNU Affero General Public License for more details.
644
+
645
+    You should have received a copy of the GNU Affero General Public License
646
+    along with this program.  If not, see <https://www.gnu.org/licenses/>.
647
+
648
+Also add information on how to contact you by electronic and paper mail.
649
+
650
+  If your software can interact with users remotely through a computer
651
+network, you should also make sure that it provides a way for users to
652
+get its source.  For example, if your program is a web application, its
653
+interface could display a "Source" link that leads users to an archive
654
+of the code.  There are many ways you could offer source, and different
655
+solutions will be better for different programs; see section 13 for the
656
+specific requirements.
657
+
658
+  You should also get your employer (if you work as a programmer) or school,
659
+if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+For more information on this, and how to apply and follow the GNU AGPL, see
661
+<https://www.gnu.org/licenses/>.

added README.md +63 −0

@@ -0,0 +1,63 @@
1
+# Schach
2
+
3
+Schlichtes GNOME-Schachprogramm (Python, GTK4, libadwaita).
4
+
5
+- **Gegner:** Maia-3 (79M-Modell), Stärke 600–2500 Elo, mit menschlicher Streuung.
6
+- **Hinweis** (Taste `H`): Maia-3 auf 2000 Elo. Erster Druck lässt die Figur
7
+  leuchten, zweiter Druck auch das Zielfeld.
8
+- **Zugbewertung:** Stockfish denkt mit, während du überlegst (Top-3-Züge, live
9
+  immer tiefer); andere Züge werden nur bei Bedarf einzeln nachgerechnet.
10
+  Nur auffällige Züge bekommen ein Zeichen an der Figur: `!!` `!` `?!` `?` `??`.
11
+- **Zugliste** (Taste `A`): ein Halbzug pro Zeile, dahinter ein Weiß/Schwarz-Balken
12
+  mit der Gewinnchance – untereinander ergibt das den Verlauf der Partie. Während
13
+  der Partie zugeklappt, am Ende öffnet sie sich. Zeile anklicken zeigt die
14
+  Stellung; Knöpfe: FEN kopieren, von hier weiterspielen (als Abzweigung in
15
+  einem neuen Fenster – die Originalpartie bleibt erhalten).
16
+- **Spielstände:** mit Namen speichern (Strg+S) und laden (Strg+O). Die laufende
17
+  Partie wird automatisch gesichert und beim nächsten Start fortgesetzt.
18
+  Ablage: `~/.local/share/schach/spielstaende/` (normale PGN-Dateien).
19
+- **Rätsel** (Taste `R`, Knopf „Rätsel“): Taktikaufgaben von Lichess, Schwierigkeit
20
+  im Pfeil-Menü daneben. Angemeldet zählt jedes Ergebnis für die Lichess-Rätselwertung –
21
+  wie auf Lichess nur dann als gelöst, wenn kein falscher Zug und kein Hinweis dabei war.
22
+- **Lichess** (Menü → Lichess): anmelden per Browser (OAuth, kein Passwort im Programm;
23
+  der Zugriffsschlüssel liegt im GNOME-Schlüsselbund). Dann: Freunde herausfordern bzw.
24
+  Herausforderungen annehmen und online spielen – ohne Hinweise, Zeichen und Bewertung
25
+  (Fair Play). Nach der Partie wird sie gespeichert und analysiert. „Meine
26
+  Lichess-Partien“ lädt die letzten 30 Partien zum Nachanalysieren.
27
+- Figurensätze aus PyChess (`/usr/share/pychess/pieces`), wählbar im Menü.
28
+
29
+## Starten
30
+
31
+    ./schach.sh
32
+
33
+Abhängigkeiten: `python-gobject`, `libadwaita`, `librsvg`, `python-chess`,
34
+`stockfish`, `maia3-git` (AUR), `python-requests`, `libsecret`.
35
+
36
+Ins App-Menü aufnehmen:
37
+
38
+    cp schach.desktop ~/.local/share/applications/
39
+
40
+## Tasten
41
+
42
+| Taste | Aktion |
43
+|---|---|
44
+| Strg+N | Neue Partie |
45
+| Strg+Z | Zug zurücknehmen |
46
+| H | Hinweis |
47
+| F | Brett drehen |
48
+| A | Zugliste ein/aus |
49
+| R | Neues Rätsel |
50
+| Strg+S | Spielstand speichern |
51
+| Strg+O | Spielstände |
52
+| Strg+Umschalt+S | Als PGN exportieren |
53
+
54
+## Stellschrauben
55
+
56
+- `schach/app.py`: `HINT_ELO`, `OPPONENT_TEMPERATURE`, `MIN_REPLY_SECONDS`
57
+- `schach/annotate.py`: Schwellen für `?!`/`?`/`??` und für „einziger Zug“ (`!`)
58
+- Einstellungen: `~/.config/schach/settings.json`
59
+
60
+## Lizenz
61
+
62
+AGPL-3.0-or-later, siehe `LICENSE` (passend zu Maia-3 unter AGPL-3 und Stockfish unter GPL-3).
63
+Geplante Erweiterungen: `ROADMAP.md`.

added ROADMAP.md +466 −0

@@ -0,0 +1,466 @@
1
+# Roadmap
2
+
3
+Stand: 20.11.2026. Leitlinie bleibt die [GNOME HIG](https://developer.gnome.org/hig/).
4
+Lizenz: AGPL-3.0-or-later (siehe `LICENSE`), passend zu Maia-3 (AGPL-3) und
5
+Stockfish (GPL-3).
6
+
7
+## 0. Grundlagen: Titelleiste nach Modus und Einstellungen
8
+
9
+### 0.1 Titelleiste
10
+
11
+**Problem:** Die Titelleiste hat heute 7–9 Bedienelemente: Neu, Zurück, Öffnen,
12
+Rätsel▾ | Hinweis, Zugliste, Menü und online zusätzlich Remis und Aufgeben. Zwei
13
+HIG-Regeln werden dabei verletzt:
14
+
15
+- „Header bars should only contain a small number of controls.“
16
+- Knöpfe nur mit Text („Rätsel“, „Hinweis“, „Remis anbieten“) sollen in der
17
+  primären Titelleiste „generally be avoided“. Sie bekommen ein Symbol, ggf. mit Text.
18
+
19
+Die HIG sagt außerdem: „The content of header bars can — and should — update
20
+along with view or mode changes.“ Darauf baut der Umbau auf.
21
+
22
+**Zielbild:**
23
+
24
+```text
25
+links:   [+▾]  [↶]                         Partie gegen Maia-3
26
+                                           Maia 800 · Italienisch
27
+rechts:                     [Modus-Slot]  [▯]  [☰]
28
+```
29
+
30
+- **`+` wird zum Split-Button „Neu“.** Ein Klick startet eine neue Partie, wie bisher.
31
+  Der Pfeil öffnet ein Menü mit den Spielarten:
32
+  - Partie gegen Maia …
33
+  - Rätsel (Untermenü Schwierigkeit)
34
+  - Eröffnung üben … (siehe 6)
35
+  - Freund auf Lichess herausfordern …
36
+  - Zwei Spieler an diesem Rechner … (siehe 7)
37
+  - Partie im LAN anbieten … (siehe 8)
38
+  - Partie aus Zwischenablage (Strg+V, siehe 4)
39
+
40
+  Neue Spielarten landen in diesem Menü, nicht in der Titelleiste.
41
+- **Öffnen fliegt raus.** „Spielstände …“ steht schon im Menü, Strg+O bleibt.
42
+- **Modus-Slot** (`Gtk.Stack`, wechselt je nach Partieart):
43
+
44
+  | Modus | Inhalt |
45
+  | --- | --- |
46
+  | Gegen Maia / Rätsel / Analyse | Hilfe-Gruppe: Hinweis▾ (Split-Button, siehe 2) und Bedrohung |
47
+  | Eröffnung üben | Hinweis zeigt den Buchzug, dazu Fortschritt „Zug 4 / 8“ |
48
+  | Lichess-Partie | Knopf mit Lichess-Symbol und Benutzername. Er öffnet ein Popover: Gegner und Wertung, Remis anbieten, Im Browser öffnen, Aufgeben (destruktiv, mit Rückfrage) |
49
+  | Zwei Spieler / LAN | Hilfe-Gruppe mit Zähler „noch 2“ für den Spieler am Zug, daneben Remis/Aufgeben im selben Popover-Muster |
50
+
51
+- **Primäres Menü** nach HIG: Spielstände, Export, Lichess-Abschnitt, Brett drehen,
52
+  dann *Einstellungen*, *Tastenkürzel* (Gtk.ShortcutsWindow) und *Info zu Schach*
53
+  (Adw.AboutDialog). Das Figuren-Untermenü zieht in die Einstellungen um. So bleibt
54
+  das Menü bei 3–12 Einträgen.
55
+- **Schmale Fenster:** Ab einem `Adw.Breakpoint` wandert der Modus-Slot in eine
56
+  untere Werkzeugleiste (`ToolbarView.add_bottom_bar`). Das ist das Muster, das
57
+  die HIG für schmale Breiten nennt.
58
+
59
+**Spieler-Zeilen am Brett.** Das ist die wichtigste Ergänzung, unabhängig von der
60
+Titelleiste. Über und unter dem Brett stehen heute nur die geschlagenen Figuren.
61
+Dort kommen Name und Herkunft dazu, so wie es jede Schach-Website macht:
62
+
63
+```text
64
+ Maia-3 · 800                     ♙♙♘♗ +3
65
+ [Brett]
66
+ Timo                             ♟♟♞
67
+```
68
+
69
+Bei Lichess-Partien steht dort „Lichess-Symbol + Benutzername (Wertung)“, im LAN
70
+„Florian · 💡 2/3“.
71
+
72
+**Name der Eröffnung im Untertitel** (Vorschlag): PyChess bringt
73
+`/usr/share/pychess/eco.db` mit, 1087 Einträge auf Deutsch (z. B. „Spanisch,
74
+(Tschigorin-System)“), gesucht wird nach der Stellung. Nach jedem Zug wird dort
75
+nachgesehen, und der Untertitel lautet z. B. „Maia 800 · Italienisch“. Weil nach
76
+Stellung statt Zugfolge gesucht wird, zählen Zugumstellungen mit. Das kostet wenig
77
+Code und bereitet 6 vor.
78
+
79
+### 0.2 Einstellungen: Ja, jetzt lohnen sie sich
80
+
81
+Bisher reichten Menü und `settings.json`. Mit wählbaren Engines (2, 3), Brettfarben und
82
+Figurensätzen kommen Dinge dazu, die man selten ändert und die ins Menü nicht passen. Das ist der klassische Fall für
83
+`Adw.PreferencesDialog`:
84
+
85
+| Seite | Inhalt |
86
+| --- | --- |
87
+| Allgemein | Standardfarbe, Gegner-Streuung (heute `OPPONENT_TEMPERATURE` im Code) |
88
+| Darstellung | Figurensatz (aus dem Menü hierher) und Brettfarben, beide als Auswahl mit kleiner Vorschau (siehe unten) |
89
+| Engines | Analyse-Engine, Standard-Helfer für Hinweise, Threads und Hash für Stockfish, Maia-Modell (5M … 79M), Liste erkannter Engines mit „Engine hinzufügen …“ |
90
+| Lichess | Anmeldung und Abmeldung mit Avatar und Name, aus dem Menü hierher. Im Menü bleibt nur der Status. |
91
+
92
+Gilt sofort, ohne Speichern-Knopf (HIG-Muster für Einstellungen).
93
+
94
+**Brettfarben** (Wunsch, angeregt von En Croissant): drei Schemata reichen.
95
+
96
+| Schema | Hell | Dunkel | Wirkung |
97
+| --- | --- | --- | --- |
98
+| Holz (heute) | `#f0d9b5` | `#b58863` | warm, klassisch |
99
+| Schiefer | `#e9ecef` | `#8b95a1` | kühl und ruhig wie En Croissant, passt gut zu Adwaita |
100
+| Grün | `#eeeed2` | `#769656` | klassisches Turnierbrett, viel Kontrast für Kinder |
101
+
102
+- Technisch heute zwei Konstanten `LIGHT`/`DARK` in `schach/board.py`. Daraus
103
+  wird ein Schema-Objekt, das auch die Farben für Markierungen (letzter Zug,
104
+  Hinweis-Leuchten) mitbringt. Diese müssen auf jedem Untergrund gut sichtbar
105
+  sein. Ein festes Gelb wie heute geht auf Grün unter.
106
+- Die Koordinaten am Rand nehmen schon heute die Gegenfarbe und passen sich
107
+  automatisch an.
108
+- Vorschlag: „Schiefer“ im dunklen Systemmodus eine Spur dunkler, damit das Brett
109
+  nachts nicht blendet. Holz und Grün bleiben unverändert.
110
+- Auswahl: drei kleine Vorschau-Bretter (2×2 Felder) als Radio-Knöpfe nebeneinander,
111
+  wie die Stilauswahl in den GNOME-Einstellungen.
112
+
113
+## 1. Bedrohungshinweis (Taste B)
114
+
115
+Der Ablauf ist zweistufig wie beim Hinweis, nur umgekehrt:
116
+
117
+1. **Erster Druck:** Das bedrohte Feld leuchtet, z. B. die eigene hängende Figur
118
+   oder das Feld, auf dem eine Gabel droht.
119
+2. **Zweiter Druck:** Zusätzlich leuchtet die drohende Figur, optional mit einem
120
+   Pfeil.
121
+
122
+**Woher kommt die Bedrohung?** Aus der Frage „Was würde *dieser* Gegner spielen,
123
+wenn er jetzt am Zug wäre?“:
124
+
125
+1. Stellung mit Nullzug: `b = chess.Board(board.fen()); b.push(chess.Move.null())`.
126
+   Danach wird ein frisches Board aus der FEN gebaut, denn `--use-uci-history`
127
+   verträgt den UCI-Nullzug `0000` vermutlich nicht. Das muss man testen.
128
+2. `maia_candidates(b, elo=<Gegner-Elo>, count=5)` liefert die Züge, die ein
129
+   800er dort wahrscheinlich sieht.
130
+3. Stockfish prüft jeden Kandidaten kurz. Er gilt als echte Bedrohung, wenn sich
131
+   die Bewertung um mindestens ~150 cp zugunsten des Gegners verschiebt oder ein
132
+   Matt droht. Maia bestimmt also, *was gesehen wird*, und Stockfish nur, *ob es
133
+   stimmt*.
134
+4. Der wahrscheinlichste echte Kandidat gewinnt. Gibt es keinen, erscheint ein
135
+   Toast „Keine akute Drohung“.
136
+
137
+**Was auf Stufe 1 leuchtet:**
138
+
139
+- Schlagzug: das Feld der bedrohten Figur.
140
+- Sonst (Gabel, Mattdrohung, Spieß): das Zielfeld des drohenden Zugs.
141
+
142
+**Regeln:**
143
+
144
+- Im Schach gibt es keinen Nullzug. Dann leuchtet direkt der König.
145
+- In Lichess-Partien ist die Funktion aus (Fair Play).
146
+- Bei Rätseln zählt sie als Hinweis.
147
+- Bei zwei Spielern und im LAN zählt sie gegen das Hinweis-Kontingent (siehe 7, 8).
148
+- Die Rechnung startet vorab, während du überlegst, so wie heute beim Hinweis.
149
+- Woher die Drohung kommt, ist wählbar (siehe 2). Standard ist „wie der Gegner“.
150
+
151
+## 2. Helfer wählbar: Split-Button „Hinweis▾“
152
+
153
+Der Hinweis-Knopf wird ein `Adw.SplitButton`. Die HIG nennt Split-Buttons
154
+ausdrücklich für Titelleisten. Ein Klick gibt wie bisher einen Hinweis, der Pfeil
155
+öffnet ein Menü mit zwei Auswahlgruppen (Radio-Aktionen):
156
+
157
+```text
158
+Hinweis von
159
+  ○ Maia 1500
160
+  ● Maia 2000        (Standard, wie heute HINT_ELO)
161
+  ○ Maia 2500
162
+  ○ Stockfish
163
+  ○ <Analyse-Engine, falls anders, siehe 3>
164
+Bedrohung von
165
+  ● wie der Gegner   (Maia mit Gegner-Elo, siehe 1)
166
+  ○ Stockfish        (alles, was objektiv droht)
167
+```
168
+
169
+- Die Auswahl wird pro Modus gemerkt: Gegen Maia gilt etwas anderes als bei
170
+  Rätseln. Der Standard steht in den Einstellungen.
171
+- Die Engine steht im Tooltip und in der Statuszeile des Hinweises, z. B. „Hinweis
172
+  von Stockfish“. Damit ist klar, warum ein Hinweis mal „menschlich“ und mal
173
+  „brutal“ ist.
174
+- Technisch: Die Jobs `maia_candidates`/`maia_move` gibt es schon. Für Stockfish
175
+  und andere UCI-Engines kommt ein `best_move(board, limit)` dazu. Vorrechnen wie
176
+  heute.
177
+- Bei Rätseln zeigt Stockfish praktisch die Lösung. Das ist in Ordnung, das Rätsel
178
+  zählt ohnehin nicht mehr als gelöst.
179
+
180
+## 3. Analyse-Engine wählbar
181
+
182
+**Engines finden:** *nicht* jedes Programm im PATH starten, denn ein Unbekanntes
183
+mit `uci` anzusprechen ist riskant und langsam. Stattdessen:
184
+
185
+1. Eine Liste bekannter Namen im PATH suchen: `stockfish`, `lc0`, `dragon`,
186
+   `komodo`, `berserk`, `ethereal`, `rubichess`, `koivisto`, `igel`, `arasan`,
187
+   `fairy-stockfish`, `maia3-uci`. Auf diesem Rechner sind heute nur `stockfish`
188
+   und `maia3-uci` installiert.
189
+2. Jeder Treffer bekommt im Hintergrund einen UCI-Handshake. Gemerkt werden
190
+   `id name`, die angebotenen Optionen und ob das Programm überhaupt antwortet.
191
+3. In den Einstellungen gibt es „Engine hinzufügen …“ mit Dateiauswahl für alles
192
+   andere.
193
+
194
+**Besonderheiten:**
195
+
196
+- `lc0` braucht eine Gewichtsdatei, also ein Feld in den Einstellungen. Sonst
197
+  bleibt es ausgegraut mit Erklärung.
198
+- `maia3-uci` als *Analyse*-Engine ist wenig sinnvoll (sie sagt menschliche Züge
199
+  vorher und bewertet nicht), also nur als Helfer anbieten.
200
+- Die Zugzeichen (`annotate.py`) sind auf Stockfish-Centipawns abgestimmt.
201
+  Andere Engines bewerten anders, z. B. lc0 über Gewinnchance (WDL). Deshalb
202
+  intern auf Gewinnchance normieren. Die Zugliste zeigt das ohnehin schon als Balken.
203
+- Wechsel während der Partie: Die laufende Analyse wird verworfen und mit der
204
+  neuen Engine neu gestartet. Die Zugzeichen der bisherigen Züge bleiben, bis sie
205
+  neu berechnet sind.
206
+
207
+## 4. PGN per Zwischenablage
208
+
209
+| Taste | Aktion |
210
+| --- | --- |
211
+| Strg+C | Partie als PGN kopieren (mit Kopfzeilen, Zugzeichen und Hinweis-Kommentaren) |
212
+| Strg+Umschalt+C | FEN der angezeigten Stellung kopieren (gibt es heute als Knopf in der Zugliste) |
213
+| Strg+V | Partie oder Stellung aus der Zwischenablage aufstellen |
214
+
215
+**Einfügen erkennt** (Vorschlag), in dieser Reihenfolge:
216
+
217
+1. PGN (`chess.pgn.read_game`, mit Zügen oder `[FEN]`-Kopf)
218
+2. FEN
219
+3. Lichess-Link (`lichess.org/abcd1234`): Die Partie wird über die API geholt. Das
220
+   ist praktisch, wenn Florian eine Partie aus dem Club zugeschickt bekommt.
221
+
222
+**Verhalten:**
223
+
224
+- Ist die aktuelle Partie leer, wird dort aufgestellt. Sonst öffnet sich ein neues
225
+  Fenster, so wie heute bei „von hier weiterspielen“. So geht nie eine Partie
226
+  verloren, und man braucht keine Rückfrage.
227
+- Danach erscheint ein Toast „Partie eingefügt“ und die Zugliste ist offen, also
228
+  Analyse-Modus.
229
+- Erkennt das Programm nichts, kommt ein Toast „Keine Partie in der
230
+  Zwischenablage“.
231
+- In Lichess- und LAN-Partien ist Einfügen gesperrt.
232
+- Strg+C/V greifen nur, wenn kein Eingabefeld den Fokus hat. In Dialogen bleibt
233
+  normales Kopieren also erhalten.
234
+- **Stellung aufbauen** (Vorschlag, Anlass: Rätsel auf Papier aus dem Club):
235
+  ein Modus, in dem man Figuren aus einer Leiste aufs Brett zieht, Seite am Zug
236
+  wählt und dann [Lösen üben] oder [Analysieren] drückt. Damit kann Florian eine
237
+  Aufgabe vom Blatt nachstellen, selbst probieren und hinterher prüfen, ob seine
238
+  Lösung stimmt. Technisch entsteht eine FEN, alles Weitere läuft wie beim Einfügen.
239
+- Gleich mit erledigen: `.pgn`-Dateien aufs Brett ziehen (`Gtk.DropTarget`) benutzt
240
+  dieselbe Funktion.
241
+
242
+## 5. Lichess deutlicher machen
243
+
244
+Empfehlung, nach Wirkung sortiert:
245
+
246
+1. **Spieler-Zeilen** (siehe 0.1): zeigen dauerhaft und ohne Platzbedarf, dass die
247
+   Partie auf Lichess läuft.
248
+2. **Lichess-Knopf im Modus-Slot**, *nur während einer Lichess-Partie*. Er ersetzt
249
+   dort den Hinweis-Knopf, der in diesem Modus ohnehin gesperrt ist. Remis und
250
+   Aufgeben wandern in sein Popover. Damit verschwinden zwei Text-Knöpfe.
251
+3. **Anmeldestatus im primären Menü:** Die Abschnittsüberschrift lautet
252
+   „Lichess · timo“. An- und Abmelden ziehen in die Einstellungen um (0.2).
253
+   Einen dauerhaften Konto-Knopf in der Titelleiste kennt die HIG nicht.
254
+4. **Kein Banner für „Online-Partie“.** Banner wirken wie eine Warnung („Working
255
+   offline“). Passend ist ein Banner nur für echte Probleme: „Verbindung zu
256
+   Lichess unterbrochen – Partie läuft weiter“ oder „Anmeldung abgelaufen [Neu
257
+   anmelden]“.
258
+
259
+## 6. Eröffnungen lernen (für Florian: Italienisch, Spanisch)
260
+
261
+**Status:** Konzept so beschlossen (20.11.2026).
262
+
263
+**Ja, das geht direkt auf dem Brett. Die Daten sind größtenteils schon da.**
264
+
265
+### Was lokal vorhanden ist (geprüft)
266
+
267
+- **Eröffnungsbuch** `/usr/share/pychess/pychess_book.bin` im Polyglot-Format,
268
+  lesbar mit `chess.polyglot`. Nach 1.e4 e5 2.Nf3 Nc6 liefert es mit Gewichten:
269
+  Lb5 (10612, Spanisch), Lc4 (4983, Italienisch), d4 (2155, Schottisch), Sc3
270
+  (1335) usw. Damit erkennt das Programm *alle* üblichen Züge, nicht nur einen.
271
+- **Eröffnungsnamen** `/usr/share/pychess/eco.db` (SQLite), gesucht nach Stellung,
272
+  auch auf Deutsch.
273
+- **Lichess-Studien als PGN** liegen bei PyChess unter `/usr/share/pychess/learn/`.
274
+  Allerdings sind es Taktik- und Endspielkurse, keine Eröffnungen. Das Format ist
275
+  aber genau das richtige (siehe unten).
276
+
277
+### Kursformat: PGN mit Varianten und Kommentaren
278
+
279
+Ein Kurs ist eine normale PGN-Datei. Die Hauptvariante ist der Plan, Varianten
280
+sind gleichwertige Alternativen und gegnerische Abweichungen, Kommentare sind die
281
+Erklärung:
282
+
283
+```pgn
284
+[Event "Italienisch – Grundidee"]
285
+1. e4 { Zentrum besetzen. } e5 2. Nf3 { Greift e5 an. } Nc6
286
+3. Bc4 { Der Läufer zielt auf f7 – die schwächste Stelle bei Schwarz. }
287
+   ( 3. Bb5 { Auch gut – das ist Spanisch. } )
288
+3... Bc5 ( 3... Nf6 { Zweispringerspiel – aufpassen auf Sg4! } ) 4. c3 ...
289
+```
290
+
291
+- Florian kann Kurse aus Lichess-Studien übernehmen (Export als PGN, auch über
292
+  `/api/study/{id}.pgn`) oder vom Trainer bekommen. Dafür muss nichts neu erfunden
293
+  werden.
294
+- **Beschlossen:** Ich schreibe zwei kurze Kurse auf Deutsch (Italienisch,
295
+  Spanisch, je 6–10 Züge mit den wichtigsten gegnerischen Antworten). Der Club
296
+  arbeitet mit Rätseln auf Papier (Fritz), das ergänzt sich, statt sich zu
297
+  überschneiden.
298
+
299
+### Ablauf „Eröffnung üben“
300
+
301
+1. Neu ▾ → Eröffnung üben … → Kurs und Farbe wählen.
302
+2. Der Computer zieht die Gegnerseite aus dem Kurs. Gibt es mehrere Varianten,
303
+   wählt **Maia mit Florians Spielstärke** unter ihnen aus. So kommen die
304
+   Antworten, die ihm im Club wirklich begegnen, am häufigsten.
305
+3. Florian zieht. Die Bewertung läuft in Stufen:
306
+
307
+   | Zug ist … | Rückmeldung |
308
+   | --- | --- |
309
+   | im Kurs | ✓ und der Kommentar aus dem PGN |
310
+   | nicht im Kurs, aber im Buch | „Spielbar – das ist *Schottisch* (Name aus eco.db). Unser Plan ist Lc4.“ [Zurücknehmen] |
311
+   | nicht im Buch, Stockfish ≤ ~50 cp schlechter | „Kein Buchzug, aber in Ordnung.“ |
312
+   | deutlich schlechter | wie die bekannten Zugzeichen `?`/`??`, mit „Nochmal“ |
313
+
314
+4. **Zugumstellungen:** Es wird nach Stellung verglichen, nicht nach Zugfolge
315
+   (Zobrist-Hash, wie Polyglot und eco.db). 1.Sf3 … 2.e4 führt zur selben
316
+   Stellung und wird erkannt. Das ist die Antwort auf „mehrere Züge führen zum
317
+   Zielbild“.
318
+5. Der Hinweis zeigt den Kurszug: auf Stufe 1 die Figur, auf Stufe 2 das Zielfeld.
319
+6. Am Ende der Linie kommt „Zielbild erreicht“ mit der Stellung und dem
320
+   Plan-Kommentar. Danach gibt es [Nächste Linie] und [Gegen Maia weiterspielen],
321
+   das nutzt den vorhandenen Abzweig-Mechanismus.
322
+
323
+### Später
324
+
325
+- **Wiederholung nach Fehlern:** Linien mit Fehlern kommen früher wieder dran
326
+  (einfaches Lernkarten-Prinzip, Speicherort `~/.local/share/schach/training.json`).
327
+- **Eröffnung in eigenen Partien:** Nach einer Partie gegen Maia steht in der
328
+  Zugliste „Buch bis Zug 6, dann Abweichung: Kurs empfiehlt …“. So merkt Florian
329
+  in echten Partien, wo er den Plan verlassen hat.
330
+- **Lichess Opening Explorer** (online, möglicherweise nur mit Anmeldung): Er
331
+  zeigt, was Spieler mit ähnlicher Wertung in der Stellung tatsächlich ziehen.
332
+  Das ist eine Ergänzung zum lokalen Buch.
333
+
334
+## 7. Zwei Spieler an einem Rechner
335
+
336
+Neu ▾ → „Zwei Spieler an diesem Rechner …“. Das braucht keine Engine als Gegner
337
+und funktioniert offline.
338
+
339
+- **Dialog:** keine Namen, man sitzt ja zusammen. Gefragt wird nur nach Hinweisen
340
+  pro Farbe, z. B. „Weiß: 0, Schwarz: 3“, und nach Zugzeichen pro Farbe (Handicap). Die Spieler-Zeilen zeigen
341
+  „Weiß“/„Schwarz“ mit dem Zähler. Wer welche Farbe nimmt, klärt man am Tisch.
342
+- **Brett drehen:** Die Option „nach jedem Zug drehen“ ist standardmäßig aus. Am
343
+  Laptop sitzt man meist nebeneinander, am Tablet gegenüber. Die Spieler-Zeile
344
+  des Spielers am Zug ist hervorgehoben.
345
+- **Hinweise:** Die Hilfe-Gruppe gilt für den Spieler am Zug und zählt dessen
346
+  Kontingent herunter. Anders als im LAN sieht der andere hier natürlich *was*
347
+  angezeigt wird. Als Handicap funktioniert es trotzdem.
348
+- **Zugzeichen am Brett** (`!!` … `??` an der Figur) sind wählbar und gehören
349
+  zum Handicap. Im Dialog gibt es pro Farbe eine Auswahl „Zugzeichen“ (`Adw.ComboRow`):
350
+
351
+  | Auswahl | Zeichen an … | Wofür |
352
+  | --- | --- | --- |
353
+  | keine (**Standard**) | – | faire Partie |
354
+  | eigene Züge | den Zügen dieser Farbe | Rückmeldung zum eigenen Spiel: „War das gerade ein Fehler?“ |
355
+  | alle Züge | eigenen und gegnerischen Zügen | zusätzlich: „Der Gegner hat gepatzt – finde die Strafe!“ |
356
+
357
+  - Die Zeichen erscheinen nur, *während die berechtigte Farbe am Zug ist*. Ist
358
+    der andere am Zug, sind sie weg.
359
+  - Ehrliche Grenze: Am selben Bildschirm sieht der andere sie natürlich mit.
360
+    Wirklich nur für einen Spieler sichtbar sind sie erst im LAN (8).
361
+  - Nach der Partie erscheinen sie für alle wie gewohnt.
362
+  - Die Seitenleiste mit dem Bewertungsbalken bleibt, wie sie ist: Während der
363
+    Partie ist sie ohnehin zugeklappt, und wer sie aufmacht, tut das bewusst.
364
+- **Zurücknehmen:** Ohne Rückfrage, man sitzt ja zusammen. Ausgelöst wie überall
365
+  mit Knopf oder Strg+Z.
366
+- **Remis und Aufgeben:** im Popover des Modus-Slots, für den Spieler am Zug.
367
+- **Später:** eine optionale Schachuhr mit Bedenkzeit pro Spieler in der
368
+  Spieler-Zeile.
369
+
370
+**Architektur:** Dieser Modus legt das Modell „zwei Menschen, je mit eigenem
371
+Hinweis-Kontingent“ an. Das LAN (8) tauscht dann nur aus, woher die Züge des
372
+anderen kommen: von der Maus oder aus dem Netz.
373
+
374
+## 8. Schach im LAN
375
+
376
+**Gibt es einen offenen Standard?** Für die Spielverbindung gibt es keinen, der
377
+sich lohnt:
378
+
379
+- *ICS/FICS-Protokoll*: historischer De-facto-Standard, textbasiert über Telnet,
380
+  auf zentrale Server ausgelegt. Zu groß für zwei Rechner.
381
+- *UCI/CECP* sind Protokolle für Engines, nicht für Partien zwischen Menschen.
382
+- *Lichess-API*: offen dokumentiert, läuft aber nur gegen deren Server.
383
+
384
+Offene Standards gibt es für die Bausteine, und sie funktionieren auch unter
385
+macOS und Windows:
386
+
387
+- **Finden:** mDNS/DNS-SD (RFC 6762/6763). Der Anbieter meldet `_schach._tcp`
388
+  an, über `python-zeroconf` (reines Python, läuft auf allen drei Systemen,
389
+  kompatibel zu Bonjour und zum mDNS von Windows 10/11). Als Ersatz gibt es eine
390
+  manuelle Eingabe von Adresse und Port.
391
+- **Spielen:** JSON-Nachrichten über **WebSocket**. Der Aufwand ist gleich wie bei
392
+  rohem TCP, aber jeder Browser spricht das Protokoll. Züge stehen in UCI-Notation,
393
+  am Ende wird die Partie als PGN ausgetauscht. Nachrichtentypen: `hello`, `offer`,
394
+  `accept`, `move`, `hint_used`, `draw_offer`, `draw_reply`, `resign`,
395
+  `takeback_request`, `takeback_reply`, `bye`.
396
+
397
+**Zugrücknahme per Anfrage:** Ausgelöst wird genau wie lokal, mit Knopf oder
398
+Strg+Z. Statt sofort zurückzunehmen, geht eine Anfrage raus:
399
+
400
+- **Beide Bretter sind kurz gesperrt**, solange die Anfrage offen ist. Dann kann
401
+  keiner nebenher ziehen und es entsteht kein Durcheinander.
402
+- **Wer fragt:** Eine Meldung „Warte auf Max …“ mit [Anfrage zurückziehen].
403
+- **Wer gefragt wird:** `Adw.AlertDialog` „Florian möchte einen Zug
404
+  zurücknehmen“ mit [Ablehnen] [Erlauben]. Ein Dialog statt Toast, weil das Brett
405
+  ohnehin gesperrt ist und eine Entscheidung nötig ist. Das ist das HIG-Muster
406
+  für Dialoge.
407
+- **Zeitlimit** (Vorschlag): Ohne Antwort gilt die Anfrage nach 20 s als
408
+  abgelehnt. Die Sperre bleibt also wirklich kurz, auch wenn der andere gerade
409
+  nicht hinschaut. Eine spätere Schachuhr hält in dieser Zeit an.
410
+- **Was zurückgenommen wird:** Bis der Fragende wieder am Zug ist. Hat der Gegner
411
+  schon geantwortet, sind das zwei Halbzüge (wie auf Lichess).
412
+- **Gleiches Muster für Lichess** (Vorschlag): Die Board-API kennt
413
+  Rücknahme-Anfragen (`/api/board/game/{id}/takeback/yes|no`). So verhält sich
414
+  Strg+Z in allen Online-Partien gleich.
415
+
416
+**Ablauf:** Neu ▾ → „Partie im LAN anbieten …“. Ein Dialog fragt Farbe und
417
+Hinweise pro Farbe ab (derselbe Dialog wie in 7). Im Netz braucht es zusätzlich
418
+einen Namen, vorbelegt mit dem Systemnamen (`GLib.get_real_name()`), damit man
419
+sieht, wer anbietet. Danach wartet der Rechner in
420
+einer Statusseite mit Abbrechen-Knopf. Auf dem anderen Rechner erscheint der Toast
421
+„Florian bietet eine Partie an [Annehmen]“.
422
+
423
+**Handicap mit Hinweisen: Ja, das geht.** Die Hinweise rechnen lokal. Übertragen
424
+wird nur `{"type": "hint_used", "kind": "hint"|"threat", "stage": 1|2, "ply": 23}`.
425
+Zugzeichen sind auch hier pro Spieler wählbar (keine / eigene / alle, Standard:
426
+keine) und erscheinen nur auf dem Rechner des Berechtigten. Der Gegner sieht den Zähler in der Spieler-Zeile (💡 2/3), ein 💡 in der Zugliste
427
+und einen kurzen Toast. *Was* angezeigt wurde, sieht er nicht. Nach der Partie
428
+steht die Nutzung als Kommentar in der PGN. Vorschlag: Ein Hinweis kostet 1, gleich
429
+ob Stufe 1 oder 2.
430
+
431
+**Mac und Windows:** Das Protokoll ist plattformneutral. Das Problem ist die App:
432
+GTK4 und libadwaita laufen auf macOS (Homebrew) und Windows (MSYS2) nur mit Mühe,
433
+dazu kommen Maia-3 und Stockfish pro Plattform.
434
+
435
+- **A: Browser-Gast (Empfehlung).** Der Linux-Rechner liefert über denselben
436
+  WebSocket-Server eine kleine Webseite aus. Tina öffnet `http://<rechner>.local:8xxx`
437
+  oder scannt einen QR-Code und muss nichts installieren. Die Hinweise für den Gast
438
+  rechnet der Gastgeber-Rechner und schickt sie nur an den Gast. Das Brett baut
439
+  auf chessground (GPL-3) auf. Die Gast-Seite verlinkt den Quellcode, das verlangt
440
+  AGPL §13.
441
+- **B: Zweite native App** auf dem Mac. Viel mehr Aufwand, lohnt sich nur, wenn
442
+  Tina dort auch allein spielen soll.
443
+
444
+Unter Windows fragt die Firewall nur nach, wenn ein Windows-Rechner selbst anbietet.
445
+
446
+**Ehrliche Grenze:** Das Kontingent ist Vertrauenssache. Wer den Client ändert,
447
+kann unbegrenzt Hinweise nehmen. In der Familie spielt das keine Rolle.
448
+
449
+## Reihenfolge
450
+
451
+| # | Paket | Warum an dieser Stelle |
452
+| --- | --- | --- |
453
+| 1 | Titelleiste nach Modus, Spieler-Zeilen, Einstellungsdialog (0) | Grundlage für alles Weitere |
454
+| 2 | PGN per Zwischenablage (4) | klein, sofort nützlich, wird von 6 gebraucht |
455
+| 3 | Helfer wählbar (2) und Bedrohungshinweis (1) | beide nutzen denselben Split-Button und dieselbe Engine-Schicht |
456
+| 4 | Eröffnungstraining (6) | größter Nutzen für Florian. Die Daten sind da, der Kursmodus ist neu |
457
+| 5 | Analyse-Engine wählbar (3) | erst sinnvoll, wenn eine zweite Engine installiert ist |
458
+| 6 | Lichess-Modus im Slot (5) | sobald der Slot aus 0 steht |
459
+| 7 | Zwei Spieler an einem Rechner (7) | klein, sobald Spieler-Zeilen und Hilfe-Gruppe stehen. Legt das Partie-Modell für 8 an |
460
+| 8 | LAN mit Browser-Gast (8) | am meisten neuer Code. Baut auf 7 auf, nur die Verbindung ist neu |
461
+
462
+## Offene Fragen
463
+
464
+- Symbole für Hinweis und Bedrohung aus der GNOME-Symbolbibliothek auswählen.
465
+- Sollen Hinweise beim Eröffnungstraining gezählt werden, z. B. für eine
466
+  Fortschrittsanzeige pro Linie?

added schach.desktop +7 −0

@@ -0,0 +1,7 @@
1
+[Desktop Entry]
2
+Type=Application
3
+Name=Schach
4
+Comment=Schach gegen Maia-3
5
+Exec=/home/timo/Projekte/schach/schach.sh
6
+Icon=org.gnome.Chess
7
+Categories=Game;BoardGame;

added schach.sh +5 −0

@@ -0,0 +1,5 @@
1
+#!/bin/sh
2
+# GTKs Vulkan-Renderer meldet auf manchen Treibern harmlose VK_SUBOPTIMAL_KHR-Warnungen;
3
+# der OpenGL-Renderer (gl) zeichnet gleich gut und bleibt still. Überschreibbar per GSK_RENDERER.
4
+export GSK_RENDERER="${GSK_RENDERER:-gl}"
5
+cd "$(dirname "$(readlink -f "$0")")" && exec python3 -m schach "$@"

added schach/__init__.py +0 −0

added schach/__main__.py +5 −0

@@ -0,0 +1,5 @@
1
+import sys
2
+
3
+from .app import main
4
+
5
+sys.exit(main())

added schach/annotate.py +246 −0

@@ -0,0 +1,246 @@
1
+"""Zugbewertung mit Stockfish: !!, !, ?!, ?, ?? – oder gar nichts.
2
+
3
+Während der Mensch nachdenkt, rechnet Stockfish seine drei besten Züge live immer
4
+tiefer (``think_job``). Züge außerhalb dieser Top-Linien werden nur bei Bedarf
5
+einzeln nachgerechnet ("lazy") – oft lässt sich das sogar ganz vermeiden.
6
+"""
7
+
8
+import threading
9
+
10
+import chess
11
+import chess.engine
12
+
13
+VALUE = {
14
+    chess.PAWN: 1,
15
+    chess.KNIGHT: 3,
16
+    chess.BISHOP: 3,
17
+    chess.ROOK: 5,
18
+    chess.QUEEN: 9,
19
+    chess.KING: 100,
20
+}
21
+
22
+NAG = {"!": 1, "?": 2, "!!": 3, "??": 4, "?!": 6}
23
+
24
+# Verlust an Gewinnwahrscheinlichkeit (Prozentpunkte) wie bei Lichess
25
+BLUNDER, MISTAKE, INACCURACY = 15.0, 10.0, 5.0
26
+# Ein "einziger Zug": alle Alternativen sind mindestens so viel schlechter
27
+ONLY_MOVE_GAP = 12.0
28
+# Hinweis: strenger als ?! (5), damit ein befolgter Hinweis nie markiert wird
29
+HINT_MAX_LOSS = 3.0
30
+
31
+TOP_LINES = 3  # so viele beste Züge rechnet Stockfish live mit
32
+THINK_LIMIT = chess.engine.Limit(depth=30, time=30)  # Obergrenze fürs Mitdenken
33
+MIN_DEPTH = 14  # ab hier gilt eine Momentaufnahme als belastbar
34
+QUICK_LIMIT = chess.engine.Limit(depth=MIN_DEPTH)  # falls schon vor dem Start gezogen wurde
35
+EXTRA_LIMIT = chess.engine.Limit(depth=MIN_DEPTH)  # einzelne Züge nachrechnen
36
+
37
+
38
+def win_pct(score, color):
39
+    return score.pov(color).wdl(model="lichess").expectation() * 100.0
40
+
41
+
42
+def is_sacrifice(before, move):
43
+    """Grobe Abschätzung: lässt der Zug mindestens zwei Bauern Material stehen?"""
44
+    mover = before.turn
45
+    after = before.copy()
46
+    after.push(move)
47
+    piece = after.piece_at(move.to_square)
48
+    if piece is None:
49
+        return False
50
+    if before.is_en_passant(move):
51
+        captured = VALUE[chess.PAWN]
52
+    else:
53
+        victim = before.piece_at(move.to_square)
54
+        captured = VALUE[victim.piece_type] if victim else 0
55
+    value = VALUE[piece.piece_type]
56
+
57
+    attackers = list(after.attackers(not mover, move.to_square))
58
+    defended = bool(after.attackers(mover, move.to_square))
59
+    if defended:
60
+        attackers = [a for a in attackers if after.piece_type_at(a) != chess.KING]
61
+    if not attackers:
62
+        return False
63
+
64
+    if defended:
65
+        cheapest = min(VALUE[after.piece_type_at(a)] for a in attackers)
66
+        net = captured - value + cheapest
67
+    else:
68
+        net = captured - value
69
+    return net <= -2
70
+
71
+
72
+def classify(before, move, best_wp, second_wp, played_wp):
73
+    """Reine Logik, ohne Engine – gibt ein Symbol oder None zurück."""
74
+    loss = best_wp - played_wp
75
+    if loss >= BLUNDER:
76
+        return "??"
77
+    if loss >= MISTAKE:
78
+        return "?"
79
+    if loss >= INACCURACY:
80
+        return "?!"
81
+
82
+    if loss > 1.0 or second_wp is None:
83
+        return None
84
+    if before.legal_moves.count() < 2:
85
+        return None
86
+    if before.is_check() and before.legal_moves.count() <= 3:
87
+        return None
88
+    if before.move_stack:
89
+        last = before.peek()
90
+        if last.to_square == move.to_square and before.is_capture(move):
91
+            return None  # Zurückschlagen ist selten bemerkenswert
92
+    if best_wp - second_wp < ONLY_MOVE_GAP or second_wp >= 80.0:
93
+        return None
94
+    return "!!" if is_sacrifice(before, move) else "!"
95
+
96
+
97
+def key(board):
98
+    return board.fen()
99
+
100
+
101
+def _entry(infos, color, depth):
102
+    scores = {i["pv"][0]: win_pct(i["score"], color) for i in infos if i.get("pv") and "score" in i}
103
+    best = max(scores, key=scores.get) if scores else None
104
+    return {"depth": depth, "best": best, "scores": scores, "top": len(scores)}
105
+
106
+
107
+def evaluate_move(engine, board, move):
108
+    """Einzelner Zug, gezielt nachgerechnet (für Züge außerhalb der Top-Linien)."""
109
+    info = engine.analyse(board, EXTRA_LIMIT, root_moves=[move])
110
+    return win_pct(info["score"], board.turn)
111
+
112
+
113
+class Thinking:
114
+    """Griff auf eine laufende Mitdenk-Rechnung; ``stop()`` ist aus jedem Thread erlaubt."""
115
+
116
+    def __init__(self):
117
+        self._lock = threading.Lock()
118
+        self._analysis = None
119
+        self.stopped = False
120
+
121
+    def attach(self, analysis):
122
+        with self._lock:
123
+            self._analysis = analysis
124
+            if self.stopped:
125
+                analysis.stop()
126
+
127
+    def stop(self):
128
+        with self._lock:
129
+            self.stopped = True
130
+            if self._analysis is not None:
131
+                self._analysis.stop()
132
+
133
+
134
+def think_job(board, candidates, thinking, on_snapshot, on_hint):
135
+    """Job-Fabrik: Stockfish denkt mit, solange der Mensch überlegt.
136
+
137
+    1. Top-Linien live bis ``MIN_DEPTH`` rechnen,
138
+    2. Hinweis aus Maias Kandidaten bestimmen (lazy, s. ``_resolve_hint``),
139
+    3. weiter in die Tiefe, bis ``thinking.stop()``.
140
+    ``on_snapshot``/``on_hint`` laufen im Worker-Thread; Ergebnis ist die letzte Momentaufnahme.
141
+    """
142
+    board = board.copy()
143
+    candidates = list(candidates)
144
+
145
+    def job(engine):
146
+        n = min(TOP_LINES, board.legal_moves.count())
147
+        if n == 0:
148
+            return None
149
+        extra = {}  # lazy nachgerechnete Züge außerhalb der Top-Linien
150
+
151
+        def stream(until_depth):
152
+            last = None
153
+            limit = QUICK_LIMIT if thinking.stopped else THINK_LIMIT
154
+            with engine.analysis(board, limit, multipv=n) as analysis:
155
+                thinking.attach(analysis)
156
+                for info in analysis:
157
+                    # Zeilen 1..n kommen am Ende jeder Tiefe; Zeile n = Tiefe fertig
158
+                    if info.get("multipv") == n and "depth" in info:
159
+                        last = _entry(analysis.multipv, board.turn, info["depth"])
160
+                        for move, wp in extra.items():
161
+                            last["scores"].setdefault(move, wp)
162
+                        on_snapshot(last)
163
+                        if until_depth and info["depth"] >= until_depth:
164
+                            break
165
+                if last is None:
166
+                    last = _entry(analysis.multipv, board.turn, 0)
167
+            return last
168
+
169
+        last = stream(MIN_DEPTH)
170
+        if thinking.stopped:
171
+            return last
172
+        on_hint(_resolve_hint(engine, board, last, candidates, extra))
173
+        if extra:
174
+            last = {**last, "scores": {**extra, **last["scores"]}}
175
+            on_snapshot(last)
176
+        if thinking.stopped:
177
+            return last
178
+        return stream(None)
179
+
180
+    return job
181
+
182
+
183
+def _resolve_hint(engine, board, entry, candidates, extra):
184
+    """Erster Maia-Kandidat, mit dem Stockfish einverstanden ist; sonst Stockfishs Zug."""
185
+    scores = dict(entry["scores"])  # Kopie: die Momentaufnahme gehört schon dem GTK-Thread
186
+    if not scores:
187
+        return None
188
+    best_wp = max(scores.values())
189
+    third_wp = min(scores.values())
190
+    for move in candidates:
191
+        if move in scores:
192
+            wp = scores[move]
193
+        elif entry["top"] >= TOP_LINES and best_wp - third_wp > HINT_MAX_LOSS:
194
+            continue  # schlechter als der Drittbeste, also sicher nicht gut genug
195
+        else:
196
+            wp = extra[move] = scores[move] = evaluate_move(engine, board, move)
197
+        if best_wp - wp <= HINT_MAX_LOSS:
198
+            return move
199
+    return entry["best"]
200
+
201
+
202
+def classify_with(entry, before, move):
203
+    """Symbol aus einer Momentaufnahme, oder ``False`` falls nachgerechnet werden muss."""
204
+    if not entry or not entry["scores"]:
205
+        return False
206
+    scores = entry["scores"]
207
+    ranked = sorted(scores.values(), reverse=True)
208
+    if move not in scores:
209
+        # Schlechter als alle Top-Linien: verliert schon die schwächste 15 Punkte, ist es ein ??
210
+        if entry["top"] >= TOP_LINES and ranked[0] - ranked[TOP_LINES - 1] >= BLUNDER:
211
+            return "??"
212
+        return False
213
+    second = ranked[1] if len(ranked) > 1 else None
214
+    return classify(before, move, ranked[0], second, scores[move])
215
+
216
+
217
+def fallback_job(before, move, entry=None):
218
+    """Rechnet den gespielten Zug gezielt nach (lazy): (Symbol, Gewinn-% des Ziehenden)."""
219
+    before = before.copy()
220
+
221
+    def job(engine):
222
+        nonlocal entry
223
+        if not entry or entry["depth"] < MIN_DEPTH:
224
+            infos = engine.analyse(before, EXTRA_LIMIT, multipv=min(TOP_LINES, before.legal_moves.count()))
225
+            entry = _entry(infos, before.turn, 0)
226
+        entry = {**entry, "scores": dict(entry["scores"])}
227
+        if move not in entry["scores"]:
228
+            entry["scores"][move] = evaluate_move(engine, before, move)
229
+        return classify_with(entry, before, move), entry["scores"][move]
230
+
231
+    return job
232
+
233
+
234
+def white_eval_job(board):
235
+    """Job-Fabrik: Gewinnchance von Weiß in dieser Stellung (für die Zugliste)."""
236
+    board = board.copy()
237
+
238
+    def job(engine):
239
+        if board.is_checkmate():
240
+            return 0.0 if board.turn == chess.WHITE else 100.0
241
+        if board.is_game_over(claim_draw=True):
242
+            return 50.0
243
+        info = engine.analyse(board, EXTRA_LIMIT)
244
+        return win_pct(info["score"], chess.WHITE)
245
+
246
+    return job

added schach/app.py +1230 −0

@@ -0,0 +1,1230 @@
1
+"""Hauptfenster: Partie gegen Maia-3, Hinweise von Maia 2000, Bewertung von Stockfish."""
2
+
3
+import datetime
4
+import json
5
+import os
6
+import random
7
+import sys
8
+import time
9
+
10
+import chess
11
+import chess.pgn
12
+import gi
13
+
14
+gi.require_version("Gtk", "4.0")
15
+gi.require_version("Adw", "1")
16
+from gi.repository import Adw, Gio, GLib, GObject, Gtk  # noqa: E402
17
+
18
+from . import annotate, lichess, savegames  # noqa: E402
19
+from .board import BoardView, available_themes  # noqa: E402
20
+from .movelist import MoveList  # noqa: E402
21
+from .engines import MAIA_CMD, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move  # noqa: E402
22
+from .online import OnlineMixin  # noqa: E402
23
+from .puzzles import PuzzleMixin  # noqa: E402
24
+
25
+APP_ID = "app.schach.Schach"
26
+HINT_ELO = 2000
27
+OPPONENT_TEMPERATURE = 1.0  # menschliche Streuung; 0 = immer der wahrscheinlichste Zug
28
+MIN_REPLY_SECONDS = 0.6
29
+AUTOSAVE_DELAY_MS = 800
30
+FEATURED_THEMES = [
31
+    "cburnett", "merida", "alpha", "california", "staunty",
32
+    "maestro", "companion", "fresca", "leipzig", "chessnut", "python-chess",
33
+]
34
+
35
+SETTINGS_PATH = os.path.join(GLib.get_user_config_dir(), "schach", "settings.json")
36
+DEFAULTS = {"elo": 1200, "color": "white", "theme": "cburnett", "puzzle_difficulty": "normal"}
37
+
38
+
39
+def load_settings():
40
+    try:
41
+        with open(SETTINGS_PATH) as fh:
42
+            return {**DEFAULTS, **json.load(fh)}
43
+    except (OSError, ValueError):
44
+        return dict(DEFAULTS)
45
+
46
+
47
+def save_settings(settings):
48
+    os.makedirs(os.path.dirname(SETTINGS_PATH), exist_ok=True)
49
+    with open(SETTINGS_PATH, "w") as fh:
50
+        json.dump(settings, fh, indent=2)
51
+
52
+
53
+def outcome_text(board, human, opponent="Maia"):
54
+    outcome = board.outcome(claim_draw=True)
55
+    if outcome is None:
56
+        return None
57
+    if outcome.winner is not None:
58
+        return "Schachmatt – du hast gewonnen!" if outcome.winner == human else f"Schachmatt – {opponent} gewinnt."
59
+    return {
60
+        chess.Termination.STALEMATE: "Patt – Remis.",
61
+        chess.Termination.INSUFFICIENT_MATERIAL: "Remis – zu wenig Material.",
62
+        chess.Termination.THREEFOLD_REPETITION: "Remis durch Stellungswiederholung.",
63
+        chess.Termination.FIVEFOLD_REPETITION: "Remis durch Stellungswiederholung.",
64
+        chess.Termination.FIFTY_MOVES: "Remis nach der 50-Züge-Regel.",
65
+        chess.Termination.SEVENTYFIVE_MOVES: "Remis nach der 75-Züge-Regel.",
66
+    }.get(outcome.termination, "Remis.")
67
+
68
+
69
+class Window(OnlineMixin, PuzzleMixin, Adw.ApplicationWindow):
70
+    """Ein Brett. ``mode``: "maia" (Partie gegen Maia), "online" (Lichess-Partie, ohne Engine-Hilfe),
71
+    "puzzle" (Lichess-Rätsel), "review" (fertige Partie ansehen und analysieren)."""
72
+
73
+    def __init__(self, app, state=None, blank=False):
74
+        super().__init__(application=app, title="Schach", default_width=900, default_height=720)
75
+        self.settings = load_settings()
76
+
77
+        self.board = chess.Board()
78
+        self.human = chess.WHITE
79
+        self.elo = int(self.settings["elo"])
80
+        self.gen = 0  # erhöht sich bei jeder Änderung; veraltete Engine-Antworten werden verworfen
81
+        self.analyses = {}  # FEN -> Stockfish-Bewertung aller Züge (siehe annotate.py)
82
+        self.symbols = {}  # Halbzug-Index -> "!", "??", …
83
+        self.badge_ply = None
84
+        self.hint_move = None
85
+        self.hint_level = 0
86
+        self.hint_pending = False
87
+        self.hint_error = None
88
+        self.hint_prefetch_gen = None
89
+        self.thinking = None  # laufende Stockfish-Rechnung, während der Mensch nachdenkt
90
+        self.pending_symbols = {}  # FEN -> (Halbzug, Zug, Stellung davor)
91
+        self.maia_ready = app.maia_ready
92
+        self.maia_thinking = False
93
+        self.save_name = ""
94
+        self.save_path = ""
95
+        self._autosave_source = 0
96
+        self.evals = {}  # Halbzug-Index -> Gewinnchance Weiß (%) nach diesem Zug
97
+        self.eval_requested = set()
98
+        self.key_ply = {}  # FEN -> Halbzug-Index der Stellung
99
+        self.browse_ply = None  # in der Zugliste gewählte Stellung (nur Ansicht)
100
+        self.end_shown = False
101
+        self.mode = "maia"
102
+        self.opponent = ""  # Gegnername, wenn nicht Maia
103
+        self.final_text = None  # Partie-Ende, das nicht am Brett ablesbar ist (Aufgabe, Zeit, Rätsel gelöst)
104
+        self.puzzle = None
105
+        self.review_requested = set()
106
+        self._online_init()
107
+
108
+        # Engines gehören der App und werden von allen Fenstern geteilt
109
+        self.maia = app.maia
110
+        self.stockfish = app.stockfish
111
+
112
+        self._build_ui()
113
+        self._install_actions()
114
+        self.connect("close-request", self._on_close)
115
+        self.connect("notify::is-active", self._on_active_changed)
116
+
117
+        if state is not None:
118
+            self.load_state(state)
119
+        elif blank:
120
+            self._refresh()
121
+        else:
122
+            color = {"white": chess.WHITE, "black": chess.BLACK}.get(self.settings["color"])
123
+            self.new_game(color if color is not None else random.choice([chess.WHITE, chess.BLACK]))
124
+
125
+    # --- Oberfläche --------------------------------------------------------
126
+
127
+    def _build_ui(self):
128
+        self.title = Adw.WindowTitle(title="Schach")
129
+        header = Adw.HeaderBar(title_widget=self.title)
130
+
131
+        new_btn = Gtk.Button(icon_name="list-add-symbolic", tooltip_text="Neue Partie (Strg+N)")
132
+        new_btn.set_action_name("win.new-game")
133
+        header.pack_start(new_btn)
134
+        undo_btn = Gtk.Button(icon_name="edit-undo-symbolic", tooltip_text="Zug zurücknehmen (Strg+Z)")
135
+        undo_btn.set_action_name("win.undo")
136
+        header.pack_start(undo_btn)
137
+        saves_btn = Gtk.Button(icon_name="document-open-symbolic", tooltip_text="Spielstände (Strg+O)")
138
+        saves_btn.set_action_name("win.open-saves")
139
+        header.pack_start(saves_btn)
140
+        self.undo_btn = undo_btn
141
+
142
+        difficulty = Gio.Menu()
143
+        for label, key in lichess.DIFFICULTIES:
144
+            difficulty.append(label, f"win.puzzle-difficulty::{key}")
145
+        puzzle_menu = Gio.Menu()
146
+        puzzle_menu.append_section("Schwierigkeit", difficulty)
147
+        puzzle_btn = Adw.SplitButton(
148
+            label="Rätsel", menu_model=puzzle_menu, tooltip_text="Neues Lichess-Rätsel (R)",
149
+            dropdown_tooltip="Schwierigkeit",
150
+        )
151
+        puzzle_btn.set_action_name("win.puzzle")
152
+        header.pack_start(puzzle_btn)
153
+
154
+        menu = Gio.Menu()
155
+        section = Gio.Menu()
156
+        section.append("Spielstand speichern …", "win.save-game")
157
+        section.append("Spielstände …", "win.open-saves")
158
+        section.append("Als PGN exportieren …", "win.save-pgn")
159
+        menu.append_section(None, section)
160
+        self.lichess_section = Gio.Menu()
161
+        menu.append_section("Lichess", self.lichess_section)
162
+        self.update_lichess_menu()
163
+        menu.append("Brett drehen", "win.flip")
164
+        themes = Gio.Menu()
165
+        installed = set(available_themes())
166
+        for name in FEATURED_THEMES:
167
+            if name in installed:
168
+                label = "Eingebaut" if name == "python-chess" else name.capitalize()
169
+                themes.append(label, f"win.theme::{name}")
170
+        menu.append_submenu("Figuren", themes)
171
+        header.pack_end(Gtk.MenuButton(icon_name="open-menu-symbolic", menu_model=menu))
172
+
173
+        self.list_btn = Gtk.ToggleButton(
174
+            icon_name="sidebar-show-right-symbolic", tooltip_text="Zugliste und Bewertung (A)"
175
+        )
176
+        header.pack_end(self.list_btn)
177
+
178
+        self.hint_btn = Gtk.Button(label="Hinweis", tooltip_text="Hinweis von Maia 2000 (H)")
179
+        self.hint_btn.set_action_name("win.hint")
180
+        header.pack_end(self.hint_btn)
181
+
182
+        # nur während einer Online-Partie
183
+        self.online_box = Gtk.Box(spacing=6, visible=False)
184
+        draw_btn = Gtk.Button(label="Remis anbieten")
185
+        draw_btn.set_action_name("win.offer-draw")
186
+        resign_btn = Gtk.Button(label="Aufgeben", css_classes=["destructive-action"])
187
+        resign_btn.set_action_name("win.resign")
188
+        self.online_box.append(draw_btn)
189
+        self.online_box.append(resign_btn)
190
+        header.pack_end(self.online_box)
191
+
192
+        self.banner = Adw.Banner(button_label="Neue Partie")
193
+        self.banner.set_action_name("win.new-game")
194
+
195
+        self.view = BoardView(theme=self.settings["theme"])
196
+        self.view.on_move = self._on_board_move
197
+        self.view.on_inactive_click = self._on_inactive_board_click
198
+
199
+        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
200
+        box.append(self.banner)
201
+        box.append(self.view)
202
+
203
+        self.movelist = MoveList()
204
+        self.movelist.on_select = self._browse
205
+        self.movelist.on_copy = self._copy_fen
206
+        self.movelist.on_continue = self._continue_from
207
+
208
+        self.split = Adw.OverlaySplitView(
209
+            content=box, sidebar=self.movelist, sidebar_position=Gtk.PackType.END,
210
+            show_sidebar=False, max_sidebar_width=320, min_sidebar_width=220,
211
+        )
212
+        self.list_btn.bind_property(
213
+            "active", self.split, "show-sidebar", GObject.BindingFlags.BIDIRECTIONAL
214
+        )
215
+        self.split.connect("notify::show-sidebar", lambda *_: self._refresh())
216
+
217
+        self.toasts = Adw.ToastOverlay(child=self.split)
218
+        toolbar = Adw.ToolbarView(content=self.toasts)
219
+        toolbar.add_top_bar(header)
220
+        self.set_content(toolbar)
221
+
222
+    def _install_actions(self):
223
+        for name, handler in [
224
+            ("new-game", self._new_game_dialog),
225
+            ("undo", self.undo),
226
+            ("hint", self.hint),
227
+            ("flip", self.flip),
228
+            ("save-pgn", self._save_pgn),
229
+            ("save-game", self._save_game_dialog),
230
+            ("open-saves", self._saves_dialog),
231
+            ("end-browse", self._end_browse),
232
+            ("toggle-list", lambda *_: self.list_btn.set_active(not self.list_btn.get_active())),
233
+            ("puzzle", self._puzzle_action),
234
+            ("lichess-login", lambda *_: self.get_application().lichess_login(self)),
235
+            ("lichess-logout", lambda *_: self.get_application().lichess_logout()),
236
+            ("challenge", self._challenge_dialog),
237
+            ("lichess-games", self._lichess_games_dialog),
238
+            ("offer-draw", self._offer_draw),
239
+            ("resign", self._resign),
240
+        ]:
241
+            action = Gio.SimpleAction.new(name, None)
242
+            action.connect("activate", handler)
243
+            self.add_action(action)
244
+
245
+        theme = Gio.SimpleAction.new_stateful(
246
+            "theme", GLib.VariantType.new("s"), GLib.Variant.new_string(self.settings["theme"])
247
+        )
248
+        theme.connect("activate", self._on_theme)
249
+        self.add_action(theme)
250
+        difficulty = Gio.SimpleAction.new_stateful(
251
+            "puzzle-difficulty", GLib.VariantType.new("s"),
252
+            GLib.Variant.new_string(self.settings.get("puzzle_difficulty", "normal")),
253
+        )
254
+        difficulty.connect("activate", self._set_puzzle_difficulty)
255
+        self.add_action(difficulty)
256
+
257
+        app = self.get_application()
258
+        app.set_accels_for_action("win.new-game", ["<Control>n"])
259
+        app.set_accels_for_action("win.undo", ["<Control>z"])
260
+        app.set_accels_for_action("win.hint", ["h"])
261
+        app.set_accels_for_action("win.flip", ["f"])
262
+        app.set_accels_for_action("win.save-game", ["<Control>s"])
263
+        app.set_accels_for_action("win.open-saves", ["<Control>o"])
264
+        app.set_accels_for_action("win.save-pgn", ["<Control><Shift>s"])
265
+        app.set_accels_for_action("win.toggle-list", ["a"])
266
+        app.set_accels_for_action("win.end-browse", ["Escape"])
267
+        app.set_accels_for_action("win.puzzle", ["r"])
268
+
269
+    def _action(self, name):
270
+        return self.lookup_action(name)
271
+
272
+    def update_lichess_menu(self):
273
+        user = self.get_application().lichess_user
274
+        self.lichess_section.remove_all()
275
+        if user is None:
276
+            self.lichess_section.append("Bei Lichess anmelden …", "win.lichess-login")
277
+        else:
278
+            self.lichess_section.append("Freund herausfordern …", "win.challenge")
279
+            self.lichess_section.append("Meine Lichess-Partien …", "win.lichess-games")
280
+            self.lichess_section.append(f"Abmelden ({user.get('username', '')})", "win.lichess-logout")
281
+
282
+    # --- Zustand → Anzeige -------------------------------------------------
283
+
284
+    def _end_text(self):
285
+        if self.final_text is not None:
286
+            return self.final_text
287
+        if self.mode in ("online", "puzzle"):
288
+            return None  # das Ende meldet Lichess bzw. die Rätsel-Lösung
289
+        name = "Maia" if self.mode == "maia" else (self.opponent.split(" (")[0] or "Gegner")
290
+        return outcome_text(self.board, self.human, name)
291
+
292
+    def _over(self):
293
+        return self._end_text() is not None
294
+
295
+    def _human_to_move(self):
296
+        if self.mode == "review":
297
+            return False
298
+        if self.mode == "puzzle" and self.puzzle is None:
299
+            return False
300
+        if self.mode == "online" and self.online_full is None:
301
+            return False
302
+        return self.board.turn == self.human and not self._over()
303
+
304
+    def _busy(self):
305
+        """Läuft hier eine Partie, die man nicht einfach ersetzen sollte?"""
306
+        if self.mode == "online":
307
+            return self.final_text is None
308
+        return self.mode == "maia" and bool(self.board.move_stack) and not self._over()
309
+
310
+    def _leave_special(self):
311
+        """Online-Partie bzw. Rätsel verlassen, bevor das Fenster etwas anderes zeigt."""
312
+        self._online_leave()
313
+        self._puzzle_leave()
314
+        self.mode = "maia"
315
+        self.opponent = ""
316
+        self.final_text = None
317
+
318
+    def _reset_game_tables(self):
319
+        self.symbols.clear()
320
+        self.analyses.clear()
321
+        self.pending_symbols.clear()
322
+        self._truncate_extras(0)
323
+        self.review_requested = set()
324
+        self.end_shown = False
325
+        self.badge_ply = None
326
+        self.maia_thinking = False
327
+        self.view.selected = None
328
+
329
+    def _board_at(self, ply):
330
+        board = self.board.copy()
331
+        while len(board.move_stack) > ply + 1:
332
+            board.pop()
333
+        return board
334
+
335
+    def _browsing(self):
336
+        return self.browse_ply is not None and self.browse_ply < len(self.board.move_stack) - 1
337
+
338
+    def _refresh(self):
339
+        v = self.view
340
+        v.human = self.human
341
+        if self._browsing():
342
+            shown = self._board_at(self.browse_ply)
343
+            v.board = shown
344
+            v.last_move = shown.peek()
345
+            v.interactive = False
346
+            v.selected = None
347
+            v.hint_from = v.hint_to = None
348
+            symbol = self.symbols.get(self.browse_ply)
349
+            v.badge = (shown.peek().to_square, symbol) if symbol else None
350
+            v.queue_draw()
351
+            self._refresh_chrome()
352
+            self._start_thinking()
353
+            return
354
+
355
+        v.board = self.board
356
+        v.last_move = self.board.peek() if self.board.move_stack else None
357
+        v.interactive = self._human_to_move()
358
+        if not v.interactive:
359
+            v.selected = None
360
+
361
+        v.hint_from = self.hint_move.from_square if self.hint_move and self.hint_level >= 1 else None
362
+        v.hint_to = self.hint_move.to_square if self.hint_move and self.hint_level >= 2 else None
363
+
364
+        v.badge = None
365
+        if self.badge_ply is not None and self.badge_ply in self.symbols:
366
+            if self.badge_ply < len(self.board.move_stack):
367
+                mv = self.board.move_stack[self.badge_ply]
368
+                piece = self.board.piece_at(mv.to_square)
369
+                if piece and piece.color == self.human:
370
+                    v.badge = (mv.to_square, self.symbols[self.badge_ply])
371
+        v.queue_draw()
372
+        self._refresh_chrome()
373
+        self._start_thinking()
374
+
375
+    def _refresh_chrome(self):
376
+        side = "Weiß" if self.human == chess.WHITE else "Schwarz"
377
+        if self._browsing():
378
+            shown = self._board_at(self.browse_ply)
379
+            mover = shown.copy()
380
+            last = mover.pop()
381
+            number = f"{mover.fullmove_number}." if mover.turn == chess.WHITE else f"{mover.fullmove_number}…"
382
+            self.title.set_subtitle(f"Ansicht: Stellung nach {number} {mover.san(last)}")
383
+        elif self.mode == "puzzle":
384
+            self.title.set_subtitle(self._puzzle_subtitle())
385
+        elif self.mode == "online":
386
+            if self.online_full is None:
387
+                self.title.set_subtitle("Verbinde mit Lichess …")
388
+            else:
389
+                from .online import time_control_text
390
+                full = self.online_full
391
+                clock = full.get("clock")
392
+                tc = (time_control_text({"type": "clock", "limit": clock["initial"] / 1000,
393
+                                         "increment": clock["increment"] // 1000}) if clock
394
+                      else time_control_text({"type": "correspondence", "daysPerTurn": full.get("daysPerTurn", 1)}))
395
+                rated = "gewertet" if full.get("rated") else "ungewertet"
396
+                self.title.set_subtitle(f"gegen {self.opponent} · {tc} · {rated}")
397
+        elif self.mode == "review":
398
+            self.title.set_subtitle(f"gegen {self.opponent} · du warst {side}" if self.opponent else "Analyse")
399
+        elif not self.maia_ready:
400
+            self.title.set_subtitle("Maia wird geladen …")
401
+        else:
402
+            self.title.set_subtitle(f"Maia {self.elo} · du spielst {side}")
403
+        default_title = {"puzzle": "Rätsel", "online": "Lichess"}.get(self.mode, "Schach")
404
+        self.title.set_title(self.save_name or default_title)
405
+
406
+        hints = self.mode in ("maia", "puzzle")
407
+        can_hint = (
408
+            hints and self._human_to_move() and self.hint_level < 2 and not self.hint_pending
409
+            and not self._browsing()
410
+        )
411
+        self._action("hint").set_enabled(can_hint)
412
+        self.hint_btn.set_visible(hints)
413
+        self.hint_btn.set_label("Zug zeigen" if self.hint_level == 1 else "Hinweis")
414
+        self.hint_btn.set_tooltip_text(
415
+            "Hinweis (H) – das Rätsel zählt dann nicht als gelöst" if self.mode == "puzzle"
416
+            else "Hinweis von Maia 2000 (H)"
417
+        )
418
+        self._action("undo").set_enabled(self.mode == "maia" and self._human_has_moved())
419
+        self.undo_btn.set_visible(self.mode == "maia")
420
+        self.online_box.set_visible(self._online_running())
421
+        self._action("offer-draw").set_enabled(self._online_running() and len(self.board.move_stack) >= 2)
422
+        self._action("resign").set_enabled(self._online_running() and self.online_full is not None)
423
+        self._action("end-browse").set_enabled(self.browse_ply is not None)
424
+        logged_in = self.get_application().lichess_user is not None
425
+        self._action("challenge").set_enabled(logged_in)
426
+        self._action("lichess-games").set_enabled(logged_in)
427
+
428
+        text = self._end_text()
429
+        if self.mode == "puzzle":
430
+            p = self.puzzle
431
+            if text and p and p["rating_diff"] is not None:
432
+                text = f"{text} Deine Rätselwertung: {p['rating_diff']:+d}"
433
+            self.banner.set_button_label("Nächstes Rätsel")
434
+            self.banner.set_action_name("win.puzzle")
435
+        else:
436
+            self.banner.set_button_label("Neue Partie")
437
+            self.banner.set_action_name("win.new-game")
438
+        self.banner.set_title(text or "")
439
+        self.banner.set_revealed(text is not None)
440
+        if text and not self.end_shown:
441
+            self.end_shown = True
442
+            if self.mode != "puzzle":
443
+                self.list_btn.set_active(True)  # Partie vorbei: Analyse aufklappen
444
+
445
+        if self.split.get_show_sidebar():
446
+            self.movelist.update(self.board, self.evals, self.symbols, self.browse_ply)
447
+            self._request_missing_evals()
448
+
449
+    def _human_has_moved(self):
450
+        n = len(self.board.move_stack)
451
+        return n >= 1 if self.human == chess.WHITE else n >= 2
452
+
453
+    def _changed(self):
454
+        self._schedule_autosave()
455
+        self.gen += 1
456
+        self.hint_move = None
457
+        self.hint_level = 0
458
+        self.hint_pending = False
459
+        self.hint_error = None
460
+        self.hint_prefetch_gen = None
461
+        if self.thinking is not None:
462
+            self.thinking.stop()
463
+            self.thinking = None
464
+
465
+    # --- Partieablauf ------------------------------------------------------
466
+
467
+    def new_game(self, color):
468
+        self._leave_special()
469
+        self.save_name = ""
470
+        self.save_path = ""
471
+        self.human = color
472
+        self.board = chess.Board()
473
+        self._reset_game_tables()
474
+        self.view.flipped = color == chess.BLACK
475
+        self._changed()
476
+        self._refresh()
477
+        if self.board.turn != self.human:
478
+            self._request_maia_move()
479
+
480
+    def _on_board_move(self, src, dst):
481
+        candidates = [m for m in self.board.legal_moves if m.from_square == src and m.to_square == dst]
482
+        if not candidates:
483
+            return
484
+        if len(candidates) == 1:
485
+            self._play_human(candidates[0])
486
+        else:
487
+            self._ask_promotion(src, dst)
488
+
489
+    def _ask_promotion(self, src, dst):
490
+        dialog = Adw.AlertDialog(heading="Umwandeln in …")
491
+        for key, label in [("q", "Dame"), ("r", "Turm"), ("b", "Läufer"), ("n", "Springer")]:
492
+            dialog.add_response(key, label)
493
+        dialog.set_default_response("q")
494
+        dialog.set_close_response("cancel")
495
+        dialog.add_response("cancel", "Abbrechen")
496
+
497
+        def on_response(_d, response):
498
+            if response in "qrbn" and response:
499
+                piece = chess.Piece.from_symbol(response).piece_type
500
+                self._play_human(chess.Move(src, dst, promotion=piece))
501
+
502
+        dialog.connect("response", on_response)
503
+        dialog.present(self)
504
+
505
+    def _play_human(self, move):
506
+        if not self._human_to_move() or move not in self.board.legal_moves:
507
+            return
508
+        if self.mode == "online":
509
+            self._online_play(move)
510
+            return
511
+        if self.mode == "puzzle":
512
+            self._puzzle_play(move)
513
+            return
514
+        ply = len(self.board.move_stack)
515
+        before = self.board.copy()
516
+        key = annotate.key(before)
517
+        self.view.animate_move(self.board, move)
518
+        self.board.push(move)
519
+        self.browse_ply = None
520
+        self.badge_ply = ply
521
+        self._changed()  # stoppt das Mitdenken
522
+        self._refresh()
523
+
524
+        entry = self.analyses.get(key)
525
+        if entry and entry["depth"] >= annotate.MIN_DEPTH:
526
+            self._annotate(ply, move, before)
527
+        else:
528
+            # sehr schnell gezogen: die gestoppte Rechnung liefert gleich ihr letztes Ergebnis
529
+            self.pending_symbols[key] = (ply, move, before)
530
+
531
+        if not self._over():
532
+            self._request_maia_move()
533
+
534
+    def _request_maia_move(self):
535
+        gen = self.gen
536
+        started = time.monotonic()
537
+        self.maia_thinking = True
538
+
539
+        def apply(move):
540
+            if gen != self.gen or self.mode != "maia" or move not in self.board.legal_moves:
541
+                return False
542
+            self.maia_thinking = False
543
+            self.browse_ply = None  # weitergespielt: Auswahl in der Zugliste aufheben
544
+            self.view.animate_move(self.board, move)
545
+            self.board.push(move)
546
+            self._changed()
547
+            self._refresh()
548
+            return False
549
+
550
+        def on_move(move, error):
551
+            if gen != self.gen:
552
+                return
553
+            if error or move is None:
554
+                self.maia_thinking = False
555
+                self.toasts.add_toast(Adw.Toast(title=f"Maia-Fehler: {error}"))
556
+                return
557
+            wait = MIN_REPLY_SECONDS - (time.monotonic() - started)
558
+            if wait > 0:
559
+                GLib.timeout_add(int(wait * 1000), apply, move)
560
+            else:
561
+                apply(move)
562
+
563
+        self.maia.submit(maia_move(self.board, self.elo, OPPONENT_TEMPERATURE), on_move)
564
+
565
+    def _on_maia_ready(self, error):
566
+        if error:
567
+            self.title.set_subtitle("Maia konnte nicht gestartet werden")
568
+            self.toasts.add_toast(Adw.Toast(title=f"Maia-Fehler: {error}", timeout=0))
569
+            return
570
+        self.maia_ready = True
571
+        self._refresh()
572
+
573
+    def undo(self, *_):
574
+        if self.mode != "maia" or not self._human_has_moved():
575
+            return
576
+        while self.board.move_stack:
577
+            mover = not self.board.turn
578
+            self.board.pop()
579
+            if mover == self.human:
580
+                break
581
+        self._truncate_extras(len(self.board.move_stack))
582
+        self.badge_ply = None
583
+        self.maia_thinking = False
584
+        self._changed()
585
+        self._refresh()
586
+
587
+    def hint(self, *_):
588
+        if not self._human_to_move():
589
+            return
590
+        if self.hint_level == 1:
591
+            self.hint_level = 2
592
+            self._refresh()
593
+            return
594
+        if self.hint_level >= 2 or self.hint_pending:
595
+            return
596
+        if self.mode == "puzzle":
597
+            self._puzzle_hint()
598
+            self._reveal_hint()
599
+            return
600
+        if self.mode != "maia":
601
+            return
602
+        if self.hint_move is not None or self.hint_error is not None:
603
+            self._reveal_hint()  # im Hintergrund schon fertig berechnet
604
+        else:
605
+            self.hint_pending = True  # Vorausberechnung läuft noch; zeigt sich, sobald fertig
606
+            self._refresh()
607
+
608
+    def _reveal_hint(self):
609
+        if self.hint_move is None:
610
+            self.toasts.add_toast(Adw.Toast(title=f"Kein Hinweis möglich: {self.hint_error}"))
611
+        else:
612
+            self.hint_level = 1
613
+        self._refresh()
614
+
615
+    def _start_thinking(self):
616
+        """Sobald der Mensch am Zug ist: Maias Kandidaten holen, dann denkt Stockfish mit."""
617
+        if self.mode != "maia" or not self._human_to_move() or self.hint_prefetch_gen == self.gen:
618
+            return  # Online-Partien: Fair Play, kein Mitdenken; Rätsel: Lösung steht fest
619
+        if not self.is_active():
620
+            return  # nur das aktive Fenster lässt Stockfish mitdenken
621
+        gen = self.hint_prefetch_gen = self.gen
622
+        board = self.board.copy()
623
+        key = annotate.key(board)
624
+        self.key_ply[key] = len(board.move_stack)
625
+        thinking = self.thinking = annotate.Thinking()
626
+
627
+        def snapshot_from_thread(entry):
628
+            GLib.idle_add(self._on_snapshot, key, entry, False)
629
+
630
+        def hint_from_thread(move):
631
+            GLib.idle_add(self._on_hint, gen, move)
632
+
633
+        def on_done(entry, error):
634
+            if entry is not None:
635
+                self._on_snapshot(key, entry, True)
636
+            elif error is not None:
637
+                self._on_hint(gen, None, error)
638
+
639
+        def on_candidates(moves, error):
640
+            # Auch wenn schon gezogen wurde: die Rechnung liefert dann rasch die Bewertung
641
+            job = annotate.think_job(board, moves or [], thinking, snapshot_from_thread, hint_from_thread)
642
+            self.stockfish.submit(job, on_done)
643
+
644
+        self.maia.submit(maia_candidates(board, HINT_ELO), on_candidates)
645
+
646
+    def _on_snapshot(self, key, entry, final):
647
+        old = self.analyses.get(key)
648
+        if old is None or entry["depth"] >= old["depth"] or len(entry["scores"]) > len(old["scores"]):
649
+            self.analyses[key] = entry
650
+        ply = self.key_ply.get(key)
651
+        stored = self.analyses[key]
652
+        if ply and stored["depth"] >= annotate.MIN_DEPTH and stored["scores"]:
653
+            # Bewertung der Stellung = Ergebnis des Zugs davor (Halbzug ply-1)
654
+            self._set_eval(ply - 1, max(stored["scores"].values()), self.human)
655
+        if key in self.pending_symbols and (final or self.analyses[key]["depth"] >= annotate.MIN_DEPTH):
656
+            ply, move, before = self.pending_symbols.pop(key)
657
+            self._annotate(ply, move, before)
658
+        return False
659
+
660
+    def _on_hint(self, gen, move, error=None):
661
+        if gen != self.gen:
662
+            return False
663
+        self.hint_move = move
664
+        self.hint_error = error if move is None else None
665
+        if move is None and error is None:
666
+            self.hint_error = "kein Zug gefunden"
667
+        if self.hint_pending:
668
+            self.hint_pending = False
669
+            self._reveal_hint()
670
+        return False
671
+
672
+    def _annotate(self, ply, move, before):
673
+        if self.mode != "maia":
674
+            return
675
+        entry = self.analyses.get(annotate.key(before))
676
+        symbol = annotate.classify_with(entry, before, move)
677
+        if symbol is False:
678
+            def on_result(result, error):
679
+                if error is None:
680
+                    symbol, wp = result
681
+                    self._set_eval(ply, wp, before.turn, move)
682
+                    self._set_symbol(ply, move, symbol)
683
+
684
+            self.stockfish.submit(annotate.fallback_job(before, move, entry), on_result)
685
+        else:
686
+            if move in entry["scores"]:
687
+                self._set_eval(ply, entry["scores"][move], before.turn, move)
688
+            self._set_symbol(ply, move, symbol)
689
+
690
+    def _set_eval(self, ply, wp, color, move=None):
691
+        stack = self.board.move_stack
692
+        if ply >= len(stack) or (move is not None and stack[ply] != move):
693
+            return
694
+        white = round(wp if color == chess.WHITE else 100.0 - wp, 1)
695
+        if abs(self.evals.get(ply, -100) - white) < 1.0:
696
+            return  # kaum Änderung: Liste nicht neu aufbauen
697
+        self.evals[ply] = white
698
+        if self.split.get_show_sidebar():
699
+            self.movelist.update(self.board, self.evals, self.symbols, self.browse_ply)
700
+
701
+    def _request_missing_evals(self):
702
+        if self.mode == "online" or (self.mode == "puzzle" and not self._over()):
703
+            return  # während der Online-Partie bzw. vor der Lösung keine Engine-Bewertung
704
+        for ply, move in enumerate(self.board.move_stack):
705
+            if ply in self.evals or (ply, move) in self.eval_requested:
706
+                continue
707
+            if ply == len(self.board.move_stack) - 1 and self._human_to_move() and self.mode == "maia":
708
+                continue  # kommt gleich aus dem Mitdenken
709
+            self.eval_requested.add((ply, move))
710
+            self.stockfish.submit(
711
+                annotate.white_eval_job(self._board_at(ply)),
712
+                lambda wp, error, ply=ply, move=move: error or self._set_eval(ply, wp, chess.WHITE, move),
713
+            )
714
+
715
+    def _analyze_review(self):
716
+        """Fertige Partie: alle eigenen Züge nachträglich mit Zeichen versehen."""
717
+        if self.mode != "review":
718
+            return
719
+        gen = self.gen
720
+        for ply, move in enumerate(self.board.move_stack):
721
+            before = self._board_at(ply - 1)
722
+            if before.turn != self.human or ply in self.symbols or ply in self.review_requested:
723
+                continue
724
+            self.review_requested.add(ply)
725
+
726
+            def on_result(result, error, ply=ply, move=move, before=before):
727
+                if error is None and gen == self.gen:
728
+                    symbol, wp = result
729
+                    self._set_eval(ply, wp, before.turn, move)
730
+                    self._set_symbol(ply, move, symbol)
731
+
732
+            self.stockfish.submit(annotate.fallback_job(before, move), on_result)
733
+
734
+    def _truncate_extras(self, n):
735
+        for table in (self.symbols, self.evals):
736
+            for ply in [p for p in table if p >= n]:
737
+                del table[ply]
738
+        self.eval_requested = {(p, m) for p, m in self.eval_requested if p < n}
739
+        self.browse_ply = None
740
+
741
+    # --- Zugliste ----------------------------------------------------------
742
+
743
+    def _browse(self, ply):
744
+        self.browse_ply = ply
745
+        self._refresh()
746
+
747
+    def _end_browse(self, *_):
748
+        if self.browse_ply is None:
749
+            return False
750
+        self.browse_ply = None
751
+        self._refresh()
752
+        return True
753
+
754
+    def _on_inactive_board_click(self):
755
+        """Klick aufs Brett beim Anschauen einer alten Stellung: zurück zum Spiel."""
756
+        return self._end_browse() and self.view.interactive
757
+
758
+    def _copy_fen(self, ply):
759
+        fen = self._board_at(ply).fen()
760
+        self.get_clipboard().set(fen)
761
+        self.toasts.add_toast(Adw.Toast(title="FEN kopiert", timeout=2))
762
+
763
+    def _continue_from(self, ply):
764
+        """Abzweigung: die Partie ab dieser Stellung in einem neuen Fenster, das Original bleibt."""
765
+        state = self.state().truncated(ply)
766
+        state.elo = self.elo or int(self.settings["elo"])
767
+        board = state.board.copy()
768
+        last = board.pop()
769
+        number = f"{board.fullmove_number}." if board.turn == chess.WHITE else f"{board.fullmove_number}…"
770
+        state.name = f"Abzweigung nach {number} {board.san(last)}"
771
+        self.get_application().open_window(state)
772
+
773
+    def _set_symbol(self, ply, move, symbol):
774
+        stack = self.board.move_stack
775
+        if symbol and len(stack) > ply and stack[ply] == move:
776
+            self.symbols[ply] = symbol
777
+            self._schedule_autosave()
778
+            self._refresh()
779
+        return False
780
+
781
+    def flip(self, *_):
782
+        self.view.flipped = not self.view.flipped
783
+        self.view.queue_draw()
784
+
785
+    def _on_theme(self, action, value):
786
+        action.set_state(value)
787
+        self.settings["theme"] = value.get_string()
788
+        save_settings(self.settings)
789
+        self.view.set_theme(value.get_string())
790
+
791
+    # --- Dialoge -----------------------------------------------------------
792
+
793
+    def _new_game_dialog(self, *_):
794
+        dialog = Adw.AlertDialog(heading="Neue Partie")
795
+        dialog.add_response("cancel", "Abbrechen")
796
+        dialog.add_response("play", "Spielen")
797
+        dialog.set_response_appearance("play", Adw.ResponseAppearance.SUGGESTED)
798
+        dialog.set_default_response("play")
799
+        dialog.set_close_response("cancel")
800
+
801
+        group = Adw.PreferencesGroup()
802
+        colors = ["white", "black", "random"]
803
+        color_row = Adw.ComboRow(title="Deine Farbe", model=Gtk.StringList.new(["Weiß", "Schwarz", "Zufällig"]))
804
+        color_row.set_selected(colors.index(self.settings.get("color", "white")))
805
+        group.add(color_row)
806
+
807
+        elo_row = Adw.ActionRow(title="Stärke von Maia")
808
+        elo_label = Gtk.Label(css_classes=["numeric", "heading"])
809
+        elo_row.add_suffix(elo_label)
810
+        group.add(elo_row)
811
+
812
+        scale = Gtk.Scale.new_with_range(Gtk.Orientation.HORIZONTAL, 600, 2500, 50)
813
+        scale.set_draw_value(False)
814
+        scale.set_hexpand(True)
815
+        scale.set_margin_top(6)
816
+        for mark in (1000, 1500, 2000):
817
+            scale.add_mark(mark, Gtk.PositionType.BOTTOM, str(mark))
818
+
819
+        def snap(value):
820
+            return int(round(value / 50) * 50)
821
+
822
+        def update_label(s):
823
+            elo_label.set_label(f"{snap(s.get_value())} Elo")
824
+
825
+        scale.connect("value-changed", update_label)
826
+        scale.set_value(self.elo)
827
+        update_label(scale)
828
+
829
+        box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6, width_request=320)
830
+        box.append(group)
831
+        box.append(scale)
832
+        dialog.set_extra_child(box)
833
+
834
+        def on_response(_d, response):
835
+            if response != "play":
836
+                return
837
+            choice = colors[color_row.get_selected()]
838
+            self.elo = snap(scale.get_value())
839
+            self.settings.update(elo=self.elo, color=choice)
840
+            save_settings(self.settings)
841
+            color = {"white": chess.WHITE, "black": chess.BLACK}.get(choice)
842
+            self.new_game(color if color is not None else random.choice([chess.WHITE, chess.BLACK]))
843
+
844
+        dialog.connect("response", on_response)
845
+        dialog.present(self)
846
+
847
+    # --- Spielstände -------------------------------------------------------
848
+
849
+    def state(self):
850
+        return savegames.GameState(
851
+            board=self.board.copy(),
852
+            human=self.human,
853
+            elo=self.elo,
854
+            symbols=dict(self.symbols),
855
+            evals=dict(self.evals),
856
+            name=self.save_name,
857
+            path=self.save_path,
858
+            mode="maia" if self.mode == "maia" else "review",
859
+            opponent=self.opponent,
860
+            final_text=self.final_text or "",
861
+        )
862
+
863
+    def load_state(self, state):
864
+        self._leave_special()
865
+        self.mode = state.mode if state.mode in ("maia", "review") else "review"
866
+        self.opponent = state.opponent
867
+        self.final_text = state.final_text or None
868
+        self.human = state.human
869
+        self.elo = state.elo or int(self.settings["elo"])
870
+        self.board = state.board.copy()
871
+        self._reset_game_tables()
872
+        self.eval_requested = set()
873
+        self.symbols = dict(state.symbols)
874
+        self.evals = dict(state.evals)
875
+        self.save_name = state.name
876
+        self.save_path = state.path
877
+        self.end_shown = self._over()
878
+        self.view.flipped = self.human == chess.BLACK
879
+        self._changed()
880
+        self._refresh()
881
+        if self.mode == "review":
882
+            if not self.end_shown:
883
+                self.list_btn.set_active(True)
884
+                self.end_shown = True
885
+            self._analyze_review()
886
+        elif not self._over() and self.board.turn != self.human:
887
+            self._request_maia_move()
888
+
889
+    def _schedule_autosave(self):
890
+        if self._autosave_source:
891
+            GLib.source_remove(self._autosave_source)
892
+        self._autosave_source = GLib.timeout_add(AUTOSAVE_DELAY_MS, self._autosave)
893
+
894
+    def _autosave(self):
895
+        self._autosave_source = 0
896
+        if not self.board.move_stack:
897
+            return False
898
+        try:
899
+            if self.mode == "maia":
900
+                savegames.write_autosave(self.state())
901
+            elif self.mode == "review" and self.save_path:
902
+                savegames.save(self.state(), self.save_name)  # Analyse-Zeichen mitspeichern
903
+        except OSError:
904
+            pass
905
+        return False
906
+
907
+    def _save_game_dialog(self, *_):
908
+        dialog = Adw.AlertDialog(heading="Spielstand speichern")
909
+        dialog.add_response("cancel", "Abbrechen")
910
+        dialog.add_response("save", "Speichern")
911
+        dialog.set_response_appearance("save", Adw.ResponseAppearance.SUGGESTED)
912
+        dialog.set_default_response("save")
913
+        dialog.set_close_response("cancel")
914
+        default = self.save_name or f"Partie vom {datetime.datetime.now():%d.%m. %H:%M}"
915
+        entry = Gtk.Entry(text=default, activates_default=True, width_request=300)
916
+        dialog.set_extra_child(entry)
917
+
918
+        def on_response(_d, response):
919
+            name = entry.get_text().strip()
920
+            if response != "save" or not name:
921
+                return
922
+            state = self.state()
923
+            try:
924
+                savegames.save(state, name)
925
+            except OSError as exc:
926
+                self.toasts.add_toast(Adw.Toast(title=f"Speichern fehlgeschlagen: {exc}"))
927
+                return
928
+            self.save_name, self.save_path = state.name, state.path
929
+            self._refresh()
930
+            self.toasts.add_toast(Adw.Toast(title=f"„{name}“ gespeichert", timeout=2))
931
+
932
+        dialog.connect("response", on_response)
933
+        dialog.present(self)
934
+        entry.grab_focus()
935
+
936
+    def _saves_dialog(self, *_):
937
+        dialog = Adw.Dialog(title="Spielstände", content_width=460, content_height=520)
938
+        toolbar = Adw.ToolbarView()
939
+        toolbar.add_top_bar(Adw.HeaderBar())
940
+        dialog.set_child(toolbar)
941
+
942
+        def fill():
943
+            saves = savegames.list_saves()
944
+            if not saves:
945
+                toolbar.set_content(Adw.StatusPage(
946
+                    icon_name="document-open-symbolic",
947
+                    title="Noch keine Spielstände",
948
+                    description="Mit Strg+S speicherst du die aktuelle Partie unter einem Namen.",
949
+                ))
950
+                return
951
+            page = Adw.PreferencesPage()
952
+            group = Adw.PreferencesGroup()
953
+            page.add(group)
954
+            for path, state, when in saves:
955
+                moves = len(state.board.move_stack)
956
+                side = "Weiß" if state.human == chess.WHITE else "Schwarz"
957
+                result = outcome_text(state.board, state.human)
958
+                status = state.final_text or result or f"Zug {state.board.fullmove_number}"
959
+                against = state.opponent or f"Maia {state.elo}"
960
+                row = Adw.ActionRow(
961
+                    title=state.name or "Ohne Namen",
962
+                    subtitle=f"{status} · {moves} Halbzüge · {against} · du {side} · {when:%d.%m.%Y %H:%M}",
963
+                    use_markup=False,
964
+                    activatable=True,
965
+                )
966
+                row.connect("activated", lambda _r, st=state: (dialog.close(), self._open_state(st)))
967
+                trash = Gtk.Button(
968
+                    icon_name="user-trash-symbolic", tooltip_text="Löschen",
969
+                    css_classes=["flat"], valign=Gtk.Align.CENTER,
970
+                )
971
+                trash.connect("clicked", lambda _b, p=path, n=state.name: confirm_delete(p, n))
972
+                row.add_suffix(trash)
973
+                row.add_suffix(Gtk.Image(icon_name="go-next-symbolic"))
974
+                group.add(row)
975
+            toolbar.set_content(page)
976
+
977
+        def confirm_delete(path, name):
978
+            alert = Adw.AlertDialog(heading="Spielstand löschen?", body=f"„{name}“ wird endgültig gelöscht.")
979
+            alert.add_response("cancel", "Behalten")
980
+            alert.add_response("delete", "Löschen")
981
+            alert.set_response_appearance("delete", Adw.ResponseAppearance.DESTRUCTIVE)
982
+            alert.set_close_response("cancel")
983
+
984
+            def on_response(_a, response):
985
+                if response == "delete":
986
+                    savegames.delete(path)
987
+                    fill()
988
+
989
+            alert.connect("response", on_response)
990
+            alert.present(self)
991
+
992
+        fill()
993
+        dialog.present(self)
994
+
995
+    def _open_state(self, state):
996
+        """Laufende Partie nie überschreiben: dann öffnet der Spielstand in einem neuen Fenster."""
997
+        if self._busy():
998
+            self.get_application().open_window(state)
999
+        else:
1000
+            self.load_state(state)
1001
+
1002
+    def _pgn(self):
1003
+        return savegames.to_pgn(self.state())
1004
+
1005
+    def _save_pgn(self, *_):
1006
+        dialog = Gtk.FileDialog(initial_name=f"partie-{datetime.date.today():%Y-%m-%d}.pgn")
1007
+
1008
+        def on_done(d, result):
1009
+            try:
1010
+                file = d.save_finish(result)
1011
+            except GLib.Error:
1012
+                return
1013
+            with open(file.get_path(), "w") as fh:
1014
+                fh.write(self._pgn())
1015
+            self.toasts.add_toast(Adw.Toast(title="Partie gespeichert"))
1016
+
1017
+        dialog.save(self, None, on_done)
1018
+
1019
+    def _on_active_changed(self, *_):
1020
+        if self.is_active():
1021
+            self._refresh()  # startet das Mitdenken wieder
1022
+        elif self.thinking is not None:
1023
+            self.thinking.stop()
1024
+            self.thinking = None
1025
+            self.hint_prefetch_gen = None
1026
+
1027
+    def _puzzle_action(self, *_):
1028
+        """Rätsel: eine laufende Partie bleibt erhalten – dann im neuen Fenster."""
1029
+        if self._busy():
1030
+            win = self.get_application().open_window(None, blank=True)
1031
+            win.start_puzzle()
1032
+        else:
1033
+            self.start_puzzle()
1034
+
1035
+    def _on_close(self, *_):
1036
+        if self._online_running() and self.online_full is not None:
1037
+            self._confirm_close_online()
1038
+            return True
1039
+        self._online_leave()
1040
+        if self.thinking is not None:
1041
+            self.thinking.stop()
1042
+        if self._autosave_source:
1043
+            GLib.source_remove(self._autosave_source)
1044
+            self._autosave()
1045
+        return False
1046
+
1047
+
1048
+class SchachApp(Adw.Application):
1049
+    def __init__(self):
1050
+        super().__init__(application_id=APP_ID, flags=Gio.ApplicationFlags.DEFAULT_FLAGS)
1051
+        self.maia_ready = False
1052
+        self.maia = None
1053
+        self.stockfish = None
1054
+        self.lichess_client = None  # nur angemeldet
1055
+        self.lichess_user = None
1056
+        self.lichess_events = None
1057
+        self.lichess_pending_login = None
1058
+        self.expected_games = set()  # selbst angenommene/gestellte Herausforderungen
1059
+        self.challenge_dialogs = {}
1060
+
1061
+    def do_startup(self):
1062
+        Adw.Application.do_startup(self)
1063
+        self.maia = EngineWorker(MAIA_CMD, on_ready=self._on_maia_ready)
1064
+        self.stockfish = EngineWorker(
1065
+            STOCKFISH_CMD, options={"Threads": min(8, os.cpu_count() or 2), "Hash": 256}
1066
+        )
1067
+        token = lichess.load_token()
1068
+        if token:
1069
+            self._lichess_connect(token)
1070
+
1071
+    # --- Lichess-Konto -----------------------------------------------------
1072
+
1073
+    def _windows(self):
1074
+        return [w for w in self.get_windows() if isinstance(w, Window)]
1075
+
1076
+    def _toast(self, toast):
1077
+        win = self.get_active_window() or next(iter(self._windows()), None)
1078
+        if isinstance(win, Window):
1079
+            win.toasts.add_toast(toast)
1080
+
1081
+    def _lichess_connect(self, token, fresh=False):
1082
+        client = lichess.Client(token)
1083
+
1084
+        def on_account(account, error):
1085
+            if error:
1086
+                if "401" in error or "No such token" in error or "invalid" in error.lower():
1087
+                    lichess.clear_token()
1088
+                    self._toast(Adw.Toast(title="Lichess-Anmeldung abgelaufen – bitte neu anmelden"))
1089
+                else:
1090
+                    self._toast(Adw.Toast(title=f"Lichess nicht erreichbar: {error}"))
1091
+                return
1092
+            self.lichess_client = client
1093
+            self.lichess_user = account
1094
+            if self.lichess_events is not None:
1095
+                self.lichess_events.close()
1096
+            self.lichess_events = lichess.EventStream(client, self._on_lichess_event)
1097
+            for win in self._windows():
1098
+                win.update_lichess_menu()
1099
+                win._refresh()
1100
+            if fresh:
1101
+                self._toast(Adw.Toast(title=f"Bei Lichess angemeldet als {account.get('username')}", timeout=3))
1102
+
1103
+        lichess._background(client.account, on_account)
1104
+
1105
+    def lichess_login(self, win):
1106
+        if self.lichess_pending_login is not None:
1107
+            self.lichess_pending_login.cancel()
1108
+
1109
+        def on_done(token, error):
1110
+            self.lichess_pending_login = None
1111
+            if error or not token:
1112
+                win.toasts.add_toast(Adw.Toast(title=f"Anmeldung fehlgeschlagen: {error}"))
1113
+                return
1114
+            try:
1115
+                lichess.store_token(token)
1116
+            except GLib.Error as exc:
1117
+                win.toasts.add_toast(Adw.Toast(title=f"Schlüsselbund nicht verfügbar: {exc.message}"))
1118
+            self._lichess_connect(token, fresh=True)
1119
+
1120
+        login = self.lichess_pending_login = lichess.Login(on_done)
1121
+        login.start()
1122
+        win.toasts.add_toast(Adw.Toast(title="Im Browser bei Lichess anmelden und „Erlauben“ wählen", timeout=8))
1123
+
1124
+    def lichess_logout(self):
1125
+        client = self.lichess_client
1126
+        if self.lichess_events is not None:
1127
+            self.lichess_events.close()
1128
+        self.lichess_events = None
1129
+        self.lichess_client = None
1130
+        self.lichess_user = None
1131
+        lichess.clear_token()
1132
+        if client is not None:
1133
+            lichess._background(client.revoke, lambda *_: None)
1134
+        for win in self._windows():
1135
+            win.update_lichess_menu()
1136
+            win._refresh()
1137
+        self._toast(Adw.Toast(title="Von Lichess abgemeldet", timeout=2))
1138
+
1139
+    def _free_window(self):
1140
+        win = self.get_active_window()
1141
+        if isinstance(win, Window) and not win._busy():
1142
+            return win
1143
+        return self.open_window(None, blank=True)
1144
+
1145
+    def _open_online(self, game_id):
1146
+        for win in self._windows():
1147
+            if win.online_id == game_id:
1148
+                win.present()
1149
+                return
1150
+        win = self._free_window()
1151
+        win.start_online(game_id)
1152
+        win.present()
1153
+
1154
+    def _on_lichess_event(self, event):
1155
+        kind = event.get("type")
1156
+        if kind == "gameStart":
1157
+            game = event.get("game", {})
1158
+            game_id = game.get("gameId") or game.get("id")
1159
+            if not game_id or not (game.get("compat") or {}).get("board", True):
1160
+                return
1161
+            if any(w.online_id == game_id for w in self._windows()):
1162
+                return
1163
+            if game_id in self.expected_games:
1164
+                self.expected_games.discard(game_id)
1165
+                self._open_online(game_id)
1166
+            else:
1167
+                # laufende Partie (z. B. nach Neustart oder im Browser begonnen): nur anbieten
1168
+                opponent = (game.get("opponent") or {}).get("username", "?")
1169
+                toast = Adw.Toast(title=f"Laufende Lichess-Partie gegen {opponent}", button_label="Öffnen", timeout=0)
1170
+                toast.connect("button-clicked", lambda *_: self._open_online(game_id))
1171
+                self._toast(toast)
1172
+        elif kind == "challenge":
1173
+            challenge = event.get("challenge", {})
1174
+            me = (self.lichess_user or {}).get("id")
1175
+            dest = challenge.get("destUser") or {}
1176
+            if dest.get("id") != me or challenge.get("id") in self.challenge_dialogs:
1177
+                return  # eigene Herausforderung oder schon gezeigt
1178
+            win = self.get_active_window()
1179
+            if not isinstance(win, Window):
1180
+                win = next(iter(self._windows()), None)
1181
+            if win is not None:
1182
+                self.challenge_dialogs[challenge["id"]] = win.incoming_challenge(challenge)
1183
+        elif kind in ("challengeCanceled", "challengeDeclined"):
1184
+            challenge_id = (event.get("challenge") or {}).get("id")
1185
+            dialog = self.challenge_dialogs.pop(challenge_id, None)
1186
+            if dialog is not None and kind == "challengeCanceled":
1187
+                dialog.force_close()
1188
+                self._toast(Adw.Toast(title="Herausforderung zurückgezogen", timeout=3))
1189
+
1190
+    def _on_maia_ready(self, error):
1191
+        self.maia_ready = error is None
1192
+        for win in self.get_windows():
1193
+            if isinstance(win, Window):
1194
+                win._on_maia_ready(error)
1195
+        return False
1196
+
1197
+    def do_activate(self):
1198
+        win = self.get_active_window()
1199
+        if win is None:
1200
+            # Weiterspielen, wo man aufgehört hat
1201
+            state = savegames.read_autosave()
1202
+            resumable = state and state.board.move_stack and not state.board.is_game_over(claim_draw=True)
1203
+            win = Window(self, state if resumable else None)
1204
+            if resumable:
1205
+                win.toasts.add_toast(Adw.Toast(title="Letzte Partie fortgesetzt", timeout=3))
1206
+        win.present()
1207
+
1208
+    def open_window(self, state, blank=False):
1209
+        win = Window(self, state, blank=blank)
1210
+        win.present()
1211
+        return win
1212
+
1213
+    def do_shutdown(self):
1214
+        for win in self.get_windows():
1215
+            if isinstance(win, Window):
1216
+                win._online_leave()
1217
+                if win.thinking is not None:
1218
+                    win.thinking.stop()
1219
+        if self.lichess_events is not None:
1220
+            self.lichess_events.close()
1221
+        self.maia.close()
1222
+        self.stockfish.close()
1223
+        Adw.Application.do_shutdown(self)
1224
+
1225
+
1226
+def main():
1227
+    import logging
1228
+
1229
+    logging.getLogger("chess.engine").setLevel(logging.ERROR)
1230
+    return SchachApp().run(sys.argv)

added schach/board.py +479 −0

@@ -0,0 +1,479 @@
1
+"""Das Schachbrett als GTK4-Widget (Cairo + librsvg)."""
2
+
3
+import math
4
+import os
5
+
6
+import cairo
7
+import chess
8
+import chess.svg
9
+import gi
10
+
11
+gi.require_version("Gtk", "4.0")
12
+gi.require_version("Rsvg", "2.0")
13
+from gi.repository import GLib, Gtk, Rsvg  # noqa: E402
14
+
15
+ANIM_SECONDS = 0.22
16
+STRIP = 0.5  # Höhe der Streifen für geschlagene Figuren, in Feldgrößen
17
+VALUE = {chess.PAWN: 1, chess.KNIGHT: 3, chess.BISHOP: 3, chess.ROOK: 5, chess.QUEEN: 9, chess.KING: 0}
18
+
19
+PYCHESS_PIECES = "/usr/share/pychess/pieces"
20
+BUILTIN_THEME = "python-chess"
21
+
22
+LIGHT = (0.941, 0.851, 0.710)
23
+DARK = (0.710, 0.533, 0.388)
24
+LAST_MOVE = (0.80, 0.82, 0.25, 0.42)
25
+SELECTED = (0.08, 0.50, 0.20, 0.45)
26
+HINT = (0.21, 0.52, 0.89)
27
+CHECK = (0.88, 0.11, 0.14)
28
+BADGE = {
29
+    "!!": (0.10, 0.62, 0.55),
30
+    "!": (0.30, 0.52, 0.80),
31
+    "?!": (0.86, 0.66, 0.08),
32
+    "?": (0.90, 0.45, 0.10),
33
+    "??": (0.82, 0.13, 0.13),
34
+}
35
+
36
+
37
+def available_themes():
38
+    themes = []
39
+    if os.path.isdir(PYCHESS_PIECES):
40
+        for name in sorted(os.listdir(PYCHESS_PIECES)):
41
+            if os.path.isfile(os.path.join(PYCHESS_PIECES, name, "wk.svg")):
42
+                themes.append(name)
43
+    return [BUILTIN_THEME] + themes
44
+
45
+
46
+def load_pieces(theme):
47
+    handles = {}
48
+    for symbol in "PNBRQKpnbrqk":
49
+        piece = chess.Piece.from_symbol(symbol)
50
+        path = os.path.join(
51
+            PYCHESS_PIECES, theme, ("w" if piece.color else "b") + symbol.lower() + ".svg"
52
+        )
53
+        if theme != BUILTIN_THEME and os.path.isfile(path):
54
+            handles[symbol] = Rsvg.Handle.new_from_file(path)
55
+        else:
56
+            handles[symbol] = Rsvg.Handle.new_from_data(chess.svg.piece(piece).encode())
57
+    return handles
58
+
59
+
60
+class BoardView(Gtk.DrawingArea):
61
+    def __init__(self, theme="cburnett"):
62
+        super().__init__(hexpand=True, vexpand=True)
63
+        self.set_size_request(320, 320)
64
+
65
+        self.board = chess.Board()
66
+        self.human = chess.WHITE
67
+        self.flipped = False
68
+        self.interactive = False
69
+        self.last_move = None
70
+        self.hint_from = None
71
+        self.hint_to = None
72
+        self.badge = None  # (feld, symbol)
73
+        self.selected = None
74
+        self.on_move = None  # callback(von, nach)
75
+        self.on_inactive_click = None  # callback() – Klick, während das Brett gesperrt ist
76
+        self.names = None  # {Farbe: "Name (1500)"} – Online-Partien
77
+        self.clocks = None  # {Farbe: Millisekunden}
78
+        self.clock_running = None  # Farbe, deren Uhr gerade läuft
79
+
80
+        self._drag_sq = None
81
+        self._drag_pos = None
82
+        self._drag_moved = False
83
+        self._was_selected = False
84
+        self._dropped = None  # (von, nach) des letzten per Maus gezogenen Zugs
85
+        self._anim = None
86
+        self._captures_key = None
87
+        self._captures = None
88
+        self.set_theme(theme)
89
+
90
+        self.set_draw_func(self._draw)
91
+        drag = Gtk.GestureDrag()
92
+        drag.connect("drag-begin", self._on_begin)
93
+        drag.connect("drag-update", self._on_update)
94
+        drag.connect("drag-end", self._on_end)
95
+        self.add_controller(drag)
96
+
97
+    def set_theme(self, theme):
98
+        self._pieces = load_pieces(theme)
99
+        self.queue_draw()
100
+
101
+    # --- Geometrie ---------------------------------------------------------
102
+
103
+    def _geometry(self):
104
+        w, h = self.get_width(), self.get_height()
105
+        size = max(min(w - 24, (h - 24) / (1 + 2 * STRIP / 8)), 8)
106
+        return (w - size) / 2, (h - size) / 2, size / 8
107
+
108
+    # --- Animation ---------------------------------------------------------
109
+
110
+    def animate_move(self, before, move):
111
+        """Vor ``board.push(move)`` aufrufen: lässt den Zug sichtbar ablaufen."""
112
+        dropped = self._dropped == (move.from_square, move.to_square)
113
+        self._dropped = None
114
+        piece = before.piece_at(move.from_square)
115
+        if piece is None:
116
+            return
117
+        movers = [] if dropped else [(piece, move.from_square, move.to_square)]
118
+
119
+        if before.is_castling(move):
120
+            rank = chess.square_rank(move.from_square)
121
+            if before.is_kingside_castling(move):
122
+                rook_from, rook_to = chess.square(7, rank), chess.square(5, rank)
123
+            else:
124
+                rook_from, rook_to = chess.square(0, rank), chess.square(3, rank)
125
+            movers.append((chess.Piece(chess.ROOK, piece.color), rook_from, rook_to))
126
+
127
+        captured = None
128
+        if before.is_en_passant(move):
129
+            square = move.to_square + (-8 if piece.color == chess.WHITE else 8)
130
+            captured = (chess.Piece(chess.PAWN, not piece.color), square)
131
+        elif before.is_capture(move) and not before.is_castling(move):
132
+            captured = (before.piece_at(move.to_square), move.to_square)
133
+
134
+        if not movers and captured is None:
135
+            return
136
+        self._anim = {
137
+            "start": GLib.get_monotonic_time(),
138
+            "movers": movers,
139
+            "captured": captured,
140
+            "progress": 0.0,
141
+        }
142
+        self.add_tick_callback(self._tick)
143
+
144
+    def _tick(self, widget, frame_clock):
145
+        if self._anim is None:
146
+            return GLib.SOURCE_REMOVE
147
+        t = (GLib.get_monotonic_time() - self._anim["start"]) / 1e6 / ANIM_SECONDS
148
+        if t >= 1.0:
149
+            self._anim = None
150
+            self.queue_draw()
151
+            return GLib.SOURCE_REMOVE
152
+        self._anim["progress"] = 1 - (1 - t) ** 3  # ease-out
153
+        self.queue_draw()
154
+        return GLib.SOURCE_CONTINUE
155
+
156
+    # --- Geschlagene Figuren -----------------------------------------------
157
+
158
+    def _captured_by(self):
159
+        """{Farbe: [geschlagene gegnerische Figuren]} aus dem Partieverlauf."""
160
+        key = (id(self.board), tuple(self.board.move_stack))
161
+        if key != self._captures_key:
162
+            result = {chess.WHITE: [], chess.BLACK: []}
163
+            replay = self.board.root()
164
+            for move in self.board.move_stack:
165
+                if replay.is_en_passant(move):
166
+                    result[replay.turn].append(chess.Piece(chess.PAWN, not replay.turn))
167
+                elif replay.is_capture(move) and not replay.is_castling(move):
168
+                    result[replay.turn].append(replay.piece_at(move.to_square))
169
+                replay.push(move)
170
+            self._captures_key, self._captures = key, result
171
+        captured = {c: list(p) for c, p in self._captures.items()}
172
+        # Die gerade verblassende Figur erscheint erst nach der Animation im Streifen
173
+        if self._anim and self._anim["captured"]:
174
+            piece = self._anim["captured"][0]
175
+            if piece in captured[not piece.color]:
176
+                captured[not piece.color].remove(piece)
177
+        return captured
178
+
179
+    def _material(self, color):
180
+        return sum(VALUE[p.piece_type] for p in self.board.piece_map().values() if p.color == color)
181
+
182
+    def _square_origin(self, square):
183
+        ox, oy, sq = self._geometry()
184
+        f, r = chess.square_file(square), chess.square_rank(square)
185
+        col, row = (7 - f, r) if self.flipped else (f, 7 - r)
186
+        return ox + col * sq, oy + row * sq
187
+
188
+    def _square_at(self, x, y):
189
+        ox, oy, sq = self._geometry()
190
+        col, row = math.floor((x - ox) / sq), math.floor((y - oy) / sq)
191
+        if not (0 <= col < 8 and 0 <= row < 8):
192
+            return None
193
+        return chess.square(7 - col, row) if self.flipped else chess.square(col, 7 - row)
194
+
195
+    def _targets(self, src):
196
+        return {m.to_square for m in self.board.legal_moves if m.from_square == src}
197
+
198
+    # --- Eingabe -----------------------------------------------------------
199
+
200
+    def _on_begin(self, gesture, x, y):
201
+        if not self.interactive:
202
+            if self.on_inactive_click and self.on_inactive_click():
203
+                self._on_begin(gesture, x, y)  # wieder spielbar: Klick normal verarbeiten
204
+            return
205
+        s = self._square_at(x, y)
206
+        if s is None:
207
+            return
208
+        if self.selected is not None and s in self._targets(self.selected):
209
+            self._commit(self.selected, s)
210
+            return
211
+        piece = self.board.piece_at(s)
212
+        if piece and piece.color == self.human:
213
+            self._was_selected = self.selected == s
214
+            self.selected = s
215
+            self._drag_sq, self._drag_pos, self._drag_moved = s, (x, y), False
216
+        else:
217
+            self.selected = None
218
+        self.queue_draw()
219
+
220
+    def _on_update(self, gesture, dx, dy):
221
+        if self._drag_sq is None:
222
+            return
223
+        _, sx, sy = gesture.get_start_point()
224
+        self._drag_pos = (sx + dx, sy + dy)
225
+        if abs(dx) + abs(dy) > 4:
226
+            self._drag_moved = True
227
+        self.queue_draw()
228
+
229
+    def _on_end(self, gesture, dx, dy):
230
+        if self._drag_sq is None:
231
+            return
232
+        _, sx, sy = gesture.get_start_point()
233
+        src, self._drag_sq = self._drag_sq, None
234
+        target = self._square_at(sx + dx, sy + dy)
235
+        if self._drag_moved:
236
+            if target is not None and target in self._targets(src):
237
+                self._dropped = (src, target)
238
+                self._commit(src, target)
239
+            elif target != src:
240
+                self.selected = None
241
+        elif self._was_selected:
242
+            self.selected = None  # zweiter Klick auf dieselbe Figur hebt Auswahl auf
243
+        self.queue_draw()
244
+
245
+    def _commit(self, src, dst):
246
+        self.selected = None
247
+        self._drag_sq = None
248
+        self.queue_draw()
249
+        if self.on_move:
250
+            self.on_move(src, dst)
251
+
252
+    # --- Zeichnen ----------------------------------------------------------
253
+
254
+    def _draw(self, area, cr, width, height):
255
+        ox, oy, sq = self._geometry()
256
+
257
+        for square in chess.SQUARES:
258
+            x, y = self._square_origin(square)
259
+            light = (chess.square_file(square) + chess.square_rank(square)) % 2 == 1
260
+            cr.set_source_rgb(*(LIGHT if light else DARK))
261
+            cr.rectangle(x, y, sq, sq)
262
+            cr.fill()
263
+
264
+        if self.last_move:
265
+            for s in (self.last_move.from_square, self.last_move.to_square):
266
+                self._fill_square(cr, s, sq, LAST_MOVE)
267
+        if self.selected is not None:
268
+            self._fill_square(cr, self.selected, sq, SELECTED)
269
+        if self.board.is_check():
270
+            king = self.board.king(self.board.turn)
271
+            if king is not None:
272
+                self._glow(cr, king, sq, CHECK, 0.85)
273
+        for s in (self.hint_from, self.hint_to):
274
+            if s is not None:
275
+                self._glow(cr, s, sq, HINT, 0.9)
276
+                x, y = self._square_origin(s)
277
+                cr.set_source_rgba(*HINT, 0.95)
278
+                cr.set_line_width(max(sq * 0.05, 2))
279
+                inset = sq * 0.04
280
+                cr.rectangle(x + inset, y + inset, sq - 2 * inset, sq - 2 * inset)
281
+                cr.stroke()
282
+
283
+        self._draw_coordinates(cr, sq)
284
+
285
+        dragging = self._drag_sq is not None and self._drag_moved
286
+        anim = self._anim
287
+        hidden = {to for _, _, to in anim["movers"]} if anim else set()
288
+        if anim and anim["captured"]:
289
+            piece, square = anim["captured"]
290
+            p = anim["progress"]
291
+            scale = 1 - 0.35 * p
292
+            x, y = self._square_origin(square)
293
+            off = sq * (1 - scale) / 2
294
+            cr.push_group()
295
+            self._draw_piece(cr, piece, x + off, y + off, sq * scale)
296
+            cr.pop_group_to_source()
297
+            cr.paint_with_alpha(1 - p)
298
+        for square, piece in self.board.piece_map().items():
299
+            if (dragging and square == self._drag_sq) or square in hidden:
300
+                continue
301
+            x, y = self._square_origin(square)
302
+            self._draw_piece(cr, piece, x, y, sq)
303
+        if anim:
304
+            p = anim["progress"]
305
+            for piece, src, dst in anim["movers"]:
306
+                x0, y0 = self._square_origin(src)
307
+                x1, y1 = self._square_origin(dst)
308
+                self._draw_piece(cr, piece, x0 + (x1 - x0) * p, y0 + (y1 - y0) * p, sq)
309
+
310
+        self._draw_captures(cr, ox, oy, sq)
311
+        self._draw_players(cr, ox, oy, sq)
312
+
313
+        if self.selected is not None and self.interactive:
314
+            for t in self._targets(self.selected):
315
+                x, y = self._square_origin(t)
316
+                cr.new_path()  # show_text hinterlässt einen Current Point; arc() zöge sonst eine Linie von dort
317
+                cr.set_source_rgba(0, 0, 0, 0.2)
318
+                if self.board.piece_at(t):
319
+                    cr.set_line_width(sq * 0.07)
320
+                    cr.arc(x + sq / 2, y + sq / 2, sq * 0.45, 0, 2 * math.pi)
321
+                    cr.stroke()
322
+                else:
323
+                    cr.arc(x + sq / 2, y + sq / 2, sq * 0.15, 0, 2 * math.pi)
324
+                    cr.fill()
325
+
326
+        if self.badge:
327
+            self._draw_badge(cr, *self.badge, sq)
328
+
329
+        if dragging:
330
+            piece = self.board.piece_at(self._drag_sq)
331
+            if piece:
332
+                px, py = self._drag_pos
333
+                s = sq * 1.1
334
+                self._draw_piece(cr, piece, px - s / 2, py - s / 2, s)
335
+
336
+    def _fill_square(self, cr, square, sq, rgba):
337
+        x, y = self._square_origin(square)
338
+        cr.set_source_rgba(*rgba)
339
+        cr.rectangle(x, y, sq, sq)
340
+        cr.fill()
341
+
342
+    def _glow(self, cr, square, sq, rgb, alpha):
343
+        x, y = self._square_origin(square)
344
+        cx, cy = x + sq / 2, y + sq / 2
345
+        grad = cairo.RadialGradient(cx, cy, sq * 0.05, cx, cy, sq * 0.72)
346
+        grad.add_color_stop_rgba(0, *rgb, alpha)
347
+        grad.add_color_stop_rgba(0.6, *rgb, alpha * 0.5)
348
+        grad.add_color_stop_rgba(1, *rgb, 0)
349
+        cr.save()
350
+        cr.rectangle(x, y, sq, sq)
351
+        cr.clip()
352
+        cr.set_source(grad)
353
+        cr.paint()
354
+        cr.restore()
355
+
356
+    def _draw_piece(self, cr, piece, x, y, size):
357
+        rect = Rsvg.Rectangle()
358
+        rect.x, rect.y, rect.width, rect.height = x, y, size, size
359
+        self._pieces[piece.symbol()].render_document(cr, rect)
360
+
361
+    def _draw_coordinates(self, cr, sq):
362
+        cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
363
+        cr.set_font_size(sq * 0.16)
364
+        bottom_rank = 7 if self.flipped else 0
365
+        left_file = 7 if self.flipped else 0
366
+        for f in range(8):
367
+            square = chess.square(f, bottom_rank)
368
+            x, y = self._square_origin(square)
369
+            light = (f + bottom_rank) % 2 == 1
370
+            cr.set_source_rgb(*(DARK if light else LIGHT))
371
+            cr.move_to(x + sq * 0.80, y + sq * 0.94)
372
+            cr.show_text(chess.FILE_NAMES[f])
373
+        for r in range(8):
374
+            square = chess.square(left_file, r)
375
+            x, y = self._square_origin(square)
376
+            light = (left_file + r) % 2 == 1
377
+            cr.set_source_rgb(*(DARK if light else LIGHT))
378
+            cr.move_to(x + sq * 0.05, y + sq * 0.2)
379
+            cr.show_text(chess.RANK_NAMES[r])
380
+
381
+    def _draw_captures(self, cr, ox, oy, sq):
382
+        captured = self._captured_by()
383
+        bottom = chess.BLACK if self.flipped else chess.WHITE
384
+        diff = self._material(chess.WHITE) - self._material(chess.BLACK)
385
+        size = sq * STRIP * 0.9
386
+        for color in (chess.WHITE, chess.BLACK):
387
+            if color == bottom:
388
+                y = oy + 8 * sq + sq * STRIP * 0.05
389
+            else:
390
+                y = oy - sq * STRIP * 0.95
391
+            x = ox
392
+            pieces = sorted(captured[color], key=lambda p: (VALUE[p.piece_type], p.piece_type))
393
+            previous = None
394
+            for piece in pieces:
395
+                if previous is not None:
396
+                    x += size * (0.45 if piece.piece_type == previous else 0.85)
397
+                self._draw_piece(cr, piece, x, y, size)
398
+                previous = piece.piece_type
399
+            advantage = diff if color == chess.WHITE else -diff
400
+            if advantage > 0:
401
+                x += size * (1.0 if pieces else 0.0)
402
+                cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
403
+                cr.set_font_size(size * 0.55)
404
+                fg = self.get_color()  # folgt hellem/dunklem Stil
405
+                cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.7)
406
+                cr.move_to(x + size * 0.1, y + size * 0.72)
407
+                cr.show_text(f"+{advantage}")
408
+
409
+    def _draw_players(self, cr, ox, oy, sq):
410
+        """Name und Uhr rechts in den Streifen über und unter dem Brett."""
411
+        if not self.names and not self.clocks:
412
+            return
413
+        bottom = chess.BLACK if self.flipped else chess.WHITE
414
+        h = sq * STRIP
415
+        fg = self.get_color()
416
+        for color in (chess.WHITE, chess.BLACK):
417
+            y = oy + 8 * sq if color == bottom else oy - h
418
+            right = ox + 8 * sq
419
+            if self.clocks and color in self.clocks:
420
+                ms = max(0, self.clocks[color])
421
+                secs = int(ms // 1000)
422
+                text = f"{secs // 3600}:{secs // 60 % 60:02d}:{secs % 60:02d}" if secs >= 3600 else (
423
+                    f"{secs // 60}:{secs % 60:02d}" if secs >= 20 else f"{secs // 60}:{secs % 60:02d}.{int(ms % 1000) // 100}"
424
+                )
425
+                cr.select_font_face("Monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
426
+                cr.set_font_size(h * 0.55)
427
+                ext = cr.text_extents(text)
428
+                pad = h * 0.25
429
+                bw, bh = ext.x_advance + 2 * pad, h * 0.8
430
+                bx, by = right - bw, y + (h - bh) / 2
431
+                running = self.clock_running == color
432
+                low = ms < 20000
433
+                if running:
434
+                    cr.set_source_rgb(*((0.80, 0.20, 0.18) if low else (0.25, 0.55, 0.30)))
435
+                else:
436
+                    cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.12)
437
+                _rounded(cr, bx, by, bw, bh, bh * 0.25)
438
+                cr.fill()
439
+                if running:
440
+                    cr.set_source_rgb(1, 1, 1)
441
+                else:
442
+                    cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.85)
443
+                cr.move_to(bx + pad, by + bh / 2 + ext.height / 2)
444
+                cr.show_text(text)
445
+                right = bx - h * 0.3
446
+            if self.names and color in self.names:
447
+                cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
448
+                cr.set_font_size(h * 0.45)
449
+                text = self.names[color]
450
+                ext = cr.text_extents(text)
451
+                cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.75)
452
+                cr.move_to(right - ext.x_advance, y + h / 2 + ext.height / 2)
453
+                cr.show_text(text)
454
+
455
+    def _draw_badge(self, cr, square, text, sq):
456
+        x, y = self._square_origin(square)
457
+        r = sq * 0.19
458
+        cx, cy = x + sq - r * 0.9, y + r * 0.9
459
+        cr.set_source_rgba(0, 0, 0, 0.3)
460
+        cr.arc(cx + 1.5, cy + 1.5, r, 0, 2 * math.pi)
461
+        cr.fill()
462
+        cr.set_source_rgb(*BADGE.get(text, (0.4, 0.4, 0.4)))
463
+        cr.arc(cx, cy, r, 0, 2 * math.pi)
464
+        cr.fill()
465
+        cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
466
+        cr.set_font_size(r * (1.05 if len(text) == 1 else 0.95))
467
+        ext = cr.text_extents(text)
468
+        cr.set_source_rgb(1, 1, 1)
469
+        cr.move_to(cx - ext.width / 2 - ext.x_bearing, cy - ext.height / 2 - ext.y_bearing)
470
+        cr.show_text(text)
471
+
472
+
473
+def _rounded(cr, x, y, w, h, r):
474
+    cr.new_sub_path()
475
+    cr.arc(x + w - r, y + r, r, -math.pi / 2, 0)
476
+    cr.arc(x + w - r, y + h - r, r, 0, math.pi / 2)
477
+    cr.arc(x + r, y + h - r, r, math.pi / 2, math.pi)
478
+    cr.arc(x + r, y + r, r, math.pi, 3 * math.pi / 2)
479
+    cr.close_path()

added schach/engines.py +105 −0

@@ -0,0 +1,105 @@
1
+"""UCI-Engines in eigenen Threads, Ergebnisse kommen über GLib.idle_add zurück."""
2
+
3
+import queue
4
+import subprocess
5
+import threading
6
+
7
+import chess
8
+import chess.engine
9
+from gi.repository import GLib
10
+
11
+MAIA_CMD = ["maia3-uci", "--model", "79m", "--use-uci-history"]
12
+STOCKFISH_CMD = ["stockfish"]
13
+
14
+
15
+class EngineWorker:
16
+    """Ein UCI-Prozess, abgearbeitet von genau einem Thread.
17
+
18
+    Jobs sind Funktionen ``fn(engine) -> Ergebnis``; ``callback(ergebnis, fehler)``
19
+    läuft danach im GTK-Hauptthread.
20
+    """
21
+
22
+    def __init__(self, cmd, options=None, on_ready=None):
23
+        self._cmd = cmd
24
+        self._options = options or {}
25
+        self._on_ready = on_ready
26
+        self._jobs = queue.Queue()
27
+        self._error = None
28
+        threading.Thread(target=self._run, daemon=True).start()
29
+
30
+    def _run(self):
31
+        engine = None
32
+        try:
33
+            engine = chess.engine.SimpleEngine.popen_uci(
34
+                self._cmd, timeout=300, stderr=subprocess.DEVNULL
35
+            )
36
+            if self._options:
37
+                engine.configure(self._options)
38
+            engine.ping()  # wartet, bis z. B. Maia ihr Modell geladen hat
39
+        except Exception as exc:  # noqa: BLE001
40
+            self._error = exc
41
+            engine = None
42
+        if self._on_ready:
43
+            GLib.idle_add(self._on_ready, self._error)
44
+
45
+        while True:
46
+            job = self._jobs.get()
47
+            if job is None:
48
+                break
49
+            fn, callback = job
50
+            if engine is None:
51
+                GLib.idle_add(callback, None, self._error)
52
+                continue
53
+            try:
54
+                result, error = fn(engine), None
55
+            except Exception as exc:  # noqa: BLE001
56
+                result, error = None, exc
57
+            GLib.idle_add(callback, result, error)
58
+
59
+        if engine is not None:
60
+            try:
61
+                engine.quit()
62
+            except Exception:  # noqa: BLE001
63
+                pass
64
+
65
+    def submit(self, fn, callback):
66
+        self._jobs.put((fn, callback))
67
+
68
+    def close(self):
69
+        self._jobs.put(None)
70
+
71
+
72
+def maia_candidates(board, elo, count=5):
73
+    """Job-Fabrik: die wahrscheinlichsten Züge eines Spielers dieser Stärke, beste zuerst."""
74
+    board = board.copy()
75
+
76
+    def job(engine):
77
+        infos = engine.analyse(
78
+            board,
79
+            chess.engine.Limit(time=0.1),
80
+            multipv=count,
81
+            options={"Elo": int(elo), "Temperature": "0.0"},
82
+        )
83
+        moves = []
84
+        for info in sorted(infos, key=lambda i: i.get("multipv", 1)):
85
+            pv = info.get("pv")
86
+            if pv and pv[0] in board.legal_moves and pv[0] not in moves:
87
+                moves.append(pv[0])
88
+        return moves
89
+
90
+    return job
91
+
92
+
93
+def maia_move(board, elo, temperature):
94
+    """Job-Fabrik: ein Zug von Maia bei gegebener Spielstärke."""
95
+    board = board.copy()
96
+
97
+    def job(engine):
98
+        result = engine.play(
99
+            board,
100
+            chess.engine.Limit(time=0.1),
101
+            options={"Elo": int(elo), "Temperature": str(temperature)},
102
+        )
103
+        return result.move
104
+
105
+    return job

added schach/lichess.py +426 −0

@@ -0,0 +1,426 @@
1
+"""Lichess: Anmeldung (OAuth mit PKCE), Herausforderungen, Online-Partien, Rätsel, Partie-Import.
2
+
3
+Der Zugriffsschlüssel liegt im GNOME-Schlüsselbund (libsecret), nie in einer Datei.
4
+Alle Netzwerkzugriffe laufen in Hintergrund-Threads; Ergebnisse kommen per
5
+GLib.idle_add zurück in den GTK-Thread.
6
+"""
7
+
8
+import base64
9
+import hashlib
10
+import http.server
11
+import io
12
+import json
13
+import secrets
14
+import threading
15
+import urllib.parse
16
+
17
+import chess
18
+import chess.pgn
19
+import gi
20
+import requests
21
+
22
+gi.require_version("Secret", "1")
23
+from gi.repository import Gio, GLib, Secret  # noqa: E402
24
+
25
+HOST = "https://lichess.org"
26
+CLIENT_ID = "schach-gtk"
27
+USER_AGENT = "schach-gtk/1.0"  # Lichess sperrt User-Agents mit „python-requests“
28
+SCOPES = "board:play challenge:read challenge:write puzzle:read puzzle:write"
29
+
30
+SCHEMA = Secret.Schema.new(
31
+    "app.schach.Lichess", Secret.SchemaFlags.NONE, {"service": Secret.SchemaAttributeType.STRING}
32
+)
33
+ATTRS = {"service": "lichess"}
34
+
35
+# (Bezeichnung, Minuten, Inkrement) – None = Fernschach mit 1 Tag pro Zug
36
+TIME_CONTROLS = [
37
+    ("10 Minuten + 5 Sekunden", 10, 5),
38
+    ("15 Minuten + 10 Sekunden", 15, 10),
39
+    ("30 Minuten", 30, 0),
40
+    ("5 Minuten + 3 Sekunden (Blitz)", 5, 3),
41
+    ("Fernschach – 1 Tag pro Zug", None, 1),
42
+]
43
+DIFFICULTIES = [("Viel leichter", "easiest"), ("Leichter", "easier"), ("Normal", "normal"),
44
+                ("Schwerer", "harder"), ("Viel schwerer", "hardest")]
45
+
46
+
47
+def _idle(fn, *args):
48
+    if fn is not None:
49
+        GLib.idle_add(lambda: fn(*args) and False)
50
+
51
+
52
+def _background(work, callback):
53
+    """work() im Thread, dann callback(ergebnis, fehler) im GTK-Thread."""
54
+    def run():
55
+        try:
56
+            result, error = work(), None
57
+        except Exception as exc:  # noqa: BLE001 – Fehler gehen als Text an die Oberfläche
58
+            result, error = None, _message(exc)
59
+        _idle(callback, result, error)
60
+
61
+    threading.Thread(target=run, daemon=True).start()
62
+
63
+
64
+def _message(exc):
65
+    if isinstance(exc, requests.HTTPError) and exc.response is not None:
66
+        try:
67
+            body = exc.response.json()
68
+            text = body.get("error") or body.get("error_description") or body
69
+            if isinstance(text, dict):
70
+                text = "; ".join(f"{k}: {', '.join(v) if isinstance(v, list) else v}" for k, v in text.items())
71
+            return str(text)
72
+        except ValueError:
73
+            return f"HTTP {exc.response.status_code}"
74
+    if isinstance(exc, requests.ConnectionError):
75
+        return "keine Verbindung zu Lichess"
76
+    return str(exc)
77
+
78
+
79
+# --- Schlüsselbund ----------------------------------------------------------
80
+
81
+
82
+def load_token():
83
+    try:
84
+        return Secret.password_lookup_sync(SCHEMA, ATTRS, None)
85
+    except GLib.Error:
86
+        return None
87
+
88
+
89
+def store_token(token):
90
+    Secret.password_store_sync(SCHEMA, ATTRS, Secret.COLLECTION_DEFAULT, "Lichess (Schach)", token, None)
91
+
92
+
93
+def clear_token():
94
+    try:
95
+        Secret.password_clear_sync(SCHEMA, ATTRS, None)
96
+    except GLib.Error:
97
+        pass
98
+
99
+
100
+# --- Anmeldung --------------------------------------------------------------
101
+
102
+
103
+class Login:
104
+    """OAuth-PKCE: Browser öffnen, Rückleitung auf 127.0.0.1 abwarten, Code gegen Schlüssel tauschen."""
105
+
106
+    def __init__(self, on_done):
107
+        self.on_done = on_done  # callback(token oder None, fehler)
108
+        self.verifier = secrets.token_urlsafe(64)
109
+        self.state = secrets.token_urlsafe(16)
110
+        self.server = None
111
+
112
+    def start(self):
113
+        login = self
114
+
115
+        class Handler(http.server.BaseHTTPRequestHandler):
116
+            def do_GET(self):  # noqa: N802
117
+                query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
118
+                if not query:
119
+                    self.send_response(404)
120
+                    self.end_headers()
121
+                    return
122
+                ok = query.get("state", [""])[0] == login.state and "code" in query
123
+                self.send_response(200)
124
+                self.send_header("Content-Type", "text/html; charset=utf-8")
125
+                self.end_headers()
126
+                text = ("Fertig! Du kannst dieses Fenster schließen und zum Schachprogramm zurückkehren."
127
+                        if ok else "Anmeldung abgebrochen.")
128
+                self.wfile.write(
129
+                    f"<!doctype html><meta charset=utf-8><title>Schach</title>"
130
+                    f"<body style='font:1.3em sans-serif;text-align:center;margin-top:20vh'>{text}".encode()
131
+                )
132
+                threading.Thread(target=login._finish, args=(query, ok), daemon=True).start()
133
+
134
+            def log_message(self, *args):
135
+                pass
136
+
137
+        self.server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
138
+        threading.Thread(target=self.server.serve_forever, daemon=True).start()
139
+        challenge = base64.urlsafe_b64encode(hashlib.sha256(self.verifier.encode()).digest()).rstrip(b"=")
140
+        params = {
141
+            "response_type": "code",
142
+            "client_id": CLIENT_ID,
143
+            "redirect_uri": self.redirect_uri,
144
+            "code_challenge_method": "S256",
145
+            "code_challenge": challenge.decode(),
146
+            "scope": SCOPES,
147
+            "state": self.state,
148
+        }
149
+        url = f"{HOST}/oauth?{urllib.parse.urlencode(params)}"
150
+        Gio.AppInfo.launch_default_for_uri(url, None)
151
+        return url
152
+
153
+    @property
154
+    def redirect_uri(self):
155
+        return f"http://127.0.0.1:{self.server.server_address[1]}/"
156
+
157
+    def cancel(self):
158
+        if self.server is not None:
159
+            threading.Thread(target=self.server.shutdown, daemon=True).start()
160
+            self.server = None
161
+
162
+    def _finish(self, query, ok):
163
+        redirect = self.redirect_uri
164
+        self.cancel()
165
+        if not ok:
166
+            _idle(self.on_done, None, query.get("error_description", ["abgebrochen"])[0])
167
+            return
168
+        try:
169
+            resp = requests.post(f"{HOST}/api/token", data={
170
+                "grant_type": "authorization_code",
171
+                "code": query["code"][0],
172
+                "code_verifier": self.verifier,
173
+                "redirect_uri": redirect,
174
+                "client_id": CLIENT_ID,
175
+            }, headers={"User-Agent": USER_AGENT}, timeout=20)
176
+            resp.raise_for_status()
177
+            _idle(self.on_done, resp.json()["access_token"], None)
178
+        except Exception as exc:  # noqa: BLE001
179
+            _idle(self.on_done, None, _message(exc))
180
+
181
+
182
+# --- Schnittstelle ----------------------------------------------------------
183
+
184
+
185
+class Client:
186
+    def __init__(self, token=None):
187
+        self.token = token
188
+        self.session = requests.Session()
189
+        self.session.headers["User-Agent"] = USER_AGENT
190
+        if token:
191
+            self.session.headers["Authorization"] = f"Bearer {token}"
192
+
193
+    def _get(self, path, **kw):
194
+        resp = self.session.get(HOST + path, timeout=kw.pop("timeout", 20), **kw)
195
+        resp.raise_for_status()
196
+        return resp
197
+
198
+    def _post(self, path, **kw):
199
+        resp = self.session.post(HOST + path, timeout=kw.pop("timeout", 20), **kw)
200
+        resp.raise_for_status()
201
+        return resp
202
+
203
+    def _stream(self, method, path, on_line, stop, **kw):
204
+        """Liest NDJSON zeilenweise, bis der Server schließt oder stop gesetzt ist."""
205
+        with self.session.request(method, HOST + path, stream=True, timeout=(20, 60), **kw) as resp:
206
+            resp.raise_for_status()
207
+            for line in resp.iter_lines():
208
+                if stop.is_set():
209
+                    return
210
+                if line:
211
+                    on_line(json.loads(line))
212
+
213
+    # Konto
214
+    def account(self):
215
+        return self._get("/api/account").json()
216
+
217
+    def revoke(self):
218
+        self.session.delete(HOST + "/api/token", timeout=10)
219
+
220
+    # Herausforderungen
221
+    def challenge(self, username, minutes, increment, color, rated, on_created, stop):
222
+        """Fordert heraus und hält die Herausforderung offen, bis sie angenommen/abgelehnt wird.
223
+
224
+        on_created(id) kommt im GTK-Thread, sobald Lichess die Herausforderung angelegt hat;
225
+        Rückgabe: {"id": …, "done": "accepted" | "declined" | "canceled" | …}.
226
+        """
227
+        data = {"rated": "true" if rated else "false", "color": color, "keepAliveStream": "true"}
228
+        if minutes is None:
229
+            data["days"] = increment
230
+        else:
231
+            data["clock.limit"] = minutes * 60
232
+            data["clock.increment"] = increment
233
+        result = {}
234
+
235
+        def on_line(obj):
236
+            if "done" in obj:
237
+                result["done"] = obj["done"]
238
+            elif "id" in obj and "id" not in result:
239
+                result["id"] = obj["id"]
240
+                _idle(on_created, obj["id"])
241
+
242
+        self._stream("POST", f"/api/challenge/{urllib.parse.quote(username)}", on_line, stop, data=data)
243
+        return result
244
+
245
+    def accept(self, challenge_id):
246
+        self._post(f"/api/challenge/{challenge_id}/accept")
247
+
248
+    def decline(self, challenge_id, reason="generic"):
249
+        self._post(f"/api/challenge/{challenge_id}/decline", data={"reason": reason})
250
+
251
+    def cancel(self, challenge_id):
252
+        self._post(f"/api/challenge/{challenge_id}/cancel")
253
+
254
+    # Partie
255
+    def move(self, game_id, uci, offering_draw=False):
256
+        params = {"offeringDraw": "true"} if offering_draw else None
257
+        self._post(f"/api/board/game/{game_id}/move/{uci}", params=params)
258
+
259
+    def resign(self, game_id):
260
+        self._post(f"/api/board/game/{game_id}/resign")
261
+
262
+    def abort(self, game_id):
263
+        self._post(f"/api/board/game/{game_id}/abort")
264
+
265
+    def draw(self, game_id, accept):
266
+        self._post(f"/api/board/game/{game_id}/draw/{'yes' if accept else 'no'}")
267
+
268
+    # Rätsel
269
+    def next_puzzle(self, difficulty="normal"):
270
+        return self._get("/api/puzzle/next", params={"difficulty": difficulty}).json()
271
+
272
+    def report_puzzle(self, puzzle_id, win):
273
+        body = {"solutions": [{"id": puzzle_id, "win": bool(win), "rated": True}]}
274
+        data = self._post("/api/puzzle/batch/mix", json=body).json()
275
+        rounds = data.get("rounds") or []
276
+        return rounds[0].get("ratingDiff") if rounds else None
277
+
278
+    # Partien
279
+    def games(self, username, max_games=30):
280
+        resp = self._get(
281
+            f"/api/games/user/{urllib.parse.quote(username)}",
282
+            params={"max": max_games, "pgnInJson": "true", "opening": "true", "moves": "true"},
283
+            headers={"Accept": "application/x-ndjson"},
284
+            timeout=40,
285
+        )
286
+        return [json.loads(line) for line in resp.text.splitlines() if line.strip()]
287
+
288
+
289
+class EventStream:
290
+    """Ereignisse des Kontos (Herausforderungen, Partiebeginn …); verbindet sich bei Abbruch neu."""
291
+
292
+    def __init__(self, client, on_event):
293
+        self.client = client
294
+        self.on_event = on_event
295
+        self.stop = threading.Event()
296
+        threading.Thread(target=self._run, daemon=True).start()
297
+
298
+    def _run(self):
299
+        while not self.stop.is_set():
300
+            try:
301
+                self.client._stream("GET", "/api/stream/event", lambda e: _idle(self.on_event, e), self.stop)
302
+            except Exception:  # noqa: BLE001 – Netz weg: kurz warten, neu verbinden
303
+                pass
304
+            self.stop.wait(5)
305
+
306
+    def close(self):
307
+        self.stop.set()
308
+
309
+
310
+class GameStream:
311
+    """Verlauf einer laufenden Online-Partie (gameFull, dann gameState bei jedem Zug)."""
312
+
313
+    def __init__(self, client, game_id, on_message, on_error):
314
+        self.client = client
315
+        self.game_id = game_id
316
+        self.stop = threading.Event()
317
+        self.on_message = on_message
318
+        self.on_error = on_error
319
+        threading.Thread(target=self._run, daemon=True).start()
320
+
321
+    def _run(self):
322
+        attempts = 0
323
+        while not self.stop.is_set():
324
+            try:
325
+                self.client._stream(
326
+                    "GET", f"/api/board/game/stream/{self.game_id}",
327
+                    lambda m: _idle(self.on_message, m), self.stop,
328
+                )
329
+                return  # Server schließt den Strom, wenn die Partie vorbei ist
330
+            except Exception as exc:  # noqa: BLE001
331
+                attempts += 1
332
+                if attempts == 3:
333
+                    _idle(self.on_error, _message(exc))
334
+                self.stop.wait(min(10, 2 * attempts))
335
+
336
+    def close(self):
337
+        self.stop.set()
338
+
339
+
340
+# --- Hilfsfunktionen --------------------------------------------------------
341
+
342
+
343
+def board_from(initial_fen, moves):
344
+    board = chess.Board() if initial_fen in (None, "", "startpos") else chess.Board(initial_fen)
345
+    for uci in (moves or "").split():
346
+        board.push(board.parse_uci(uci))
347
+    return board
348
+
349
+
350
+def player_label(player):
351
+    """'Name (1500)' bzw. 'Lichess KI Stufe 3' aus einem gameFull-Spieler."""
352
+    if not player:
353
+        return "?"
354
+    if player.get("aiLevel"):
355
+        return f"Lichess-KI Stufe {player['aiLevel']}"
356
+    name = player.get("name") or player.get("id") or "?"
357
+    if player.get("title"):
358
+        name = f"{player['title']} {name}"
359
+    return f"{name} ({player['rating']})" if player.get("rating") else name
360
+
361
+
362
+STATUS_TEXT = {
363
+    "mate": "Schachmatt",
364
+    "resign": "Aufgabe",
365
+    "stalemate": "Patt",
366
+    "timeout": "Verbindung verloren",
367
+    "draw": "Remis",
368
+    "outoftime": "Zeit abgelaufen",
369
+    "aborted": "Partie abgebrochen",
370
+    "noStart": "Partie nicht begonnen",
371
+    "cheat": "Partie beendet",
372
+    "unknownFinish": "Partie beendet",
373
+    "insufficientMaterialClaim": "Remis – zu wenig Material",
374
+    "variantEnd": "Partie beendet",
375
+}
376
+
377
+
378
+def finish_text(status, winner, my_color):
379
+    """Text für das Partie-Ende aus Lichess-Status und Sieger (aus Sicht des Spielers)."""
380
+    reason = STATUS_TEXT.get(status, "Partie beendet")
381
+    if status in ("aborted", "noStart"):
382
+        return f"{reason}."
383
+    if winner is None:
384
+        return f"{reason} – Remis." if reason != "Remis" else "Remis."
385
+    won = (winner == "white") == (my_color == chess.WHITE)
386
+    if status == "resign":
387
+        reason = "Gegner hat aufgegeben" if won else "Aufgegeben"
388
+    elif status == "outoftime":
389
+        reason = "Zeit des Gegners abgelaufen" if won else "Zeit abgelaufen"
390
+    return f"{reason} – du hast gewonnen!" if won else f"{reason} – du hast verloren."
391
+
392
+
393
+def puzzle_from(data):
394
+    """(Brett vor dem letzten Gegnerzug, letzter Gegnerzug, Lösung als Züge, Infos)."""
395
+    game = chess.pgn.read_game(io.StringIO(data["game"]["pgn"]))
396
+    board = game.end().board()
397
+    last = board.pop()
398
+    solution = []
399
+    probe = board.copy()
400
+    probe.push(last)
401
+    for uci in data["puzzle"]["solution"]:
402
+        move = chess.Move.from_uci(uci)
403
+        solution.append(move)
404
+        probe.push(move)
405
+    return board, last, solution, data["puzzle"]
406
+
407
+
408
+def imported_game(item, username):
409
+    """GameState-Bausteine aus einem Eintrag des Partie-Exports."""
410
+    game = chess.pgn.read_game(io.StringIO(item["pgn"]))
411
+    board = game.end().board()
412
+    players = item.get("players", {})
413
+    white = (players.get("white", {}).get("user") or {}).get("name", "")
414
+    me_white = white.lower() == username.lower()
415
+    color = chess.WHITE if me_white else chess.BLACK
416
+    opp = players.get("black" if me_white else "white", {})
417
+    if opp.get("aiLevel"):
418
+        opponent = f"Lichess-KI Stufe {opp['aiLevel']}"
419
+    else:
420
+        opponent = (opp.get("user") or {}).get("name", "?")
421
+        if opp.get("rating"):
422
+            opponent += f" ({opp['rating']})"
423
+    text = None
424
+    if not board.is_game_over(claim_draw=True) and item.get("status") not in ("started", "created"):
425
+        text = finish_text(item.get("status"), item.get("winner"), color)
426
+    return board, color, opponent, text

added schach/movelist.py +182 −0

@@ -0,0 +1,182 @@
1
+"""Zugliste für die Analyse: ein Halbzug pro Zeile, dahinter ein Weiß/Schwarz-Balken."""
2
+
3
+import chess
4
+import gi
5
+
6
+gi.require_version("Gtk", "4.0")
7
+from gi.repository import Gtk  # noqa: E402
8
+
9
+from .board import BADGE  # noqa: E402
10
+
11
+CSS = b"""
12
+.movelist row { padding: 0; min-height: 0; }
13
+.move-pill {
14
+  background: alpha(white, 0.88);
15
+  color: #1e1e1e;
16
+  border-radius: 6px;
17
+  padding: 1px 7px;
18
+  font-feature-settings: "tnum";
19
+}
20
+.move-pill.selected-move { background: @accent_bg_color; color: @accent_fg_color; }
21
+.move-row-buttons button { min-height: 22px; min-width: 22px; padding: 1px; }
22
+"""
23
+
24
+
25
+def _hex(rgb):
26
+    return "#" + "".join(f"{int(c * 255):02x}" for c in rgb)
27
+
28
+
29
+class MoveList(Gtk.Box):
30
+    def __init__(self):
31
+        super().__init__(orientation=Gtk.Orientation.VERTICAL, width_request=240)
32
+        provider = Gtk.CssProvider()
33
+        provider.load_from_data(CSS)
34
+        Gtk.StyleContext.add_provider_for_display(
35
+            self.get_display(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
36
+        )
37
+
38
+        self.on_select = None  # callback(halbzug oder None)
39
+        self.on_copy = None  # callback(halbzug)
40
+        self.on_continue = None  # callback(halbzug)
41
+
42
+        header = Gtk.Box(spacing=6, margin_start=12, margin_end=6, margin_top=6, margin_bottom=6)
43
+        header.append(Gtk.Label(label="Partie", css_classes=["heading"], hexpand=True, xalign=0))
44
+        self.live_btn = Gtk.Button(
45
+            icon_name="go-bottom-symbolic", tooltip_text="Zur aktuellen Stellung", css_classes=["flat"]
46
+        )
47
+        self.live_btn.connect("clicked", lambda *_: self._select(None))
48
+        header.append(self.live_btn)
49
+        self.append(header)
50
+
51
+        self.listbox = Gtk.ListBox(selection_mode=Gtk.SelectionMode.SINGLE, css_classes=["movelist"])
52
+        self.listbox.connect("row-selected", self._on_row_selected)
53
+        self.scroller = Gtk.ScrolledWindow(vexpand=True, hscrollbar_policy=Gtk.PolicyType.NEVER)
54
+        self.scroller.set_child(self.listbox)
55
+        self.append(self.scroller)
56
+
57
+        self._rows = []
58
+        self._selected = None
59
+        self._signature = None
60
+        self._updating = False
61
+
62
+    # --- Aufbau ------------------------------------------------------------
63
+
64
+    def update(self, board, evals, symbols, selected):
65
+        """Baut die Liste neu, wenn sich Züge, Bewertungen oder Zeichen geändert haben."""
66
+        moves = list(board.move_stack)
67
+        signature = (tuple(moves), tuple(sorted(evals.items())), tuple(sorted(symbols.items())))
68
+        if signature != self._signature:
69
+            self._signature = signature
70
+            self._rebuild(board, moves, evals, symbols)
71
+        self._apply_selection(selected)
72
+
73
+    def _rebuild(self, board, moves, evals, symbols):
74
+        self._updating = True
75
+        self.listbox.remove_all()
76
+        self._rows = []
77
+        replay = board.root()
78
+        for ply, move in enumerate(moves):
79
+            number = replay.fullmove_number
80
+            prefix = f"{number}." if replay.turn == chess.WHITE else f"{number}…"
81
+            san = replay.san(move)
82
+            replay.push(move)
83
+            self._rows.append(self._make_row(ply, prefix, san, symbols.get(ply), evals.get(ply)))
84
+        for row, _ in self._rows:
85
+            self.listbox.append(row)
86
+        self._updating = False
87
+        if self._rows:
88
+            # nach dem Layout ans Ende scrollen
89
+            self.scroller.get_vadjustment().connect("changed", self._scroll_to_end_once)
90
+
91
+    def _scroll_to_end_once(self, adj):
92
+        adj.disconnect_by_func(self._scroll_to_end_once)
93
+        if self.listbox.get_selected_row() is None:
94
+            adj.set_value(adj.get_upper() - adj.get_page_size())
95
+
96
+    def _make_row(self, ply, prefix, san, symbol, white_pct):
97
+        bar = Gtk.DrawingArea(content_height=30, hexpand=True)
98
+        bar.set_draw_func(self._draw_bar, white_pct)
99
+
100
+        text = f"<span alpha='60%'>{prefix}</span> <b>{san}</b>"
101
+        if symbol:
102
+            text += f" <span foreground='{_hex(BADGE[symbol])}' weight='heavy'>{symbol}</span>"
103
+        pill = Gtk.Label(use_markup=True, label=text, css_classes=["move-pill"], valign=Gtk.Align.CENTER)
104
+
105
+        copy_btn = Gtk.Button(
106
+            icon_name="edit-copy-symbolic", tooltip_text="Stellung als FEN kopieren", css_classes=["osd", "circular"]
107
+        )
108
+        copy_btn.connect("clicked", lambda *_: self.on_copy and self.on_copy(ply))
109
+        play_btn = Gtk.Button(
110
+            icon_name="media-playback-start-symbolic", tooltip_text="Von hier weiterspielen",
111
+            css_classes=["osd", "circular"],
112
+        )
113
+        play_btn.connect("clicked", lambda *_: self.on_continue and self.on_continue(ply))
114
+        buttons = Gtk.Box(spacing=4, css_classes=["move-row-buttons"], valign=Gtk.Align.CENTER, visible=False)
115
+        buttons.append(copy_btn)
116
+        buttons.append(play_btn)
117
+
118
+        content = Gtk.Box(spacing=6, margin_start=8, margin_end=8)
119
+        content.append(pill)
120
+        content.append(Gtk.Box(hexpand=True))
121
+        content.append(buttons)
122
+
123
+        overlay = Gtk.Overlay(child=bar)
124
+        overlay.add_overlay(content)
125
+        row = Gtk.ListBoxRow(child=overlay)
126
+        row.ply = ply
127
+        row.pill = pill
128
+        # Knöpfe schon beim Darüberfahren zeigen
129
+        hover = Gtk.EventControllerMotion()
130
+        hover.connect("enter", lambda *_: buttons.set_visible(True))
131
+        hover.connect("leave", lambda *_: buttons.set_visible(ply == self._selected))
132
+        row.add_controller(hover)
133
+        return row, buttons
134
+
135
+    @staticmethod
136
+    def _draw_bar(area, cr, width, height, white_pct):
137
+        if white_pct is None:
138
+            cr.set_source_rgba(0.5, 0.5, 0.5, 0.12)
139
+            cr.rectangle(0, 0, width, height)
140
+            cr.fill()
141
+        else:
142
+            split = width * max(0.0, min(100.0, white_pct)) / 100.0
143
+            cr.set_source_rgb(0.95, 0.95, 0.93)
144
+            cr.rectangle(0, 0, split, height)
145
+            cr.fill()
146
+            cr.set_source_rgb(0.17, 0.17, 0.18)
147
+            cr.rectangle(split, 0, width - split, height)
148
+            cr.fill()
149
+        cr.set_source_rgba(0.5, 0.5, 0.5, 0.6)
150
+        cr.rectangle(width / 2 - 0.5, 0, 1, height)
151
+        cr.fill()
152
+
153
+    # --- Auswahl -----------------------------------------------------------
154
+
155
+    def _apply_selection(self, selected):
156
+        self._updating = True
157
+        if selected is None or selected >= len(self._rows):
158
+            self.listbox.unselect_all()
159
+        else:
160
+            self.listbox.select_row(self._rows[selected][0])
161
+        self._updating = False
162
+        self._show_buttons(selected)
163
+        self.live_btn.set_sensitive(selected is not None)
164
+
165
+    def _show_buttons(self, selected):
166
+        self._selected = selected
167
+        for ply, (row, buttons) in enumerate(self._rows):
168
+            buttons.set_visible(ply == selected)
169
+            if ply == selected:
170
+                row.pill.add_css_class("selected-move")
171
+            else:
172
+                row.pill.remove_css_class("selected-move")
173
+
174
+    def _on_row_selected(self, listbox, row):
175
+        if self._updating:
176
+            return
177
+        self._select(row.ply if row is not None else None)
178
+
179
+    def _select(self, ply):
180
+        # Die letzte Zeile ist die aktuelle Stellung – dort braucht es keinen Ansichtsmodus
181
+        if self.on_select:
182
+            self.on_select(ply)

added schach/online.py +450 −0

@@ -0,0 +1,450 @@
1
+"""Online-Partien über Lichess (Board-API) – als Mixin für das Hauptfenster.
2
+
3
+Fair Play: Solange eine Online-Partie läuft, gibt es keine Engine-Hilfe – kein
4
+Hinweis, keine Zeichen, keine Bewertungsbalken, kein Mitdenken von Stockfish.
5
+Nach dem Ende wird die Partie gespeichert und wie eine importierte Partie analysiert.
6
+"""
7
+
8
+import datetime
9
+import threading
10
+import time
11
+
12
+import chess
13
+import gi
14
+
15
+gi.require_version("Adw", "1")
16
+from gi.repository import Adw, GLib, Gtk  # noqa: E402
17
+
18
+from . import lichess, savegames  # noqa: E402
19
+
20
+
21
+def _short(label):
22
+    """'Name (1500)' → 'Name'."""
23
+    return label.split(" (")[0] if label else "Gegner"
24
+
25
+
26
+def time_control_text(tc):
27
+    if not tc:
28
+        return ""
29
+    kind = tc.get("type")
30
+    if kind == "clock":
31
+        minutes = tc.get("limit", 0) / 60
32
+        minutes = int(minutes) if minutes == int(minutes) else round(minutes, 1)
33
+        return f"{minutes}+{tc.get('increment', 0)}"
34
+    if kind == "correspondence":
35
+        days = tc.get("daysPerTurn", 1)
36
+        return f"{days} Tag pro Zug" if days == 1 else f"{days} Tage pro Zug"
37
+    return "ohne Uhr"
38
+
39
+
40
+class OnlineMixin:
41
+    def _online_init(self):
42
+        self.online_id = None
43
+        self.online_stream = None
44
+        self.online_full = None
45
+        self.online_clock = None  # {"white": ms, "black": ms, "at": monotonic}
46
+        self.online_tick = 0
47
+        self.online_moves = ""  # Züge laut Lichess (UCI), zum Zurücksetzen nach Fehlern
48
+        self.online_draw_offered = False
49
+        self.online_saved = False
50
+
51
+    # --- Start / Ende ------------------------------------------------------
52
+
53
+    def start_online(self, game_id):
54
+        self._leave_special()
55
+        self.mode = "online"
56
+        self.online_id = game_id
57
+        self.board = chess.Board()
58
+        self._reset_game_tables()
59
+        self.save_name = ""
60
+        self.save_path = ""
61
+        stream = lichess.GameStream(
62
+            self.get_application().lichess_client, game_id,
63
+            lambda msg: self._online_message(stream, msg),
64
+            lambda err: self._online_error(stream, err),
65
+        )
66
+        self.online_stream = stream
67
+        self._changed()
68
+        self._refresh()
69
+
70
+    def _online_leave(self):
71
+        if self.online_stream is not None:
72
+            self.online_stream.close()
73
+        if self.online_tick:
74
+            GLib.source_remove(self.online_tick)
75
+        self._online_init()
76
+        self.view.names = self.view.clocks = self.view.clock_running = None
77
+
78
+    def _online_running(self):
79
+        return self.mode == "online" and self.final_text is None
80
+
81
+    # --- Nachrichten von Lichess -------------------------------------------
82
+
83
+    def _online_message(self, stream, msg):
84
+        if stream is not self.online_stream:
85
+            return
86
+        kind = msg.get("type")
87
+        if kind == "gameFull":
88
+            self.online_full = msg
89
+            me = (self.get_application().lichess_user or {}).get("id", "")
90
+            self.human = chess.WHITE if msg.get("white", {}).get("id") == me else chess.BLACK
91
+            other = msg["black"] if self.human == chess.WHITE else msg["white"]
92
+            self.opponent = lichess.player_label(other)
93
+            self.view.names = {
94
+                chess.WHITE: lichess.player_label(msg.get("white")),
95
+                chess.BLACK: lichess.player_label(msg.get("black")),
96
+            }
97
+            self.view.flipped = self.human == chess.BLACK
98
+            self.board = lichess.board_from(msg.get("initialFen"), "")
99
+            self._online_state(msg["state"])
100
+        elif kind == "gameState":
101
+            if self.online_full is not None:
102
+                self._online_state(msg)
103
+        elif kind == "opponentGone":
104
+            if msg.get("gone"):
105
+                secs = msg.get("claimWinInSeconds")
106
+                extra = f" – in {secs} s kannst du den Sieg auf lichess.org beanspruchen" if secs else ""
107
+                self.toasts.add_toast(Adw.Toast(title=f"{_short(self.opponent)} ist nicht mehr da{extra}"))
108
+
109
+    def _online_error(self, stream, error):
110
+        if stream is self.online_stream:
111
+            self.toasts.add_toast(Adw.Toast(title=f"Lichess: {error} – versuche es weiter …"))
112
+
113
+    def _online_state(self, st):
114
+        moves = st.get("moves", "")
115
+        self.online_moves = moves
116
+        server = lichess.board_from(self.online_full.get("initialFen"), moves)
117
+        mine = list(self.board.move_stack)
118
+        theirs = list(server.move_stack)
119
+        if mine != theirs:
120
+            if len(theirs) == len(mine) + 1 and theirs[:-1] == mine:
121
+                move = theirs[-1]
122
+                self.view.animate_move(self.board, move)
123
+                self.board.push(move)
124
+            else:
125
+                self.board = server
126
+            self.browse_ply = None
127
+            self._changed()
128
+
129
+        if self.online_full.get("clock"):
130
+            self.online_clock = {"white": st.get("wtime", 0), "black": st.get("btime", 0), "at": time.monotonic()}
131
+            if not self.online_tick:
132
+                self.online_tick = GLib.timeout_add(100, self._online_tick_clock)
133
+            self._online_tick_clock()
134
+
135
+        flag = st.get("bdraw") if self.human == chess.WHITE else st.get("wdraw")
136
+        if flag and not self.online_draw_offered:
137
+            self.online_draw_offered = True
138
+            toast = Adw.Toast(title=f"{_short(self.opponent)} bietet Remis an", button_label="Annehmen", timeout=0)
139
+            toast.connect("button-clicked", lambda *_: self._online_call(
140
+                lambda c, g: c.draw(g, True)))
141
+            self.toasts.add_toast(toast)
142
+        elif not flag:
143
+            self.online_draw_offered = False
144
+
145
+        status = st.get("status")
146
+        if status not in ("created", "started"):
147
+            self.final_text = lichess.finish_text(status, st.get("winner"), self.human)
148
+            self._online_finished()
149
+        self._refresh()
150
+
151
+    def _online_tick_clock(self):
152
+        clock = self.online_clock
153
+        if clock is None:
154
+            self.online_tick = 0
155
+            return False
156
+        running = self.final_text is None and len(self.board.move_stack) >= 2
157
+        elapsed = (time.monotonic() - clock["at"]) * 1000 if running else 0
158
+        turn = self.board.turn
159
+        self.view.clocks = {
160
+            chess.WHITE: clock["white"] - (elapsed if turn == chess.WHITE else 0),
161
+            chess.BLACK: clock["black"] - (elapsed if turn == chess.BLACK else 0),
162
+        }
163
+        self.view.clock_running = turn if running else None
164
+        self.view.queue_draw()
165
+        if self.final_text is not None:
166
+            self.online_tick = 0
167
+            return False
168
+        return True
169
+
170
+    def _online_finished(self):
171
+        if self.online_stream is not None:
172
+            self.online_stream.close()
173
+            self.online_stream = None
174
+        self.view.clock_running = None
175
+        if self.online_saved or not self.board.move_stack:
176
+            return
177
+        self.online_saved = True
178
+        self.mode = "review"  # ab jetzt darf Stockfish analysieren
179
+        name = f"Lichess gegen {_short(self.opponent)} ({datetime.datetime.now():%d.%m. %H:%M})"
180
+        state = self.state()
181
+        try:
182
+            savegames.save(state, name)
183
+            self.save_name, self.save_path = state.name, state.path
184
+            self.toasts.add_toast(Adw.Toast(title=f"Partie als „{name}“ gespeichert", timeout=4))
185
+        except OSError as exc:
186
+            self.toasts.add_toast(Adw.Toast(title=f"Speichern fehlgeschlagen: {exc}"))
187
+        self._analyze_review()
188
+
189
+    # --- Eigene Aktionen ---------------------------------------------------
190
+
191
+    def _online_play(self, move):
192
+        self.view.animate_move(self.board, move)
193
+        self.board.push(move)
194
+        self.browse_ply = None
195
+        self._changed()
196
+        self._refresh()
197
+        self._online_call(lambda c, g: c.move(g, move.uci()), on_error=self._online_resync)
198
+
199
+    def _online_resync(self):
200
+        self.board = lichess.board_from(self.online_full.get("initialFen"), self.online_moves)
201
+        self._changed()
202
+        self._refresh()
203
+
204
+    def _online_call(self, fn, on_error=None):
205
+        client, game_id = self.get_application().lichess_client, self.online_id
206
+
207
+        def done(_result, error):
208
+            if error:
209
+                self.toasts.add_toast(Adw.Toast(title=f"Lichess: {error}"))
210
+                if on_error:
211
+                    on_error()
212
+
213
+        lichess._background(lambda: fn(client, game_id), done)
214
+
215
+    def _offer_draw(self, *_):
216
+        if not self._online_running():
217
+            return
218
+        self._online_call(lambda c, g: c.draw(g, True))
219
+        self.toasts.add_toast(Adw.Toast(title="Remis angeboten", timeout=2))
220
+
221
+    def _resign(self, *_):
222
+        if not self._online_running():
223
+            return
224
+        early = len(self.board.move_stack) < 2
225
+        dialog = Adw.AlertDialog(
226
+            heading="Partie abbrechen?" if early else "Aufgeben?",
227
+            body="Noch hat niemand richtig gezogen – die Partie wird ohne Wertung abgebrochen." if early
228
+            else "Die Partie ist dann verloren.",
229
+        )
230
+        dialog.add_response("cancel", "Weiterspielen")
231
+        dialog.add_response("yes", "Abbrechen" if early else "Aufgeben")
232
+        dialog.set_response_appearance("yes", Adw.ResponseAppearance.DESTRUCTIVE)
233
+        dialog.set_close_response("cancel")
234
+
235
+        def on_response(_d, response):
236
+            if response == "yes":
237
+                self._online_call((lambda c, g: c.abort(g)) if early else (lambda c, g: c.resign(g)))
238
+
239
+        dialog.connect("response", on_response)
240
+        dialog.present(self)
241
+
242
+    def _confirm_close_online(self):
243
+        dialog = Adw.AlertDialog(
244
+            heading="Fenster schließen?",
245
+            body="Die Partie läuft auf Lichess weiter – deine Uhr auch. "
246
+                 "Beim nächsten Start kannst du sie wieder öffnen.",
247
+        )
248
+        dialog.add_response("cancel", "Weiterspielen")
249
+        dialog.add_response("close", "Schließen")
250
+        dialog.set_response_appearance("close", Adw.ResponseAppearance.DESTRUCTIVE)
251
+        dialog.set_close_response("cancel")
252
+
253
+        def on_response(_d, response):
254
+            if response == "close":
255
+                self._online_leave()
256
+                self.close()
257
+
258
+        dialog.connect("response", on_response)
259
+        dialog.present(self)
260
+
261
+    # --- Herausforderungen -------------------------------------------------
262
+
263
+    def _challenge_dialog(self, *_):
264
+        app = self.get_application()
265
+        if app.lichess_user is None:
266
+            return
267
+        dialog = Adw.AlertDialog(heading="Freund herausfordern",
268
+                                 body="Die Partie läuft über Lichess – ohne Hinweise und Bewertung.")
269
+        dialog.add_response("cancel", "Abbrechen")
270
+        dialog.add_response("send", "Herausfordern")
271
+        dialog.set_response_appearance("send", Adw.ResponseAppearance.SUGGESTED)
272
+        dialog.set_default_response("send")
273
+        dialog.set_close_response("cancel")
274
+
275
+        group = Adw.PreferencesGroup(width_request=340)
276
+        name_row = Adw.EntryRow(title="Lichess-Name", text=self.settings.get("friend", ""))
277
+        group.add(name_row)
278
+        tc_row = Adw.ComboRow(title="Bedenkzeit", model=Gtk.StringList.new([t[0] for t in lichess.TIME_CONTROLS]))
279
+        tc_row.set_selected(min(self.settings.get("time_control", 0), len(lichess.TIME_CONTROLS) - 1))
280
+        group.add(tc_row)
281
+        colors = ["random", "white", "black"]
282
+        color_row = Adw.ComboRow(title="Deine Farbe", model=Gtk.StringList.new(["Zufällig", "Weiß", "Schwarz"]))
283
+        group.add(color_row)
284
+        rated_row = Adw.SwitchRow(title="Gewertet", subtitle="Verändert die Lichess-Wertung")
285
+        group.add(rated_row)
286
+        dialog.set_extra_child(group)
287
+
288
+        def on_response(_d, response):
289
+            name = name_row.get_text().strip()
290
+            if response != "send" or not name:
291
+                return
292
+            self.settings.update(friend=name, time_control=tc_row.get_selected())
293
+            from .app import save_settings
294
+            save_settings(self.settings)
295
+            _label, minutes, inc = lichess.TIME_CONTROLS[tc_row.get_selected()]
296
+            self._send_challenge(name, minutes, inc, colors[color_row.get_selected()], rated_row.get_active())
297
+
298
+        dialog.connect("response", on_response)
299
+        dialog.present(self)
300
+        name_row.grab_focus()
301
+
302
+    def _send_challenge(self, name, minutes, inc, color, rated):
303
+        app = self.get_application()
304
+        stop = threading.Event()
305
+        created = {}
306
+        waiting = Adw.AlertDialog(
307
+            heading=f"Warte auf {name} …",
308
+            body=f"{name} sieht die Herausforderung auf lichess.org. Sobald sie angenommen ist, "
309
+                 "beginnt die Partie hier.",
310
+        )
311
+        waiting.add_response("withdraw", "Zurückziehen")
312
+        waiting.set_close_response("withdraw")
313
+        spinner = Adw.Spinner(height_request=32)
314
+        waiting.set_extra_child(spinner)
315
+
316
+        def on_created(challenge_id):
317
+            created["id"] = challenge_id
318
+            app.expected_games.add(challenge_id)  # Partie-ID = Herausforderungs-ID
319
+
320
+        def on_withdraw(_d, _response):
321
+            if stop.is_set():
322
+                return
323
+            stop.set()
324
+            if "id" in created:
325
+                lichess._background(lambda: app.lichess_client.cancel(created["id"]), lambda *_: None)
326
+
327
+        def on_done(result, error):
328
+            if not stop.is_set():
329
+                stop.set()
330
+                waiting.force_close()
331
+            if error:
332
+                self.toasts.add_toast(Adw.Toast(title=f"Herausforderung fehlgeschlagen: {error}"))
333
+                return
334
+            done = (result or {}).get("done")
335
+            if done == "declined":
336
+                self.toasts.add_toast(Adw.Toast(title=f"{name} hat abgelehnt"))
337
+            elif done not in ("accepted", "canceled", None):
338
+                self.toasts.add_toast(Adw.Toast(title=f"Herausforderung beendet ({done})"))
339
+
340
+        waiting.connect("response", on_withdraw)
341
+        waiting.present(self)
342
+        lichess._background(
343
+            lambda: app.lichess_client.challenge(name, minutes, inc, color, rated, on_created, stop), on_done
344
+        )
345
+
346
+    def incoming_challenge(self, challenge):
347
+        """Dialog für eine Herausforderung an uns; gibt den Dialog zurück (zum Schließen bei Rücknahme)."""
348
+        app = self.get_application()
349
+        who = lichess.player_label(challenge.get("challenger"))
350
+        tc = time_control_text(challenge.get("timeControl"))
351
+        rated = "gewertet" if challenge.get("rated") else "ungewertet"
352
+        their = challenge.get("color", "random")
353
+        mine = {"white": "Schwarz", "black": "Weiß"}.get(their, "zufällige Farbe")
354
+        variant = (challenge.get("variant") or {}).get("key", "standard")
355
+        speed = challenge.get("speed")
356
+        supported = variant == "standard" and speed not in ("bullet", "ultraBullet")
357
+
358
+        dialog = Adw.AlertDialog(heading=f"{who} fordert dich heraus")
359
+        if supported:
360
+            dialog.set_body(f"{tc}, {rated} – du spielst {mine}.")
361
+            dialog.add_response("decline", "Ablehnen")
362
+            dialog.add_response("accept", "Annehmen")
363
+            dialog.set_response_appearance("accept", Adw.ResponseAppearance.SUGGESTED)
364
+            dialog.set_default_response("accept")
365
+        else:
366
+            name = (challenge.get("variant") or {}).get("name", variant)
367
+            dialog.set_body(f"{name}, {tc}: Das geht hier leider nicht – nur normales Schach ohne Bullet. "
368
+                            "Du kannst sie auf lichess.org annehmen.")
369
+            dialog.add_response("later", "Ignorieren")
370
+            dialog.add_response("decline", "Ablehnen")
371
+        dialog.set_close_response("later" if not supported else "decline")
372
+        challenge_id = challenge["id"]
373
+
374
+        def on_response(_d, response):
375
+            app.challenge_dialogs.pop(challenge_id, None)
376
+            client = app.lichess_client
377
+            if client is None:
378
+                return
379
+            if response == "accept":
380
+                app.expected_games.add(challenge_id)
381
+                lichess._background(lambda: client.accept(challenge_id), self._toast_error)
382
+            elif response == "decline":
383
+                lichess._background(lambda: client.decline(challenge_id), self._toast_error)
384
+
385
+        dialog.connect("response", on_response)
386
+        dialog.present(self)
387
+        return dialog
388
+
389
+    def _toast_error(self, _result, error):
390
+        if error:
391
+            self.toasts.add_toast(Adw.Toast(title=f"Lichess: {error}"))
392
+
393
+    # --- Eigene Partien importieren ----------------------------------------
394
+
395
+    def _lichess_games_dialog(self, *_):
396
+        app = self.get_application()
397
+        user = app.lichess_user
398
+        if user is None:
399
+            return
400
+        dialog = Adw.Dialog(title="Meine Lichess-Partien", content_width=520, content_height=560)
401
+        toolbar = Adw.ToolbarView()
402
+        toolbar.add_top_bar(Adw.HeaderBar())
403
+        toolbar.set_content(Adw.Spinner())
404
+        dialog.set_child(toolbar)
405
+        dialog.present(self)
406
+
407
+        def on_games(items, error):
408
+            if error:
409
+                toolbar.set_content(Adw.StatusPage(icon_name="network-error-symbolic",
410
+                                                   title="Partien nicht geladen", description=error))
411
+                return
412
+            if not items:
413
+                toolbar.set_content(Adw.StatusPage(icon_name="document-open-symbolic",
414
+                                                   title="Noch keine Partien auf Lichess"))
415
+                return
416
+            page = Adw.PreferencesPage()
417
+            group = Adw.PreferencesGroup(description="Anklicken öffnet die Partie mit Zugliste und Analyse.")
418
+            page.add(group)
419
+            for item in items:
420
+                try:
421
+                    board, color, opponent, end = lichess.imported_game(item, user["username"])
422
+                except (ValueError, KeyError, AttributeError):
423
+                    continue
424
+                winner = item.get("winner")
425
+                if item.get("status") in ("aborted", "noStart"):
426
+                    result = "Abgebrochen"
427
+                elif winner is None:
428
+                    result = "Remis" if item.get("status") not in ("started", "created") else "Läuft"
429
+                else:
430
+                    result = "Gewonnen" if (winner == "white") == (color == chess.WHITE) else "Verloren"
431
+                when = datetime.datetime.fromtimestamp(item.get("createdAt", 0) / 1000)
432
+                opening = (item.get("opening") or {}).get("name", "")
433
+                speed = {"bullet": "Bullet", "blitz": "Blitz", "rapid": "Schnellschach", "classical": "Klassisch",
434
+                         "correspondence": "Fernschach"}.get(item.get("speed"), item.get("speed", ""))
435
+                row = Adw.ActionRow(
436
+                    title=f"gegen {opponent} – {result}",
437
+                    subtitle=" · ".join(x for x in (f"{when:%d.%m.%Y}", speed, opening) if x),
438
+                    use_markup=False, activatable=True,
439
+                )
440
+                row.add_suffix(Gtk.Image(icon_name="go-next-symbolic"))
441
+                state = savegames.GameState(
442
+                    board=board, human=color, elo=0, mode="review", opponent=opponent,
443
+                    final_text=end or "", name=f"Lichess gegen {_short(opponent)} ({when:%d.%m.%Y})",
444
+                )
445
+                row.connect("activated", lambda _r, st=state: (dialog.close(), self._open_state(st)))
446
+                group.add(row)
447
+            toolbar.set_content(page)
448
+
449
+        client = app.lichess_client
450
+        lichess._background(lambda: client.games(user["username"]), on_games)

added schach/puzzles.py +170 −0

@@ -0,0 +1,170 @@
1
+"""Lichess-Rätsel – als Mixin für das Hauptfenster.
2
+
3
+Angemeldet wird jedes Ergebnis gewertet an Lichess gemeldet, sodass sich die
4
+Rätselwertung ändert. Wie auf Lichess zählt ein Rätsel nur als gelöst, wenn
5
+kein falscher Zug gespielt und kein Hinweis benutzt wurde.
6
+"""
7
+
8
+import chess
9
+import gi
10
+
11
+gi.require_version("Adw", "1")
12
+from gi.repository import Adw, GLib  # noqa: E402
13
+
14
+from . import lichess  # noqa: E402
15
+
16
+OPPONENT_DELAY_MS = 550
17
+TAKE_BACK_MS = 900
18
+
19
+
20
+class PuzzleMixin:
21
+    def start_puzzle(self, *_):
22
+        self._leave_special()
23
+        self.mode = "puzzle"
24
+        self.puzzle = None
25
+        self.board = chess.Board()
26
+        self._reset_game_tables()
27
+        self.save_name = ""
28
+        self.save_path = ""
29
+        self._changed()
30
+        self._refresh()
31
+        gen = self.gen
32
+        app = self.get_application()
33
+        client = app.lichess_client or lichess.Client()
34
+        difficulty = self.settings.get("puzzle_difficulty", "normal")
35
+        lichess._background(lambda: client.next_puzzle(difficulty), lambda d, e: self._puzzle_loaded(gen, d, e))
36
+
37
+    def _puzzle_loaded(self, gen, data, error):
38
+        if gen != self.gen or self.mode != "puzzle":
39
+            return
40
+        if error:
41
+            self.final_text = f"Rätsel konnte nicht geladen werden: {error}"
42
+            self._refresh()
43
+            return
44
+        try:
45
+            board, last, solution, info = lichess.puzzle_from(data)
46
+        except (ValueError, KeyError, AttributeError) as exc:
47
+            self.final_text = f"Rätsel unlesbar: {exc}"
48
+            self._refresh()
49
+            return
50
+        self.board = board
51
+        self.human = not board.turn  # der letzte Zug ist vom Gegner, danach ist man selbst dran
52
+        self.view.flipped = self.human == chess.BLACK
53
+        self.puzzle = {
54
+            "id": info["id"], "rating": info.get("rating"), "themes": info.get("themes", []),
55
+            "solution": solution, "index": 0, "failed": False, "done": False,
56
+            "reported": False, "rating_diff": None,
57
+        }
58
+        self._changed()
59
+        self._refresh()
60
+        GLib.timeout_add(OPPONENT_DELAY_MS, self._puzzle_reply, self.gen, last, False)
61
+
62
+    def _puzzle_reply(self, gen, move, counts=True):
63
+        """Gegnerzug (der Ausgangszug oder eine Antwort aus der Lösung)."""
64
+        if gen != self.gen or self.mode != "puzzle" or move not in self.board.legal_moves:
65
+            return False
66
+        self.view.animate_move(self.board, move)
67
+        self.board.push(move)
68
+        if counts:
69
+            self.puzzle["index"] += 1
70
+        self._changed()
71
+        self._refresh()
72
+        return False
73
+
74
+    def _puzzle_play(self, move):
75
+        p = self.puzzle
76
+        if p is None or p["done"]:
77
+            return
78
+        solution = p["solution"]
79
+        expected = solution[p["index"]]
80
+        ply = len(self.board.move_stack)
81
+        self.view.animate_move(self.board, move)
82
+        self.board.push(move)
83
+        self.browse_ply = None
84
+        # Wie auf Lichess: Ein anderes Matt im letzten Zug gilt auch
85
+        correct = move == expected or self.board.is_checkmate()
86
+        if correct:
87
+            p["index"] += 1
88
+            self._changed()
89
+            if p["index"] >= len(solution) or self.board.is_checkmate():
90
+                self._puzzle_done()
91
+            else:
92
+                reply = solution[p["index"]]
93
+                GLib.timeout_add(OPPONENT_DELAY_MS, self._puzzle_reply, self.gen, reply)
94
+            self._refresh()
95
+            return
96
+        self._puzzle_fail()
97
+        self.symbols[ply] = "?"
98
+        self.badge_ply = ply
99
+        self._changed()
100
+        self._refresh()
101
+        self.toasts.add_toast(Adw.Toast(title="Das ist nicht der Zug – versuch es nochmal", timeout=2))
102
+        GLib.timeout_add(TAKE_BACK_MS, self._puzzle_take_back, self.gen, ply)
103
+
104
+    def _puzzle_take_back(self, gen, ply):
105
+        if gen != self.gen or len(self.board.move_stack) != ply + 1:
106
+            return False
107
+        self.board.pop()
108
+        self.symbols.pop(ply, None)
109
+        self.badge_ply = None
110
+        self._changed()
111
+        self._refresh()
112
+        return False
113
+
114
+    def _puzzle_hint(self):
115
+        p = self.puzzle
116
+        if p is None or p["done"]:
117
+            return
118
+        self._puzzle_fail()
119
+        self.hint_move = p["solution"][p["index"]]
120
+
121
+    def _puzzle_fail(self):
122
+        p = self.puzzle
123
+        if not p["failed"]:
124
+            p["failed"] = True
125
+            self._puzzle_report(False)  # Lichess wertet beim ersten Fehler, nicht erst am Ende
126
+
127
+    def _puzzle_done(self):
128
+        p = self.puzzle
129
+        p["done"] = True
130
+        self.final_text = "Gelöst!" if not p["failed"] else "Geschafft – zählt diesmal aber nicht als gelöst."
131
+        self._puzzle_report(True)
132
+
133
+    def _puzzle_report(self, win):
134
+        p = self.puzzle
135
+        app = self.get_application()
136
+        if p["reported"] or app.lichess_client is None:
137
+            return
138
+        p["reported"] = True
139
+        client, puzzle_id = app.lichess_client, p["id"]
140
+
141
+        def done(diff, error):
142
+            if error:
143
+                self.toasts.add_toast(Adw.Toast(title=f"Ergebnis nicht an Lichess gemeldet: {error}"))
144
+                return
145
+            if self.puzzle is p and diff is not None:
146
+                p["rating_diff"] = diff
147
+                self._refresh()
148
+
149
+        lichess._background(lambda: client.report_puzzle(puzzle_id, win), done)
150
+
151
+    def _puzzle_leave(self):
152
+        self.puzzle = None
153
+
154
+    def _puzzle_subtitle(self):
155
+        p = self.puzzle
156
+        if p is None:
157
+            return "Rätsel wird geladen …" if self.final_text is None else "Rätsel"
158
+        side = "Weiß" if self.human == chess.WHITE else "Schwarz"
159
+        parts = [f"Rätsel {p['rating']}" if p.get("rating") else "Rätsel"]
160
+        if p["rating_diff"] is not None:
161
+            parts.append(f"deine Rätselwertung {p['rating_diff']:+d}")
162
+        elif not p["done"]:
163
+            parts.append(f"{side} am Zug")
164
+        return " · ".join(parts)
165
+
166
+    def _set_puzzle_difficulty(self, action, value):
167
+        action.set_state(value)
168
+        self.settings["puzzle_difficulty"] = value.get_string()
169
+        from .app import save_settings
170
+        save_settings(self.settings)

added schach/savegames.py +191 −0

@@ -0,0 +1,191 @@
1
+"""Spielstände: PGN-Dateien mit Namen, plus automatischer Spielstand der letzten Partie.
2
+
3
+Zeichen (!, ?? …) stehen als NAGs im PGN, die Balkenwerte der Zugliste als
4
+Kommentar ``[%wp 52.3]`` (Gewinnchance Weiß in Prozent). So bleibt jede Datei
5
+ein gewöhnliches PGN, das auch andere Programme öffnen können.
6
+"""
7
+
8
+import dataclasses
9
+import datetime
10
+import io
11
+import os
12
+import re
13
+
14
+import chess
15
+import chess.pgn
16
+from gi.repository import GLib
17
+
18
+from .annotate import NAG
19
+
20
+DATA_DIR = os.path.join(GLib.get_user_data_dir(), "schach")
21
+SAVE_DIR = os.path.join(DATA_DIR, "spielstaende")
22
+AUTOSAVE_PATH = os.path.join(DATA_DIR, "letzte-partie.pgn")
23
+
24
+SYMBOL_FOR_NAG = {nag: symbol for symbol, nag in NAG.items()}
25
+WP_RE = re.compile(r"\[%wp ([0-9.]+)\]")
26
+
27
+
28
+@dataclasses.dataclass
29
+class GameState:
30
+    board: chess.Board
31
+    human: bool
32
+    elo: int
33
+    symbols: dict = dataclasses.field(default_factory=dict)
34
+    evals: dict = dataclasses.field(default_factory=dict)
35
+    name: str = ""
36
+    path: str = ""  # Datei, aus der geladen bzw. in die zuletzt gespeichert wurde
37
+    mode: str = "maia"  # "maia" = gegen Maia weiterspielbar, "review" = nur ansehen (Lichess-Partie)
38
+    opponent: str = ""  # Gegnername, wenn nicht Maia
39
+    final_text: str = ""  # Partie-Ende, das nicht am Brett ablesbar ist (Aufgabe, Zeit …)
40
+
41
+    def truncated(self, ply):
42
+        """Kopie bis einschließlich Halbzug ``ply`` (für Abzweigungen)."""
43
+        board = self.board.copy()
44
+        while len(board.move_stack) > ply + 1:
45
+            board.pop()
46
+        n = len(board.move_stack)
47
+        return GameState(
48
+            board=board,
49
+            human=self.human,
50
+            elo=self.elo,
51
+            symbols={p: s for p, s in self.symbols.items() if p < n},
52
+            evals={p: e for p, e in self.evals.items() if p < n},
53
+        )
54
+
55
+
56
+def to_pgn(state):
57
+    game = chess.pgn.Game()
58
+    now = datetime.datetime.now()
59
+    game.headers["Event"] = state.name or "Partie gegen Maia-3"
60
+    game.headers["Date"] = now.strftime("%Y.%m.%d")
61
+    maia = state.opponent or f"Maia-3 ({state.elo})"
62
+    game.headers["White"], game.headers["Black"] = (
63
+        ("Spieler", maia) if state.human == chess.WHITE else (maia, "Spieler")
64
+    )
65
+    game.headers["Result"] = state.board.result(claim_draw=True)
66
+    if state.final_text and game.headers["Result"] == "*":
67
+        game.headers["Termination"] = state.final_text
68
+    game.headers["SchachHuman"] = "white" if state.human == chess.WHITE else "black"
69
+    game.headers["SchachElo"] = str(state.elo)
70
+    game.headers["SchachSaved"] = now.isoformat(timespec="seconds")
71
+    if state.mode != "maia":
72
+        game.headers["SchachMode"] = state.mode
73
+    if state.opponent:
74
+        game.headers["SchachOpponent"] = state.opponent
75
+    if state.final_text:
76
+        game.headers["SchachEnd"] = state.final_text
77
+    root = state.board.root()
78
+    if root.fen() != chess.STARTING_FEN:
79
+        game.setup(root)
80
+    node = game
81
+    for ply, move in enumerate(state.board.move_stack):
82
+        node = node.add_variation(move)
83
+        if ply in state.symbols:
84
+            node.nags.add(NAG[state.symbols[ply]])
85
+        if ply in state.evals:
86
+            node.comment = f"[%wp {state.evals[ply]:.1f}]"
87
+    return str(game) + "\n"
88
+
89
+
90
+def from_pgn(text, path=""):
91
+    game = chess.pgn.read_game(io.StringIO(text))
92
+    if game is None:
93
+        raise ValueError("Keine Partie in der Datei")
94
+    headers = game.headers
95
+    board = game.board()
96
+    symbols, evals = {}, {}
97
+    for ply, node in enumerate(game.mainline()):
98
+        board.push(node.move)
99
+        for nag in node.nags:
100
+            if nag in SYMBOL_FOR_NAG:
101
+                symbols[ply] = SYMBOL_FOR_NAG[nag]
102
+        match = WP_RE.search(node.comment or "")
103
+        if match:
104
+            evals[ply] = float(match.group(1))
105
+    human = chess.BLACK if headers.get("SchachHuman") == "black" else chess.WHITE
106
+    try:
107
+        elo = int(headers.get("SchachElo", "1200"))
108
+    except ValueError:
109
+        elo = 1200
110
+    name = headers.get("Event", "")
111
+    return GameState(
112
+        board, human, elo, symbols, evals, name=name, path=path,
113
+        mode=headers.get("SchachMode", "maia"),
114
+        opponent=headers.get("SchachOpponent", ""),
115
+        final_text=headers.get("SchachEnd", ""),
116
+    )
117
+
118
+
119
+def _write(path, text):
120
+    os.makedirs(os.path.dirname(path), exist_ok=True)
121
+    tmp = path + ".tmp"
122
+    with open(tmp, "w") as fh:
123
+        fh.write(text)
124
+    os.replace(tmp, path)
125
+
126
+
127
+def _slug(name):
128
+    slug = re.sub(r"[^\w-]+", "-", name.lower()).strip("-")
129
+    return slug[:40] or "spielstand"
130
+
131
+
132
+def save(state, name):
133
+    """Speichert unter ``name``; derselbe Name im selben Fenster überschreibt den alten Stand."""
134
+    state.name = name
135
+    if state.path and os.path.dirname(state.path) == SAVE_DIR and os.path.exists(state.path):
136
+        path = state.path
137
+        try:
138
+            if from_pgn(open(path).read()).name != name:
139
+                path = ""
140
+        except (OSError, ValueError):
141
+            path = ""
142
+    else:
143
+        path = ""
144
+    if not path:
145
+        stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
146
+        path = os.path.join(SAVE_DIR, f"{stamp}-{_slug(name)}.pgn")
147
+    _write(path, to_pgn(state))
148
+    state.path = path
149
+    return path
150
+
151
+
152
+def list_saves():
153
+    """[(Pfad, GameState, gespeichert-am)] – neueste zuerst."""
154
+    result = []
155
+    if not os.path.isdir(SAVE_DIR):
156
+        return result
157
+    for filename in os.listdir(SAVE_DIR):
158
+        if not filename.endswith(".pgn"):
159
+            continue
160
+        path = os.path.join(SAVE_DIR, filename)
161
+        try:
162
+            with open(path) as fh:
163
+                text = fh.read()
164
+            state = from_pgn(text, path)
165
+            saved = re.search(r'\[SchachSaved "([^"]+)"\]', text)
166
+            when = datetime.datetime.fromisoformat(saved.group(1)) if saved else (
167
+                datetime.datetime.fromtimestamp(os.path.getmtime(path))
168
+            )
169
+        except (OSError, ValueError):
170
+            continue
171
+        result.append((path, state, when))
172
+    result.sort(key=lambda item: item[2], reverse=True)
173
+    return result
174
+
175
+
176
+def delete(path):
177
+    if os.path.dirname(os.path.abspath(path)) == SAVE_DIR:
178
+        os.remove(path)
179
+
180
+
181
+def write_autosave(state):
182
+    autosave = dataclasses.replace(state, path="")
183
+    _write(AUTOSAVE_PATH, to_pgn(autosave))
184
+
185
+
186
+def read_autosave():
187
+    try:
188
+        with open(AUTOSAVE_PATH) as fh:
189
+            return from_pgn(fh.read())
190
+    except (OSError, ValueError):
191
+        return None