-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchessapp.py
2845 lines (2199 loc) · 95.3 KB
/
chessapp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Sturddlefish Chess App (c) 2021, 2022, 2023, 2024 Cristian Vlasceanu
-------------------------------------------------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-------------------------------------------------------------------------
"""
import os
os.environ['KIVY_CLIPBOARD']='sdl2' # workaround nspaste throwing index errors on macos
os.environ['KIVY_NO_CONFIG']='1'
from kivy.config import Config
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'multisample', 16)
Config.set('graphics', 'window_state', 'hidden')
import ctypes
import math
import random
import re
from collections import defaultdict
from copy import copy
from datetime import datetime
from functools import partial
from io import StringIO
from os import path
import chess.pgn
from kivy.app import App
from kivy.animation import Animation
from kivy.clock import Clock, mainthread
from kivy.core.clipboard import Clipboard
from kivy.core.text import Label as CoreLabel
from kivy.core.window import Keyboard, Window
from kivy.utils import get_color_from_hex, platform
if Window.dpi == 0:
# https://github.com/kivy/kivy/issues/7874
Window.dpi = ctypes.windll.user32.GetDpiForSystem() if platform == 'win' else 96
from kivy.graphics import *
from kivy.graphics.tesselator import Tesselator
from kivy.logger import Logger, LOG_LEVELS
from kivy.metrics import *
from kivy.properties import *
from kivy.storage.dictstore import DictStore
from kivy.uix.actionbar import ActionPrevious
from kivy.uix.bubble import Bubble
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.modalview import ModalView
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput
import sturddle_chess_engine as chess_engine
from assistant import Assistant
from center import CenterControl
from engine import Engine
from movestree import MovesTree
from msgbox import MessageBox, ModalBox
from normalize import substitute_chess_moves, capitalize_chess_coords
from opening import ECO
from puzzleview import PuzzleCollection, PuzzleView, puzzle_description
from speech import nlp, stt, tts, voice
try:
from android.runnable import run_on_ui_thread
from jnius import autoclass
android_api_version = autoclass('android.os.Build$VERSION')
PythonActivity = autoclass('org.kivy.android.PythonActivity')
Intent = autoclass('android.content.Intent')
Logger.info(f'API: level={android_api_version.SDK_INT}')
except ImportError:
def run_on_ui_thread(func):
def wrapper(*args):
Logger.debug(f'{func.__name__} called on non android platform')
return wrapper
def hlink(link):
return f'[color=2fa7d4][ref={link}[/color]' if link else ''
CHESS = 'https://python-chess.readthedocs.io/en/latest/]python-chess'
CODE = 'https://github.com/cristivlas/sturddle-chess-app]github.com/sturddle-chess-app'
KIVY = 'https://kivy.org/]Kivy'
ABOUT = f"""Powered by the [b]Sturddle Chess Engine[/b],
{hlink(KIVY)}, and {hlink(CHESS)} {Engine.chess_ver()}.
{hlink(CODE)}
(C) 2022 - 2024 Cristian Vlasceanu
Sturddlefish image by Alexandra Nicolae
"""
GAME = 'game'
IMAGE = 'images/splash.png'
VIEW_MODE = ' Mode [color=A0A0A0]/[/color][b][color=FFA045] Engine Off[/color][/b]'
WIDTH = 600
HEIGHT = 900
# Modified Font Awesome codes for chess pieces
PIECE_CODES = [
[0, '\uF468', '\uF469', '\uF46A', '\uF46B', '\uF46C', '\uF46D'],
[0, '\uF470', '\uF471', '\uF472', '\uF473', '\uF474', '\uF475'],
]
COLOR_NAMES = ['Black', 'White']
CONFIRM_QUIT = 'Save game and exit application'
SWIPE_DIST = cm(1.5)
CHESS_QUOTES = [
'In chess, as in life, opportunity strikes but once.',
'A bad plan is better than none at all. Especially if it confuses your opponent.',
'Chess is life in miniature. And yes, it’s okay to be a drama king or queen.',
'Every chess master was once a beginner... and probably a coffee addict.',
'Checkmate happens only when you stop thinking about pizza.',
'In life, as in chess, forethought wins. So does coffee.',
'Not all artists are chess players, but all chess players are artists. With really cool hats.',
'The beauty of a move lies not in its appearance but in the thought behind it. And sometimes, in the bluff.',
'To avoid traps, keep your eye on the board, not just the pieces. Or the snacks.',
'Life is like a game of chess, changing with each move. And with each snack break.',
'A sacrifice in chess brings its own rewards. Like more room on the board for your snacks.',
'Chess demands total concentration and a love for the game. And for snacks.',
'One bad move nullifies forty good ones. But who’s counting?',
'The essence of chess is thinking about what chess is. And why we’re not playing checkers.',
'In chess, as in life, patience is a virtue. And so is a good poker face.',
'The king is a fighting piece. But sometimes, it just wants to chill in the corner.',
'Chess is a sea in which a gnat may drink and an elephant may bathe. And where your strategy drowns.',
'Remember, in chess, the queen rules. Just like in real life.',
'In chess, the best move is always the one you remember after the game.',
'Chess: Turning introverts into strategists since forever.'
]
def is_mobile():
return platform in ['ios', 'android']
if not is_mobile():
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
from pynput import keyboard # For handling headset/media button events
def bold(text):
return f'[b]{text}[/b]'
def screen_scale():
scale = 1.0 # TODO: Other platforms?
if platform == 'win':
scale = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100
return scale
class Arrow:
'''
Draw an arrow on the chess board.
'''
def __init__(self, **kwargs):
from_xy = kwargs.get('from_xy', (0, 0))
to_xy = kwargs.get('to_xy', (100, 100))
width = kwargs.get('width', 10)
head_size = max(1.05 * width, kwargs.get('head_size', 2 * width))
outline_width = kwargs.get('outline_width', 1)
color = kwargs.get('color', [0,1,0,1])
outline_color = kwargs.get('outline_color', [0,0,0,1])
length = math.dist(from_xy, to_xy)
points = [-width/4, 0, -width/2, length-head_size, -head_size/2, length-head_size,
0, length, head_size/2, length-head_size, width/2, length-head_size, width/4, 0 ]
tess = Tesselator()
tess.add_contour(points)
tess.tesselate()
PushMatrix()
Translate(*from_xy)
angle = -math.degrees(math.atan2(to_xy[0]-from_xy[0], to_xy[1]-from_xy[1]))
Rotate(angle=angle, origin=(0,0))
Color(*color)
for v, i in tess.meshes:
Mesh(vertices=v, indices=i, mode='triangle_fan')
Color(*outline_color)
SmoothLine(points=points, width=outline_width, joint='miter')
PopMatrix()
class RotatingActionPrevious(ActionPrevious):
angle = NumericProperty(0)
spinner_icon = StringProperty('images/spinner.png') # Path to spinner icon
def __init__(self, **kwargs):
super(RotatingActionPrevious, self).__init__(**kwargs)
self.anim = None
def start_rotation(self):
if not self.anim:
self.anim = Animation(angle=360, duration=1) + Animation(angle=0, duration=0)
self.anim.repeat = True
self.anim.start(self)
self.original_icon = self.app_icon
self.app_icon = self.spinner_icon # Change to spinner icon
def stop_rotation(self):
if self.anim:
self.anim.cancel(self)
self.anim = None
self.angle = 0
self.app_icon = self.original_icon # Change back to original icon
def on_angle(self, instance, value):
canvas = self.ids.app_icon_image.canvas
center = self.ids.app_icon_image.center
canvas.before.clear()
with canvas.before:
PushMatrix()
Rotate(angle=value, axis=(0, 0, 1), origin=center)
canvas.after.clear()
with canvas.after:
PopMatrix()
class AppSettings(GridLayout):
pass
class AdvancedSettings(GridLayout):
pass
class ExtraSettings(GridLayout):
pass
class EditControls(GridLayout):
pass
class FontScalingLabel(Label):
font_resize = NumericProperty(0)
max_font_size = sp(18)
auto_wrap = True
default_background = get_color_from_hex('202020')
def __init__(self, **kwargs):
super(FontScalingLabel, self).__init__(**kwargs)
self.margin = -2, 0
self.bind(size=self.scale_font)
def scale_font(self, *_):
if not self.text:
return
self.font_size = self.max_font_size
self.texture_update()
while any([self.texture_size[i] > self.size[i] for i in [0,1]]):
if self.font_size <= 1:
break
self.font_size -= dp(1)
self.texture_update()
self.font_resize = self.font_size
class Menu(DropDown):
pass
class Notepad(TextInput):
'''
Custom widget for displaying game transcripts and PGN comments.
'''
lined = BooleanProperty(False)
def __init__(self, **kwargs):
super(Notepad, self).__init__(**kwargs)
def on_lined(*_):
if self.lined:
self.bind(size=self._redraw)
self.padding[0] = 60
self.bind(lined=on_lined)
self.bind(size=self._resize)
self._height_adjusted = False
self._update_graphics_ev.cancel()
def get_bounding_box(self, width, lines_max=500):
'''
Compute the minimum height required to display the entire
text (without scrolling) inside of a box of a given width.
'''
extents = CoreLabel(
font_name=self.font_name,
font_size=self.font_size
).get_cached_extents()
padding = self.padding[0] + self.padding[2]
num_lines = 1
line = ''
words = self.text.split()
while words and num_lines < lines_max:
w = words.pop(0)
line += w + ' '
if extents(line)[0] + padding >= width:
num_lines += 1
line = ''
# put the word back in the list
words.insert(0, w)
if line:
if num_lines == 1:
width = extents(line)[0] + padding
num_lines += 1
text_height = extents(self.text)[1]
return (
width,
num_lines * (text_height + self.line_spacing)
+ self.padding[1]
+ self.padding[3]
)
def _redraw(self, *_):
self.canvas.before.clear()
with self.canvas.before:
Color(*self.background_color)
Rectangle(pos=self.pos, size=self.size)
y = self.y + self.padding[1]
Color(0,1,1,0.5)
while y < self.y + self.size[1]:
Line(points=[self.x, y, self.x + self.size[0], y])
y += self.line_height + self.line_spacing
# vertical red lines
Color(1,0,0,0.7)
x = self.x + self.padding[0] - 10
Line(points=[x, self.y, x, self.y + self.size[1]])
Line(points=[x + 3, self.y, x + 3, self.y + self.size[1]])
Color(0,0,0,1)
def _resize(self, *_):
if 100 < self.height < self.minimum_height:
self.height = self.minimum_height
self.size_hint_y = None
self._height_adjusted = True
def _update_graphics(self, *args):
if self._height_adjusted:
super()._update_graphics(*args)
class ScrolledPad(ScrollView):
'''
Scrolled Notebook.
'''
text = StringProperty()
font_name = StringProperty('Roboto-Italic')
font_size = NumericProperty(12)
readonly = BooleanProperty(True)
use_bubble = BooleanProperty(True)
background_color = ColorProperty()
lined = BooleanProperty(False)
def __init__(self, **kwargs):
super(ScrolledPad, self).__init__(**kwargs)
self.bind(on_scroll_start=lambda *_:self.ids.text._hide_cut_copy_paste())
class PolyglotChooser(GridLayout):
'''
Widget for selecting the opening book file.
'''
_filechooser = ObjectProperty(None)
selection = StringProperty('')
def __init__(self, **kwargs):
super(PolyglotChooser, self).__init__(**kwargs)
self.dir = 1
def dismiss(self):
self._popup.dismiss()
def _on_selection(self, _, sel):
if sel:
filename = sel[0]
if len(filename) > 40:
basename = path.basename(filename)
filename = filename[:36 - len(basename)] + '.../' + basename
self._selected.text = 'Current book: ' + filename
def switch_data_dir(self, btn):
self.dir ^= 1
def view_files(path, *_):
try:
btn.text = btn._app
self._filechooser.filter_dirs = False
self._filechooser.rootpath = path
except:
Logger.exception('view_files')
if self.dir:
self._filechooser.rootpath = '.'
self._filechooser.filter_dirs = True
btn.text = btn._sys
else:
if platform == 'android':
Environment = autoclass('android.os.Environment')
data_path = Environment.getExternalStorageDirectory().getPath()
from android.permissions import Permission, request_permissions
request_permissions(
[Permission.READ_EXTERNAL_STORAGE],
callback=partial(view_files, data_path))
else:
view_files('..')
class Root(GridLayout):
pass
class no_update_callbacks:
def __init__(self, engine):
self._engine = engine
self._update = engine.update_callback
self._move = None
def __no_update(self, move):
# record last move, but don't update the UI
self._move = move
def __enter__(self):
self._engine.update_callback = self.__no_update
return self
def __exit__(self, *_):
# restore update callback
self._engine.update_callback = self._update
# ...and perform one single update
self._update(self._move)
def _to_clipboard(text):
try:
return Clipboard.copy(text)
except Exception as e:
Logger.warning(f'_to_clipboard: {e}')
def _from_clipboard():
try:
return Clipboard.paste()
except Exception as e:
Logger.warning(f'_from_clipboard: {e}')
class ChessApp(App):
icon = 'images/logo_50.png'
font_awesome = 'fonts/Font Awesome 5 Free Solid.ttf'
engine_busy = ObjectProperty(bool) # used in settings.kv
_use_voice = ObjectProperty(bool)
# Node-per-second limits by "skill-level". The engine does not
# implement strength levels, the application layer injects delays
# and "fuzzes" the evaluation function (EVAL_FUZZ is an engine
# parameter which introduces random errors in the closed interval
# [-EVAL_FUZZ, EVAL_FUZZ]
# ----------------------------------------------------------------
NPS_LEVEL = [ 1500, 2500, 4000, 6000, 10000, 15000, 20000, 25000 ]
FUZZ = [ 90, 75, 55, 40, 25, 20, 15, 10 ]
MAX_DEPTH = [ 3, 4, 5, 7, 9, 11, 13, 15 ]
# ----------------------------------------------------------------
MAX_DIFFICULTY = len(NPS_LEVEL) + 1
use_intent_recognizer = BooleanProperty(False)
def __init__(self, **kwargs):
super().__init__(**kwargs)
chess.pgn.LOGGER.setLevel(50)
datafile = 'game.dat' if is_mobile() else os.path.join(os.path.expanduser('~'), '.chess')
self.in_game_animation = False # animation in progress?
self.assistant = Assistant(self)
self.openai_api_key = os.environ.get('OPENAI_API_KEY', '')
self.modal = None
self.store = DictStore(datafile)
self.eco = None
self.engine = Engine(self.update, self.update_move, Logger.debug)
self.engine.depth_callback = self.update_hash_usage
self.engine.promotion_callback = self.get_promotion_type
self.engine.search_complete_callback = self.on_search_complete
self.engine.search_callback = self.search_callback
# ------------------------------------------------------------
# wrap engine search
self._search_move = self.engine.search_move
self.engine.search_move = self.search_move
# ------------------------------------------------------------
self.use_eco(True) # use Encyclopedia of Chess Openings
self.moves_record = MovesTree()
self.voice_input = voice.Input(self)
self.auto_voice = False
self._use_voice = False
self._study_mode = False
self.edit = None
self.puzzle = None
self.puzzle_play = False
self.selected_puzzle = 0
self.comments = False
self._time_limit = [ 1, 3, 5, 10, 15, 30, 60, 180, 300, 600, 900 ]
self.limit = 1
self.delay = 0
self.nps = 0 # nodes per second
self.show_nps = False
self.show_hash = False
self.difficulty_level = 0
self.set_difficulty_level(1)
self.touch = None # for swipe left / right
self.analysis_time = 3 # in seconds, see analyze
Logger.setLevel(LOG_LEVELS[os.environ.get('KIVY_LOG_LEVEL', 'info')])
self.use_assistant = False # "Remote Assistant"
self.use_intent_recognizer = True # "Local Assistant"
def about(self, *_):
TITLE = f'Sturddle Chess (Engine {chess_engine.version()})'
self.message_box(TITLE, ABOUT, Image(source=IMAGE), auto_wrap=False)
self.modal.popup.size_hint=(.9, .35)
self.modal.popup.message_max_font_size = sp(14)
@mainthread
def analyze(self, *, assist=None, full=False):
if self.is_analyzing():
return
# Save current settings
book = self.engine.book
search_callback = self.engine.search_callback
depth_limit = self.engine.depth_limit
time_limit = self.engine.time_limit
engine_paused = self.engine.worker.is_paused()
@mainthread
def update_on_main_thread():
if engine_paused:
self.engine.pause()
else:
# The engine may be paused by the user touching / clicking
# on the main button (which shows a spinner during analysis).
self.engine.resume(auto_move=False)
self.update_button_states()
self.update_status()
def on_analysis_complete(search, color, move, score):
try:
self.on_search_complete(search, color, move, score, analysis=True, assist=assist, full=full)
finally:
self.engine.book = book
self.engine.depth_limit = depth_limit
self.engine.time_limit = time_limit
self.engine.search_callback = search_callback
self.engine.search_complete_callback = self.on_search_complete
update_on_main_thread()
self.engine.book = None # Force move search, do not use opening book
self.engine.depth_limit = 100
self.engine.time_limit = self.analysis_time
self.engine.search_callback = None
self.engine.search_complete_callback = on_analysis_complete
if engine_paused:
self.engine.resume(auto_move=False)
self.update_button_states()
self.engine.worker.send_message(partial(self.search_move, True))
def _animate(self, from_move=0, callback=lambda *_:None):
self.set_study_mode(True) # Pause the engine.
while self.can_undo() and self.game_len() > from_move:
self.undo_move()
def redo(*_):
assert self.engine.worker.is_paused()
self.in_game_animation = True
if tts.is_speaking():
Clock.schedule_once(redo, 0.5)
else:
if self.can_redo():
self.redo_move(in_animation=True)
Clock.schedule_once(redo)
else:
callback()
self.in_game_animation = False
self.update_button_states()
redo()
def _auto_open(self):
'''
Play (for both sides) a sequence of moves from the opening book.
'''
self._opening = self.opening.text
study_mode = self.study_mode
title = 'Opening Book' # message box title
def show_opening_name():
if self._opening:
Clock.schedule_once(
lambda *_: self.message_box(
title,
f'[color=40FFFF][u]{self._opening}[/u][/color]'
), 1.0)
self.set_study_mode(study_mode)
def callback():
self.identify_opening()
if self.opening.text:
self._opening = self.opening.text
current = self.game_len()
with no_update_callbacks(self.engine):
if self.engine.auto_open(callback):
self._animate(from_move=current, callback=show_opening_name)
else:
# This should not happen, because engine.can_auto_open() should return False when
# the opening book has no suitable moves for the given position, and the UI button
# should be disabled -- but just in case...
Clock.schedule_once(
lambda *_: self.message_box(title, 'No suitable moves were found.'), 1)
self.update_button_states()
def auto_open(self):
self.confirm(
'Lookup matching sequence in the opening book, and play moves for both sides',
self._auto_open)
"""
https://stackoverflow.com/questions/43159532/hiding-navigation-bar-on-android
https://developer.android.com/training/system-ui/immersive
"""
@run_on_ui_thread
def _android_hide_menu(self, restore=False):
if android_api_version.SDK_INT >= 19:
View = autoclass('android.view.View')
decorView = PythonActivity.mActivity.getWindow().getDecorView()
flags = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY \
| View.SYSTEM_UI_FLAG_FULLSCREEN \
| View.SYSTEM_UI_FLAG_LOW_PROFILE \
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
decorView.setSystemUiVisibility(flags)
Logger.debug("_android_hide_menu: ok")
def backup(self, move_count=1):
Logger.debug(f'backup: {move_count}, game_len={self.game_len()}')
study_mode = self.study_mode
if not study_mode:
move_count *= 2 # use full moves in play mode, half-moves in study
if move_count > self.game_len():
self.speak('Going back to start of the game...')
self.set_study_mode(True)
while move_count > 0 and self.can_undo():
move_count -= 1
self.undo_move()
self.set_study_mode(study_mode)
def set_window_size(self, *_):
if not is_mobile():
try:
import pyautogui # raises error if .Xauthority not found
_, h = pyautogui.size()
scale = screen_scale()
ratio = min(1.0, h / 1200 / scale)
Window.size = WIDTH * ratio, HEIGHT * ratio
except:
Window.size = (WIDTH, HEIGHT)
def setup_listeners(self, _):
"""Use pynput keyboard to get events from headset button."""
self.listener = keyboard.Listener(on_press=self.on_keypress)
self.listener.start()
def build(self):
Window.bind(on_keyboard=self.on_keyboard)
Window.bind(on_request_close=self.on_quit)
Window.bind(on_restore=lambda *_: self._android_hide_menu(True))
Window.bind(on_touch_down=self.on_touch_down)
Window.bind(on_touch_up=self.on_touch_up)
Window.bind(top=self.on_position_change, left=self.on_position_change)
Window.show()
Window._update_density_and_dpi()
root = Root()
for id, widget in root.ids.items():
setattr(self, id, widget)
self.board_widget.set_model(self.engine.board)
# custom fonts and codes for the promotion bubble
self.board_widget.set_piece_codes(PIECE_CODES, self.font_awesome, close='\uF410')
self.board_widget._copy = self._copy
self.board_widget._paste = self._paste
self.board_widget._hint = self._hint
self.board_widget._variation_hints = self.variation_hints
self.board_widget.bind(on_user_move=self.on_user_move)
self.board_widget.bind(on_drag=self.on_drag)
self.board_widget.bind(on_drag_end=self.on_drag_end)
self.board_widget.bind(on_square=self.on_square)
self.build_menu()
self.load()
# Position the widgets that show hash usage and nodes-per-seconds
def on_size(w, *_):
y = (w.height - w.board_size - self.status.height - self.action.height) / 2 + self.nps_label.height
self.nps_label.y = y - self.nps_label.height - dp(5)
self.hash_label.y = y - self.hash_label.height - dp(5)
self.board_widget.bind(size=on_size)
def sync_font_sizes(*_):
self.hash_label.font_size = self.nps_label.font_size
self.hash_label.texture_update()
self.nps_label.bind(font_resize=sync_font_sizes)
if not is_mobile():
Clock.schedule_once(self.setup_listeners, 0)
return root
def build_menu(self):
self.menu = Menu()
for id, widget in self.menu.ids.items():
setattr(self, id, widget)
# Ensure the engine is not running while executing menu actions
def cancel_move_if_busy(*_):
if self.engine.busy:
self.undo_move()
for btn in self.menu.children[0].children:
btn.bind(on_release=cancel_move_if_busy)
def can_auto_open(self):
return (
self.engine.can_auto_open()
and not bool(self.edit)
and not self.in_game_animation
and not self.is_analyzing()
)
def can_edit(self):
return (
not self.engine.busy
and not self.in_game_animation
and not self.is_analyzing()
)
def can_pause_play(self):
return (
not bool(self.edit)
and not self.in_game_animation
and not self.is_analyzing()
)
def can_switch(self):
''' Can switch sides (i.e. flip the board)? '''
return (
self.engine.can_switch()
and not bool(self.edit) # The editor has its own button for this.
and not self.is_analyzing()
)
def can_use_assistant(self):
# return (
# self.openai_api_key
# and self.assistant.enabled
# and not self.assistant.busy
# and self.eco # required for looking up openings
# )
return self.eco and not self.assistant.busy
def can_undo(self):
if self.is_analyzing():
return False
if self.study_mode:
return not self.puzzle and bool(self.engine.board.move_stack)
return self.engine.can_undo()
def can_redo(self):
if self.is_analyzing():
return False
if self.study_mode:
return not self.puzzle and self.moves_record.current_move
return self.engine.can_redo()
def can_restart(self):
return (
not self.engine.busy
and self.game_in_progress() # otherwise there's nothing to restart
and not self.in_game_animation
)
def chat_assist(self, user_input=None):
if self.can_use_assistant():
if not user_input:
user_input = self.voice_input.get_user_input()
if user_input:
return self.assistant.call(user_input)
def describe_move(self, move, spell_digits=False):
'''
Return a description of the move in English
'''
return nlp.describe_move(
self.engine.board,
move,
announce_check=True,
announce_capture=True,
spell_digits=spell_digits)
def draw_arrow(self, from_square, to_square, color=(0.25, 0.75, 0, 0.45)):
half_square = self.board_widget.square_size / 2
def square_center_xy(square):
return [i + half_square for i in self.board_widget.screen_coords(square % 8, square // 8)]
return Arrow(
from_xy=square_center_xy(from_square),
to_xy = square_center_xy(to_square),
color=color,
width=self.board_widget.square_size / 7.5,
outline_color=(1, 1, 0.5, 0.75),
outline_width=2)
def exit(self, *_):
self.confirm(CONFIRM_QUIT, self.stop)
@staticmethod
def find_unsupported_pieces(board, support=False):
# Initialize lists for black (index 0) and white (index 1) pieces
undefended = [[], []]
for square in chess.SQUARES:
piece = board.piece_at(square)
# Skip kings and pieces that are defended by their own color.
if not piece or piece.piece_type == chess.KING or board.is_attacked_by(piece.color, square):
continue
# Attacked by the opposite color?
is_attacked = board.is_attacked_by(not piece.color, square)
if is_attacked and support != is_attacked:
undefended[piece.color].append((
chess.PIECE_NAMES[piece.piece_type],
chess.square_name(square).upper())
)
return undefended
def format_opening(self, opening_name):
opening = opening_name
if not opening.endswith(' Opening'):
opening += ' Opening'
opening_name = f'[i][ref=https://www.google.com/search?q={opening}][b]{opening_name}[/b][/ref][/i]'
self.opening.text = opening_name
def identify_opening(self):
'''
Use ECO categorization to match moves played so far against classic openings
'''
if not self.puzzle:
if self.eco is None:
self.opening.text = ''
else:
if opening := self.eco.lookup(self.board_widget.model):
self.format_opening(opening['name'])
else:
self.opening.text = ''
def is_analyzing(self):
return self.engine.search_complete_callback != self.on_search_complete
@staticmethod
def has_modal_views():
return Window.children and isinstance(Window.children[0], ModalView)
def load_game_study(self, store):
label = store.get('study_name', None)
game = chess.pgn.read_game(StringIO(store.get('named_study', '')))
if game:
fen = game.headers.get('FEN', None)
self.moves_record = MovesTree.import_pgn(game, label, fen=fen)
self.update_moves_record(pop_last_move=True)
def load(self):
'''
Load app state (including game in progress, if any)
'''
if self.store.exists(GAME):
store = self.store.get(GAME)
self.engine.opponent = store.get('play_as', True)
self.engine.setup(store.get('moves', []), store.get('fen', None))
if not self.engine.opponent:
self.board_widget.rotate()
self.set_study_mode(store.get('study_mode', False))
self.engine.use_opening_book(store.get('use_opening_book', True))
self.engine.polyglot_file=store.get('polyglot', self.engine.polyglot_file)
self.engine.variable_strategy = store.get('var_strategy', True)
self.use_eco(store.get('use_eco', True))
self.engine.set_notation(store.get('notation', 'san'))
self.load_game_study(store)
self.limit = store.get('limit', self._limit)
self.engine.algorithm = store.get('algo', Engine.Algorithm.MTDF)
self.engine.clear_hash_on_move = store.get('clear_hash', False)
self.comments = store.get('comments', False)
self.cpu_cores = store.get('cores', 1)
# Set difficulty after cores, as it resets cores to 1 if level < MAX
self.set_difficulty_level(int(store.get('level', 1)))
# Show hash table usage and nodes-per-second
self.show_hash = store.get('show_hash', False)
self.show_nps = store.get('show_nps', False)
# Remember last puzzle