-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.py
1597 lines (1394 loc) · 54.6 KB
/
run.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
from __future__ import print_function
import sys
import argparse
import random
DEBUG = False
TO_EXE = getattr(sys, "frozen", False)
XRESOLUTION = 1920
import time as tt
from datetime import datetime, timedelta
from select import *
from socket import *
import chess.pgn
import chess
import os
import pickle
import pygame
import stockfish
import subprocess
import logging
import logging.handlers
import Queue
from constants import CERTABO_SAVE_PATH, CERTABO_DATA_PATH
logging.basicConfig(level="DEBUG", format="%(asctime)s:%(module)s:%(message)s")
logger = logging.getLogger()
filehandler = logging.handlers.TimedRotatingFileHandler(
os.path.join(CERTABO_DATA_PATH, "certabo.log"), backupCount=12
)
logger.addHandler(filehandler)
import codes
from utils import port2number, port2udp, find_port, get_engine_list, coords_in
from publish import Publisher
stockfish.TO_EXE = TO_EXE
parser = argparse.ArgumentParser()
parser.add_argument("--port")
parser.add_argument("--publish", help="URL to publish data")
parser.add_argument("--game-id", help="Game ID")
parser.add_argument("--game-key", help="Game key")
parser.add_argument("--robust", help="Robust", action="store_true")
args = parser.parse_args()
if args.port is None:
portname = find_port()
else:
portname = args.port
port = port2number(portname)
board_listen_port, gui_listen_port = port2udp(port)
SEND_SOCKET = ("127.0.0.1", board_listen_port) # send to
LISTEN_SOCKET = ("127.0.0.1", gui_listen_port) # listen to
pgn_queue = None
publisher = None
DEFAULT_ENGINES = ("stockfish", "houdini", "komodo", "fire", "lczero")
def make_publisher():
global pgn_queue, publisher
if publisher:
publisher.stop()
pgn_queue = Queue.Queue()
publisher = Publisher(args.publish, pgn_queue, args.game_id, args.game_key)
publisher.start()
return pgn_queue, publisher
def publish():
global pgn_queue
pgn_queue.put(generate_pgn())
for d in (CERTABO_SAVE_PATH, CERTABO_DATA_PATH):
try:
os.makedirs(d)
except OSError:
pass
def txt(s, x, y, color):
img = font.render(s, 22, color) # string, blend, color, background color
pos = x * x_multiplier, y * y_multiplier
scr.blit(img, pos)
def txt_large(s, x, y, color):
img = font_large.render(s, 22, color) # string, blend, color, background color
pos = x * x_multiplier, y * y_multiplier
scr.blit(img, pos)
def do_poweroff(proc):
if args.publish:
publisher.stop()
subprocess.call(["taskkill", "/F", "/T", "/PID", str(proc.pid)])
pygame.display.quit()
pygame.quit()
sys.exit()
f = open("screen.ini", "rb")
try:
XRESOLUTION = int(f.readline().split(" #")[0])
logging.info("%s", XRESOLUTION)
if XRESOLUTION == 1380:
XRESOLUTION = 1366
except:
logging.info("Cannot read resolution from screen.ini")
if XRESOLUTION != 480 and XRESOLUTION != 1366 and XRESOLUTION != 1920:
logging.info("Wrong value xscreensize.ini = %s, setting 1366", XRESOLUTION)
XRESOLUTION = 1366
try:
s = f.readline().split(" #")[0]
if s == "fullscreen":
fullscreen = True
else:
fullscreen = False
except:
fullscreen = False
logging.info("Cannot read 'fullscreen' or 'window' as second line from screen.ini")
f.close()
# define set of colors
green = 0, 200, 0
darkergreen = 0, 180, 0
red = 200, 0, 0
black = 0, 0, 0
blue = 0, 0, 200
white = 255, 255, 255
terminal_text_color = 0xCF, 0xE0, 0x9A
grey = 100, 100, 100
lightgrey = 190, 190, 190
lightestgrey = 230, 230, 230
if TO_EXE:
usb_command = ["usbtool.exe"]
else:
usb_command = ["python", "usbtool.py"]
if portname is not None:
usb_command.extend(["--port", portname])
logging.debug("Calling %s", usb_command)
usb_proc = subprocess.Popen(usb_command)
tt.sleep(1) # time to make stable COMx connection
os.environ["SDL_VIDEO_WINDOW_POS"] = "90,20"
pygame.mixer.init()
pygame.init()
# auto reduce a screen's resolution
infoObject = pygame.display.Info()
xmax, ymax = infoObject.current_w, infoObject.current_h
logging.info("Xmax = %s", xmax)
logging.info("XRESOLUTION = %s", XRESOLUTION)
if xmax < XRESOLUTION:
XRESOLUTION = 1366
if xmax < XRESOLUTION:
XRESOLUTION = 480
if XRESOLUTION == 480:
screen_width, screen_height = 480, 320
elif XRESOLUTION == 1920:
screen_width, screen_height = 1500, 1000
elif XRESOLUTION == 1366:
screen_width, screen_height = 900, 600
x_multiplier, y_multiplier = float(screen_width) / 480, float(screen_height) / 320
if fullscreen:
scr = pygame.display.set_mode(
(screen_width, screen_height),
pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.FULLSCREEN,
32,
)
else:
scr = pygame.display.set_mode(
(screen_width, screen_height), pygame.HWSURFACE | pygame.DOUBLEBUF, 32
)
pygame.display.set_caption("Chess software")
font = pygame.font.Font("Fonts//OpenSans-Regular.ttf", int(13 * y_multiplier))
font_large = pygame.font.Font("Fonts//OpenSans-Regular.ttf", int(19 * y_multiplier))
scr.fill(black) # clear screen
pygame.display.flip() # copy to screen
# change mouse cursor to be unvisible - not needed for Windows!
# if not DEBUG:
# mc_strings = ' ',' ',' ',' ',' ',' ',' ',' '
# cursor,mask = pygame.cursors.compile( mc_strings )
# cursor_sizer = ((8, 8), (0, 0), cursor, mask)
# pygame.mouse.set_cursor(*cursor_sizer)
# ----------- load sprites
names = (
"black_bishop",
"black_king",
"black_knight",
"black_pawn",
"black_queen",
"black_rook",
"white_bishop",
"white_king",
"white_knight",
"white_pawn",
"white_queen",
"white_rook",
"terminal",
"logo",
"chessboard_xy",
"new_game",
"resume_game",
"save",
"exit",
"hint",
"setup",
"take_back",
"resume_back",
"analysing",
"back",
"black",
"confirm",
"delete-game",
"depth1",
"depth2",
"depth3",
"depth4",
"depth5",
"depth6",
"depth7",
"depth8",
"depth9",
"depth10",
"depth11",
"depth12",
"depth13",
"depth14",
"depth15",
"depth16",
"depth17",
"depth18",
"depth19",
"depth20",
"done",
"force-move",
"select-depth",
"start",
"welcome",
"white",
"hide_back",
"start-up-logo",
"do-your-move",
"move-certabo",
"place-pieces",
"place-pieces-on-chessboard",
"new-setup",
"please-wait",
"check-mate-banner",
)
sprite = {}
for name in names:
if XRESOLUTION == 480:
path = "sprites//"
elif XRESOLUTION == 1920:
path = "sprites_1920//"
elif XRESOLUTION == 1366:
path = "sprites_1380//"
sprite[name] = pygame.image.load(path + name + ".png")
sound = {}
sound_names = (
"move",
)
for _sound_name in sound_names:
try:
sound[_sound_name] = pygame.mixer.Sound('sounds/{}.wav'.format(_sound_name))
except:
logging.error('Unable to load `{}` sound'.format(_sound_name))
def play_sound(sound_name):
global sound
try:
s = sound[sound_name]
except KeyError:
return
s.play()
# show sprite by name from names
def show(name, x, y):
scr.blit(sprite[name], (x * x_multiplier, y * y_multiplier))
def button(
text,
x,
y,
padding=(5, 5, 5, 5),
color=white,
text_color=grey,
font=font_large,
font_size=22,
):
ptop, pleft, pbottom, pright = padding
text_width, text_height = font.size(text)
widget_width = pleft * x_multiplier + text_width + pright * x_multiplier
widget_height = ptop * y_multiplier + text_height + pbottom * y_multiplier
pygame.draw.rect(
scr, color, (x * x_multiplier, y * y_multiplier, widget_width, widget_height)
)
img = font.render(text, font_size, text_color)
pos = (x + pleft) * x_multiplier, (y + ptop) * y_multiplier
scr.blit(img, pos)
return (
x,
y,
x + int(widget_width // x_multiplier),
y + int(widget_height // y_multiplier),
)
# Show chessboard using FEN string like
# "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
FEN = {
"b": "black_bishop",
"k": "black_king",
"n": "black_knight",
"p": "black_pawn",
"q": "black_queen",
"r": "black_rook",
"B": "white_bishop",
"K": "white_king",
"N": "white_knight",
"P": "white_pawn",
"Q": "white_queen",
"R": "white_rook",
}
chessboard = chess.Board()
board_state = chessboard.fen()
move = []
def show_board(FEN_string, x0, y0):
show("chessboard_xy", x0, y0)
if rotate180:
FEN_string = "/".join(
row[::-1] for row in reversed(FEN_string.split(" ")[0].split("/"))
)
x, y = 0, 0
for c in FEN_string:
if c in FEN:
show(FEN[c], x0 + 26 + 31.8 * x, y0 + 23 + y * 31.8)
x += 1
elif c == "/": # new line
x = 0
y += 1
elif c == " ":
break
else:
x += int(c)
letter = "a", "b", "c", "d", "e", "f", "g", "h"
def show_board_and_animated_move(FEN_string, move, x0, y0):
piece = ""
if rotate180:
FEN_string = "/".join(
row[::-1] for row in reversed(FEN_string.split(" ")[0].split("/"))
)
xa = letter.index(move[0])
ya = 8 - int(move[1])
xb = letter.index(move[2])
yb = 8 - int(move[3])
if rotate180:
xa = 7 - xa
ya = 7 - ya
xb = 7 - xb
yb = 7 - yb
xstart, ystart = x0 + 26 + 31.8 * xa, y0 + 23 + ya * 31.8
xend, yend = x0 + 26 + 31.8 * xb, y0 + 23 + yb * 31.8
show("chessboard_xy", x0, y0)
x, y = 0, 0
for c in FEN_string:
if c in FEN:
if x != xa or y != ya:
show(FEN[c], x0 + 26 + 31.8 * x, y0 + 23 + y * 31.8)
else:
piece = FEN[c]
x += 1
elif c == "/": # new line
x = 0
y += 1
elif c == " ":
break
else:
x += int(c)
# pygame.display.flip() # copy to screen
if piece == "":
return
logging.info("%s", piece)
for i in range(20):
x, y = 0, 0
show("chessboard_xy", x0, y0)
for c in FEN_string:
if c in FEN:
if x != xa or y != ya:
show(FEN[c], x0 + 26 + 31.8 * x, y0 + 23 + y * 31.8)
x += 1
elif c == "/": # new line
x = 0
y += 1
elif c == " ":
break
else:
x += int(c)
xp = xstart + (xend - xstart) * i / 20.0
yp = ystart + (yend - ystart) * i / 20.0
show(piece, xp, yp)
# print x,y
# tt.sleep(0.1)
pygame.display.flip() # copy to screen
tt.sleep(0.01)
def generate_pgn():
global play_white, human_game, mate_we_lost, mate_we_won
move_history = [_move.uci() for _move in chessboard.move_stack]
game = chess.pgn.Game()
game.headers["Date"] = datetime.now().strftime("%Y.%m.%d")
if play_white:
game.headers["White"] = "Human"
game.headers["Black"] = "Computer" if not human_game else "Human"
else:
game.headers["White"] = "Computer" if not human_game else "Human"
game.headers["Black"] = "Human"
if mate_we_lost:
game.headers["Result"] = "0-1" if play_white else "1-0"
if mate_we_won:
game.headers["Result"] = "1-0" if play_white else "0-1"
if not mate_we_won and not mate_we_lost:
game.headers["Result"] = "*"
game.setup(chess.Board(starting_position))
node = game.add_variation(chess.Move.from_uci(move_history[0]))
for move in move_history[1:]:
node = node.add_variation(chess.Move.from_uci(move))
exporter = chess.pgn.StringExporter()
return game.accept(exporter)
# ------------- start point --------------------------------------------------------
timeout = datetime.now() + timedelta(milliseconds=500)
old_left_click = 0
T = datetime.now() + timedelta(milliseconds=100)
x, y = 0, 0
window = "home" # name of current page
dialog = "" # dialog inside the window
# window="resume"
timer = 0
play_white = True
side_to_move = "white"
difficulty = 0
terminal_lines = ["Game started", "Terminal text here"]
def terminal_print(s, newline=True):
global terminal_lines
if newline:
terminal_lines = [terminal_lines[1], s]
else:
terminal_lines[1] = "{}{}".format(terminal_lines[1], s)
pressed_key = ""
hint_text = ""
starting_position = chess.STARTING_FEN
name_to_save = ""
rotate180 = False
board_letters = "a", "b", "c", "d", "e", "f", "g", "h"
previous_board_click = "" # example: "e2"
board_click = "" # example: "e2"
do_ai_move = True
do_user_move = False
conversion_dialog = False
mate_we_lost = False
mate_we_won = False
human_game = False
use_board_position = False
renew = True
left_click = False
engine = "stockfish"
saved_files = []
resume_file_selected = 0
resume_file_start = 0 # starting filename to show
resuming_new_game = False
sock = socket(AF_INET, SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sock.bind(LISTEN_SOCKET)
sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
recv_list = [sock]
new_usb_data = False
usb_data_exist = False
codes.load_calibration(port)
calibration = False
calibration_samples_counter = 0
calibration_samples = []
usb_data_history_depth = 3
usb_data_history = range(usb_data_history_depth)
usb_data_history_filled = False
usb_data_history_i = 0
move_detect_tries = 0
move_detect_max_tries = 3
banner_right_places = False
banners_counter = 0
game_process_just_startted = True
waiting_for_user_move = False
new_setup = False
current_engine_page = 0
def send_leds(message='\x00' * 8):
sock.sendto(message, SEND_SOCKET)
send_leds('\xff' * 8)
scr.fill(white) # clear screen
show("start-up-logo", 7, 0)
pygame.display.flip() # copy to screen
tt.sleep(2)
send_leds()
poweroff_time = datetime.now()
while 1:
t = datetime.now() # current time
# event from system & keyboard
for event in pygame.event.get(): # all values in event list
if event.type == pygame.QUIT:
do_poweroff(usb_proc)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
do_poweroff(usb_proc)
if event.key == pygame.K_h:
window = "home"
if event.key == pygame.K_a:
pass
recv_ready, wtp, xtp = select(recv_list, [], [], 0.002)
if recv_ready:
try:
data, addr = sock.recvfrom(2048)
usb_data = map(int, data.split(" "))
new_usb_data = True
usb_data_exist = True
except:
logging.info("No new data from usb.exe, perhaps chess board not connected")
scr.fill(white) # clear screen
x, y = pygame.mouse.get_pos() # mouse position
x = x / x_multiplier
y = y / y_multiplier
mbutton = pygame.mouse.get_pressed()
if DEBUG:
txt(str((x, y)), 80, 300, lightgrey)
if mbutton[0] == 1 and old_left_click == 0:
left_click = True
else:
left_click = False
if x < 110 and y < 101 and mbutton[0] == 1:
if datetime.now() - poweroff_time >= timedelta(seconds=2):
do_poweroff(usb_proc)
else:
poweroff_time = datetime.now()
show("logo", 8, 6)
# -------------- home ----------------
if window == "home":
if new_usb_data:
new_usb_data = False
if usb_data_history_i >= usb_data_history_depth:
usb_data_history_filled = True
usb_data_history_i = 0
if DEBUG:
logging.info("usb_data_history_i = %s", usb_data_history_i)
usb_data_history[usb_data_history_i] = usb_data[:]
usb_data_history_i += 1
if usb_data_history_filled:
usb_data_processed = codes.statistic_processing(usb_data_history, False)
if usb_data_processed != []:
test_state = codes.usb_data_to_FEN(usb_data_processed, rotate180)
if test_state != "":
board_state = test_state
else:
logging.info("found unknown piece, filter processing")
if calibration:
calibration_samples.append(usb_data)
logging.info(" adding new calibration sample")
calibration_samples_counter += 1
if calibration_samples_counter >= 15:
logging.info(
"------- we have collected enough samples for averaging ----"
)
usb_data = codes.statistic_processing_for_calibration(
calibration_samples, False
)
# print usb_data
codes.calibration(usb_data, new_setup, port)
board_state = codes.usb_data_to_FEN(usb_data, rotate180)
calibration = False
# "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
# do a calibration
show("new_game", 5, 149)
if not args.robust:
show("resume_game", 5, 149 + 40)
show("setup", 5, 149 + 80)
show("new-setup", 5, 149 + 120)
show_board(board_state, 178, 40)
show("welcome", 111, 6)
if calibration:
show("please-wait", 253, 170)
if left_click:
if 6 < x < 102 and 232 < y < 265:
logging.info("calibration")
if usb_data_exist:
calibration = True
new_setup = False
calibration_samples_counter = 0
calibration_samples = []
calibration_samples.append(usb_data)
if 6 < x < 102 and y >= 265:
logging.info("New setup calibration")
if usb_data_exist:
calibration = True
new_setup = True
calibration_samples_counter = 0
calibration_samples = []
calibration_samples.append(usb_data)
if 6 < x < 123 and 150 < y < 190: # new game pressed
window = "new game"
send_leds()
if 6 < x < 163 and 191 < y < 222: # resume pressed
window = "resume"
# update saved files list to load
files = os.listdir(CERTABO_SAVE_PATH)
saved_files = [v for v in files if ".pgn" in v]
saved_files_time = []
terminal_lines = ["", ""]
mate_we_won = False
mate_we_lost = False
for name in saved_files:
saved_files_time.append(
tt.gmtime(
os.stat(os.path.join(CERTABO_SAVE_PATH, name)).st_mtime
)
)
# ---------------- Resume game dialog ----------------
elif window == "resume":
txt_large("Select game name to resume", 159, 1, black)
show("resume_back", 107, 34)
show("resume_game", 263, 283)
show("back", 3, 146)
show("delete-game", 103, 283)
pygame.draw.rect(
scr,
lightestgrey,
(
113 * x_multiplier,
41 * y_multiplier + resume_file_selected * 29 * y_multiplier,
330 * x_multiplier,
30 * y_multiplier,
),
) # selection
for i in range(len(saved_files)):
if i > 7:
break
txt_large(saved_files[i + resume_file_start][:-4], 117, 41 + i * 29, grey)
v = saved_files_time[i]
txt_large(
"%d-%d-%d %d:%d"
% (v.tm_year, v.tm_mon, v.tm_mday, v.tm_hour, v.tm_min),
300,
41 + i * 29,
lightgrey,
)
if dialog == "delete":
show("hide_back", 0, 0)
pygame.draw.rect(scr, lightgrey, (200 + 2, 77 + 2, 220, 78))
pygame.draw.rect(scr, white, (200, 77, 220, 78))
txt_large("Delete the game ?", 200 + 32, 67 + 15, grey)
show("back", 200 + 4, 77 + 40)
show("confirm", 200 + 4 + 112, 77 + 40)
if left_click:
if (77 + 40 - 5) < y < (77 + 40 + 30):
dialog = ""
if x > (200 + 105): # confirm button
logging.info("do delete")
os.unlink(
os.path.join(
CERTABO_SAVE_PATH,
saved_files[resume_file_selected + resume_file_start],
)
)
# update saved files list to load
files = os.listdir(CERTABO_SAVE_PATH)
saved_files = [v for v in files if ".pgn" in v]
saved_files_time = []
for name in saved_files:
saved_files_time.append(
tt.gmtime(
os.stat(
os.path.join(CERTABO_SAVE_PATH, name)
).st_mtime
)
)
resume_file_selected = 0
resume_file_start = 0
if left_click:
if 7 < x < 99 and 150 < y < 179: # back button
window = "home"
if 106 < x < 260 and 287 < y < 317: # delete button
dialog = "delete" # start delete confirm dialog on the page
if 107 < x < 442 and 40 < y < 274: # pressed on file list
i = (int(y) - 41) / 29
if i < len(saved_files):
resume_file_selected = i
if 266 < x < 422 and 286 < y < 316: # Resume button
logging.info("Resuming game")
with open(
os.path.join(
CERTABO_SAVE_PATH,
saved_files[resume_file_selected + resume_file_start],
),
"rb",
) as f:
_game = chess.pgn.read_game(f)
chessboard = _game.end().board()
_node = _game
while _node.variations:
_node = _node.variations[0]
play_white = _game.headers["White"] == "Human"
starting_position = _game.board().fen()
logging.info("Move history - %s", [_move.uci() for _move in _game.main_line()])
previous_board_click = ""
board_click = ""
do_ai_move = False
do_user_move = False
conversion_dialog = False
waiting_for_user_move = False
banner_place_pieces = True
resuming_new_game = True
window = "new game"
if 448 < x < 472: # arrows
if 37 < y < 60: # arrow up
if resume_file_start > 0:
resume_file_start -= 1
elif 253 < y < 284:
if (resume_file_start + 8) < len(saved_files):
resume_file_start += 1
# ---------------- Save game dialog ----------------
elif window == "save":
txt_large("Enter game name to save", 159, 41, grey)
show("terminal", 139, 80)
txt_large(
name_to_save, 273 - len(name_to_save) * (51 / 10.0), 86, terminal_text_color
)
# show keyboard
keyboard_buttons = (
("1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-"),
("q", "w", "e", "r", "t", "y", "u", "i", "o", "p"),
("a", "s", "d", "f", "g", "h", "j", "k", "l"),
("z", "x", "c", "v", "b", "n", "m"),
)
lenx = 42 # size of buttons
leny = 38 # size of buttons
ky = 128
x0 = 11
hover_key = ""
pygame.draw.rect(
scr,
lightgrey,
(
431 * x_multiplier,
81 * y_multiplier,
lenx * x_multiplier - 2,
leny * y_multiplier - 2,
),
) # back space
txt_large("<", (431 + 14), (81 + 4), black)
for row in keyboard_buttons:
kx = x0
for key in row:
pygame.draw.rect(
scr,
lightgrey,
(
kx * x_multiplier,
ky * y_multiplier,
lenx * x_multiplier - 2,
leny * y_multiplier - 2,
),
)
txt_large(key, kx + 14, ky + 4, black)
if kx < x < (kx + lenx) and ky < y < (ky + leny):
hover_key = key
kx += lenx
ky += leny
x0 += 20
pygame.draw.rect(
scr,
lightgrey,
(
x0 * x_multiplier + lenx * x_multiplier,
ky * y_multiplier,
188 * x_multiplier,
leny * y_multiplier - 2,
),
) # spacebar
if (x0 + lenx) < x < (x0 + lenx + 188) and ky < y < (ky + leny):
hover_key = " "
show("save", 388, 264)
if 388 < x < (388 + 100) and 263 < y < (263 + 30):
hover_key = "save"
if 431 < x < (431 + lenx) and 81 < y < (81 + leny):
hover_key = "<"
# ----- process buttons -----
if left_click:
if hover_key != "":
if hover_key == "save":
OUTPUT_PGN = os.path.join(
CERTABO_SAVE_PATH, "{}.pgn".format(name_to_save)
)
with open(OUTPUT_PGN, "w") as f:
f.write(generate_pgn())
window = "game"
# banner_do_move = False
previous_board_click = ""
board_click = ""
left_click = False
conversion_dialog = False
elif hover_key == "<":
if len(name_to_save) > 0:
name_to_save = name_to_save[: len(name_to_save) - 1]
else:
if len(name_to_save) < 22:
name_to_save += hover_key
# ---------------- game dialog ----------------
elif window == "game":
if new_usb_data:
new_usb_data = False
if DEBUG:
logging.info("Virtual board: %s", chessboard.fen())
banners_counter += 1
if usb_data_history_i >= usb_data_history_depth:
usb_data_history_filled = True
usb_data_history_i = 0
# print "usb_data_history_i = ",usb_data_history_i
usb_data_history[usb_data_history_i] = usb_data[:]
usb_data_history_i += 1
if usb_data_history_filled:
usb_data_processed = codes.statistic_processing(usb_data_history, False)
if usb_data_processed != []:
test_state = codes.usb_data_to_FEN(usb_data_processed, rotate180)
if test_state != "":
board_state_usb = test_state
game_process_just_started = False
# compare virtual board state and state from usb
s1 = chessboard.board_fen()
s2 = board_state_usb.split(" ")[0]
if s1 != s2:
if waiting_for_user_move:
try:
move_detect_tries += 1
move = codes.get_moves(chessboard, board_state_usb)
except codes.InvalidMove:
if move_detect_tries > move_detect_max_tries:
terminal_print("Invalid move")
else:
move_detect_tries = 0
if move:
waiting_for_user_move = False
do_user_move = True
else:
if DEBUG:
logging.info("Place pieces on their places")
banner_right_places = True
if not human_game:
if play_white != chessboard.turn:
banner_place_pieces = True
else:
banner_place_pieces = True
else:
if DEBUG:
logging.info("All pieces on right places")
send_leds()
banner_right_places = False
banner_place_pieces = False
# start with black, do move just right after right initial board placement
if not human_game:
if chessboard.turn != play_white:
do_ai_move = True
else:
do_ai_move = False
if (
not game_process_just_started
and not do_user_move
and not do_ai_move
):
banner_place_pieces = False
waiting_for_user_move = True
else:
logging.info("found unknown piece, filter processing")