-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1725 lines (1616 loc) · 97.1 KB
/
main.py
File metadata and controls
1725 lines (1616 loc) · 97.1 KB
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
# pylint: disable=E1101
"""
Chess created by Brad Wyatt
"""
import random
import sys
import os
import copy
import datetime
import asyncio
import logging
import logging.handlers
import ast
import json
import pygame
import pygame.freetype
import initvar
if sys.platform != "emscripten":
import tkinter as tk
from tkinter.filedialog import asksaveasfilename, askopenfilename
else:
tk = None
asksaveasfilename = None
askopenfilename = None
import load_images_sounds as lis
import menu_buttons
import board
import start_objects
import placed_objects
import play_objects
import replayed_objects
#############
# Logging
#############
today = datetime.datetime.today()
log = logging.getLogger("log_guy")
log.handlers = []
log.setLevel(logging.INFO)
# Handlers for logging errors
if not initvar.exe_mode:
log_file_name = "{0}.log".format(today.strftime("%Y-%m-%d %H%M%S"))
log_file = os.path.join(initvar.log_path, log_file_name)
os.makedirs(initvar.log_path, exist_ok=True)
file_handler = logging.FileHandler(log_file)
log_file_formatter = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
file_handler.setFormatter(log_file_formatter)
file_handler.setLevel(logging.DEBUG)
log.addHandler(file_handler)
console_handler = logging.StreamHandler()
log_console_handler = logging.Formatter("%(message)s")
console_handler.setFormatter(log_console_handler)
console_handler.setLevel(logging.DEBUG)
log.addHandler(console_handler)
#############
# Submodule imports (re-exported for backward compatibility)
#############
from game.controllers.move_tracker import MoveTracker
from game.controllers.text_controller import TextController
from game.controllers.cpu_controller import CpuController
from game.controllers.panel_controller import PanelController
from game.controllers.switch_modes import SwitchModesController, GridController
from game.controllers.game_controller import EditModeController, GameController, MoveController
from game.io.positions import (
native_file_dialogs_available, itch_mode_blocked,
pos_load_file, load_position_from_json, get_dict_rect_positions, pos_save_file, pos_lists_to_coord,
GameProperties, POSITION_METADATA_DEFAULTS, load_position_from_dict,
)
from game.io.pgn import PgnWriterAndLoader
async def main():
import asyncio
import logging
import load_images_sounds as lis
pygame = lis.pygame
log = logging.getLogger("log_guy")
try:
running, debug = 0, 1
state = running
debug_message = 0
app_running = True
clock = pygame.time.Clock()
pending_cpu_move_at = None
def cancel_pending_cpu_move():
nonlocal pending_cpu_move_at
pending_cpu_move_at = None
def schedule_cpu_move():
nonlocal pending_cpu_move_at
pending_cpu_move_at = pygame.time.get_ticks() + initvar.CPU_MOVE_DELAY_MS
def _sync_cpu_turn_after_mode_change():
if SwitchModesController.GAME_MODE != SwitchModesController.PLAY_MODE:
cancel_pending_cpu_move()
return
if not CpuController.cpu_mode or game_controller.result_abb != "*":
cancel_pending_cpu_move()
return
if game_controller.whoseturn == CpuController.cpu_color:
schedule_cpu_move()
else:
cancel_pending_cpu_move()
def start_game(whoseturn=None):
nonlocal game_controller
cancel_pending_cpu_move()
start_objects.Dragging.dragging_all_false()
SwitchModesController.switch_mode(SwitchModesController.PLAY_MODE, play_edit_switch_button)
if whoseturn is None:
whoseturn = pending_start_whoseturn
game_controller = GameController(
GridController.flipped,
whoseturn=whoseturn,
variant_key=active_game_mode_key,
)
game_controller.refresh_objects()
if CpuController.cpu_mode and game_controller.whoseturn == CpuController.cpu_color:
schedule_cpu_move()
def _normalize_game_mode_label(game_mode):
normalized = str(game_mode).strip().lower().replace("-", " ").replace("_", " ")
if normalized == "play as white vs cpu":
return "Play as White vs CPU"
if normalized == "play as black vs cpu":
return "Play as Black vs CPU"
return "Human vs Human"
def _normalize_board_orientation_label(board_orientation):
normalized = str(board_orientation).strip().lower().replace("-", " ").replace("_", " ")
if normalized == "black on bottom":
return "Black on Bottom"
return "White on Bottom"
def _normalize_starting_turn(whoseturn):
return "black" if str(whoseturn).strip().lower() == "black" else "white"
def _current_position_config():
if not CpuController.cpu_mode:
game_mode = "Human vs Human"
elif CpuController.cpu_color == "black":
game_mode = "Play as White vs CPU"
else:
game_mode = "Play as Black vs CPU"
return {
"game_mode": game_mode,
"board_orientation": "Black on Bottom" if GridController.flipped else "White on Bottom",
"starting_turn": pending_start_whoseturn,
}
def _apply_position_config(config, fallback_whoseturn="white"):
nonlocal pending_start_whoseturn
merged_config = POSITION_METADATA_DEFAULTS.copy()
if config:
merged_config.update(config)
game_mode = _normalize_game_mode_label(merged_config["game_mode"])
if game_mode == "Play as White vs CPU":
CpuController.cpu_mode = True
CpuController.cpu_color = "black"
CpuController.enemy_color = "white"
elif game_mode == "Play as Black vs CPU":
CpuController.cpu_mode = True
CpuController.cpu_color = "white"
CpuController.enemy_color = "black"
else:
CpuController.cpu_mode = False
CpuController.cpu_color = "black"
CpuController.enemy_color = "white"
board_orientation = _normalize_board_orientation_label(merged_config["board_orientation"])
should_be_flipped = (board_orientation == "Black on Bottom")
if GridController.flipped != should_be_flipped:
GridController.flip_grids()
starting_turn = fallback_whoseturn
if config and "starting_turn" in config:
starting_turn = config["starting_turn"]
elif fallback_whoseturn is None:
starting_turn = merged_config["starting_turn"]
pending_start_whoseturn = _normalize_starting_turn(starting_turn)
def reset_to_default_setup():
nonlocal pending_start_whoseturn, active_game_mode_key
if GridController.flipped:
GridController.flip_grids()
CpuController.cpu_mode = False
CpuController.cpu_color = "black"
CpuController.enemy_color = "white"
GameProperties.Event = ""
GameProperties.Site = ""
GameProperties.Date = ""
GameProperties.Round = ""
GameProperties.White = ""
GameProperties.Black = ""
GameProperties.Result = ""
GameProperties.WhiteElo = ""
GameProperties.BlackElo = ""
GameProperties.ECO = ""
GameProperties.TimeControl = "0"
start_objects.Start.restart_start_positions()
pos_load_file(reset=True)
pending_start_whoseturn = "white"
TextController.remove_check_checkmate_text()
active_game_mode_key = None
def _build_current_orientation_config(starting_turn="white"):
return {
"game_mode": "Human vs Human",
"board_orientation": "Black on Bottom" if GridController.flipped else "White on Bottom",
"starting_turn": _normalize_starting_turn(starting_turn),
}
def _reset_board_for_game_mode_load():
cancel_pending_cpu_move()
start_objects.Dragging.dragging_all_false()
start_objects.Start.restart_start_positions()
TextController.remove_check_checkmate_text()
GameProperties.Result = ""
if SwitchModesController.GAME_MODE == SwitchModesController.PLAY_MODE:
stop_game()
def _clear_active_game_mode_if_edit_board_changed(previous_snapshot):
nonlocal active_game_mode_key
if active_game_mode_key and previous_snapshot != get_dict_rect_positions():
active_game_mode_key = None
def _generate_random_setup_position():
back_rank = [None] * 8
even_files = [0, 2, 4, 6]
odd_files = [1, 3, 5, 7]
light_bishop_index = random.choice(even_files)
dark_bishop_index = random.choice(odd_files)
back_rank[light_bishop_index] = "bishop"
back_rank[dark_bishop_index] = "bishop"
remaining = [index for index, piece in enumerate(back_rank) if piece is None]
queen_index = random.choice(remaining)
back_rank[queen_index] = "queen"
remaining = [index for index, piece in enumerate(back_rank) if piece is None]
knight_indices = random.sample(remaining, 2)
for knight_index in knight_indices:
back_rank[knight_index] = "knight"
remaining = sorted(index for index, piece in enumerate(back_rank) if piece is None)
back_rank[remaining[0]] = "rook"
back_rank[remaining[1]] = "king"
back_rank[remaining[2]] = "rook"
files = "abcdefgh"
def _coords_for(piece_name, rank):
return [f"{files[index]}{rank}" for index, piece in enumerate(back_rank) if piece == piece_name]
return {
"white_pawn": [f"{file_name}2" for file_name in files],
"white_bishop": _coords_for("bishop", 1),
"white_knight": _coords_for("knight", 1),
"white_rook": _coords_for("rook", 1),
"white_queen": _coords_for("queen", 1),
"white_king": _coords_for("king", 1),
"black_pawn": [f"{file_name}7" for file_name in files],
"black_bishop": _coords_for("bishop", 8),
"black_knight": _coords_for("knight", 8),
"black_rook": _coords_for("rook", 8),
"black_queen": _coords_for("queen", 8),
"black_king": _coords_for("king", 8),
}
def generateChaosSetup():
files = "abcdefgh"
capped_piece_counts = {
"queen": 2,
"rook": 3,
"bishop": 3,
"knight": 3,
}
def _generate_back_rank():
piece_pool = ["king"]
for piece_name, max_count in capped_piece_counts.items():
piece_pool.extend([piece_name] * max_count)
chosen_pieces = ["king"]
chosen_pieces.extend(random.sample(piece_pool[1:], 7))
random.shuffle(chosen_pieces)
return chosen_pieces
def _coords_for(back_rank, piece_name, rank):
return [
f"{files[index]}{rank}"
for index, current_piece in enumerate(back_rank)
if current_piece == piece_name
]
white_back_rank = _generate_back_rank()
black_back_rank = _generate_back_rank()
return {
"white_pawn": [f"{file_name}2" for file_name in files],
"white_bishop": _coords_for(white_back_rank, "bishop", 1),
"white_knight": _coords_for(white_back_rank, "knight", 1),
"white_rook": _coords_for(white_back_rank, "rook", 1),
"white_queen": _coords_for(white_back_rank, "queen", 1),
"white_king": _coords_for(white_back_rank, "king", 1),
"black_pawn": [f"{file_name}7" for file_name in files],
"black_bishop": _coords_for(black_back_rank, "bishop", 8),
"black_knight": _coords_for(black_back_rank, "knight", 8),
"black_rook": _coords_for(black_back_rank, "rook", 8),
"black_queen": _coords_for(black_back_rank, "queen", 8),
"black_king": _coords_for(black_back_rank, "king", 8),
}
def loadPawnsOnly():
nonlocal game_modes_modal_open, restore_default_setup_on_stop, pending_start_whoseturn, active_game_mode_key
_reset_board_for_game_mode_load()
load_position_from_dict({
"white_pawn": [f"{file_name}2" for file_name in "abcdefgh"],
"white_bishop": [],
"white_knight": [],
"white_rook": [],
"white_queen": [],
"white_king": ["e1"],
"black_pawn": [f"{file_name}7" for file_name in "abcdefgh"],
"black_bishop": [],
"black_knight": [],
"black_rook": [],
"black_queen": [],
"black_king": ["e8"],
})
_apply_position_config(_build_current_orientation_config("white"))
game_modes_modal_open = False
restore_default_setup_on_stop = False
active_game_mode_key = "pawns_only"
def loadRandomSetup():
nonlocal game_modes_modal_open, restore_default_setup_on_stop, pending_start_whoseturn, active_game_mode_key
_reset_board_for_game_mode_load()
load_position_from_dict(_generate_random_setup_position())
_apply_position_config(_build_current_orientation_config("white"))
game_modes_modal_open = False
restore_default_setup_on_stop = False
active_game_mode_key = "random_setup"
def loadChaosSetup():
nonlocal game_modes_modal_open, restore_default_setup_on_stop, pending_start_whoseturn, active_game_mode_key
_reset_board_for_game_mode_load()
load_position_from_dict(generateChaosSetup())
_apply_position_config(_build_current_orientation_config("white"))
game_modes_modal_open = False
restore_default_setup_on_stop = False
active_game_mode_key = "chaos_setup"
def loadPeasantsRevolt():
nonlocal game_modes_modal_open, restore_default_setup_on_stop, pending_start_whoseturn, active_game_mode_key
_reset_board_for_game_mode_load()
load_position_from_dict({
"white_pawn": [f"{file_name}2" for file_name in "abcdefgh"],
"white_bishop": [],
"white_knight": [],
"white_rook": [],
"white_queen": [],
"white_king": ["e1"],
"black_pawn": ["e7"],
"black_bishop": [],
"black_knight": ["b8", "d8", "g8"],
"black_rook": [],
"black_queen": [],
"black_king": ["e8"],
})
_apply_position_config(_build_current_orientation_config("white"))
game_modes_modal_open = False
restore_default_setup_on_stop = False
active_game_mode_key = "peasants_revolt"
def loadLightBrigade():
nonlocal game_modes_modal_open, restore_default_setup_on_stop, pending_start_whoseturn, active_game_mode_key
_reset_board_for_game_mode_load()
load_position_from_dict({
"white_pawn": [f"{file_name}2" for file_name in "abcdefgh"],
"white_bishop": [],
"white_knight": [],
"white_rook": [],
"white_queen": ["b1", "d1", "g1"],
"white_king": ["e1"],
"black_pawn": [f"{file_name}7" for file_name in "abcdefgh"],
"black_bishop": [],
"black_knight": ["a8", "b8", "c8", "d8", "f8", "g8", "h8"],
"black_rook": [],
"black_queen": [],
"black_king": ["e8"],
})
_apply_position_config(_build_current_orientation_config("white"))
game_modes_modal_open = False
restore_default_setup_on_stop = False
active_game_mode_key = "light_brigade"
def stop_game():
nonlocal game_controller, restore_default_setup_on_stop
cancel_pending_cpu_move()
start_objects.Dragging.dragging_all_false()
SwitchModesController.switch_mode(SwitchModesController.EDIT_MODE, play_edit_switch_button)
del game_controller
if restore_default_setup_on_stop:
reset_to_default_setup()
restore_default_setup_on_stop = False
play_edit_switch_button = menu_buttons.PlayEditSwitchButton(initvar.PLAY_EDIT_SWITCH_BUTTON_TOPLEFT)
features_panel = menu_buttons.SidebarSectionPanel(
(
initvar.FEATURES_SECTION_X,
initvar.FEATURES_SECTION_Y,
initvar.FEATURES_SECTION_W,
initvar.FEATURES_SECTION_H,
),
"LIBRARY",
)
game_modes_button = menu_buttons.SidebarActionButton(initvar.PUZZLES_BUTTON_TOPLEFT, "Game Modes")
pgn_games_button = menu_buttons.SidebarActionButton(initvar.PGN_GAMES_BUTTON_TOPLEFT, "PGN Games")
help_button = menu_buttons.HelpButton(initvar.HELP_BUTTON_TOPLEFT)
flip_board_button = menu_buttons.FlipBoardButton(initvar.FLIP_BOARD_BUTTON_TOPLEFT)
game_mode_selector = menu_buttons.GameModeSelector(initvar.GAME_MODE_SELECTOR_TOPLEFT)
starting_turn_selector = menu_buttons.StartingTurnSelector(initvar.TURN_SELECTOR_TOPLEFT)
help_overlay_open = False
game_modes_modal_open = False
pgn_games_modal_open = False
save_position_modal_open = False
restore_default_setup_on_stop = False
pending_start_whoseturn = "white"
show_help_hint = True
hint_expire_at = pygame.time.get_ticks() + 4200
help_panel_width = 430
help_panel_rect = pygame.Rect(help_button.rect.right - help_panel_width, help_button.rect.bottom + 14, help_panel_width, 320)
modal_panel_rect = pygame.Rect(0, 0, 0, 0)
modal_close_rect = pygame.Rect(0, 0, 0, 0)
game_mode_button_rects = {}
game_mode_section_rects = {}
save_turn_button_rects = {}
game_mode_sections = [
{
"section_key": "puzzles",
"title": "Puzzles",
"helper_text": "Curated mate positions for fast solving.",
"collapsible": True,
"expanded": True,
"modes": [
("mate_in_1", "🧩", "Mate in 1", "Puzzle", "Play as Black vs CPU and find the forced mate in one.", "chess_positions/black_to_move_mate_in_1.json", "black"),
("mate_in_2", "🧩", "Mate in 2", "Puzzle", "Play as Black vs CPU and find the forced mate in two.", "chess_positions/black_to_move_mate_in_2.json", "black"),
("mate_in_3", "🧩", "Mate in 3", "Puzzle", "Play as Black vs CPU and find the forced mate in three.", "chess_positions/black_to_move_mate_in_3.json", "black"),
("mate_in_4", "🧩", "Mate in 4", "Puzzle", "Play as White vs CPU and find the forced mate in four.", "chess_positions/white_to_move_mate_in_4.json", "white"),
],
},
{
"section_key": "variants",
"title": "Variants",
"helper_text": "Experimental setups for alternate openings and piece mixes.",
"collapsible": True,
"expanded": True,
"modes": [
("pawns_only", "♟️", "Pawns Only", "Variant", "Strip the board down to kings and pawns on their standard files.", None, "white"),
("random_setup", "🎲", "Random Setup", "Variant", "Generate a fresh Chess960-style back rank while keeping pawns in place.", None, "white"),
("chaos_setup", "⚡", "Chaos Setup", "Variant", "Randomized armies. Standard pawn lines and no castling.", None, "white"),
("peasants_revolt", "⚔️", "Peasant's Revolt", "Variant", "White fields a king with eight pawns against Black's king, three knights, and one pawn.", None, "white"),
("light_brigade", "🐎", "Charge of the Light Brigade", "Variant", "White charges with three queens and a full pawn line against Black's seven knights and pawns.", None, "white"),
],
},
]
active_game_mode_key = None
emoji_font = None
for candidate_font_path in (
"/System/Library/Fonts/Apple Color Emoji.ttc",
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
):
if os.path.exists(candidate_font_path):
try:
emoji_font = pygame.freetype.Font(candidate_font_path, 32)
break
except (FileNotFoundError, OSError, pygame.error):
emoji_font = None
pgn_game_button_rects = {}
pgn_game_options = [
("carlsen_kasparov", "Carlsen vs Kasparov (2004)", "pgn_sample_games/carlsen_kasparov_2004.pgn"),
("de_los_santos_polgar", "De los Santos vs Polgar (1990)", "pgn_sample_games/de_los_santos_polgar_1990.pgn"),
("deep_blue_kasparov", "Deep Blue vs Kasparov (1996)", "pgn_sample_games/DeepBlue_GarryKasparov_02101996.pgn"),
]
file_actions_panel = None
game_properties_button = None
if not initvar.ITCH_MODE:
game_properties_button = menu_buttons.GamePropertiesButton(initvar.GAME_PROPERTIES_BUTTON_TOPLEFT)
file_actions_panel = menu_buttons.FileActionsPanel()
reset_board_button = menu_buttons.ResetBoardButton(initvar.RESET_BOARD_BUTTON_TOPLEFT)
clear_button = menu_buttons.ClearButton(initvar.CLEAR_BUTTON_TOPLEFT)
scroll_up_button = menu_buttons.ScrollUpButton(initvar.SCROLL_UP_BUTTON_TOPLEFT)
scroll_down_button = menu_buttons.ScrollDownButton(initvar.SCROLL_DOWN_BUTTON_TOPLEFT)
beginning_move_button = menu_buttons.BeginningMoveButton(initvar.BEGINNING_MOVE_BUTTON_TOPLEFT)
prev_move_button = menu_buttons.PrevMoveButton(initvar.PREV_MOVE_BUTTON_TOPLEFT)
next_move_button = menu_buttons.NextMoveButton(initvar.NEXT_MOVE_BUTTON_TOPLEFT)
last_move_button = menu_buttons.LastMoveButton(initvar.LAST_MOVE_BUTTON_TOPLEFT)
undo_move_button = menu_buttons.UndoMoveButton(initvar.UNDO_MOVE_BUTTON_TOPLEFT)
replay_button_tooltips = (
(beginning_move_button, "Go to Beginning"),
(prev_move_button, "Previous Move"),
(next_move_button, "Next Move"),
(last_move_button, "Go to Last Move"),
)
# Window
gameicon = pygame.image.load("sprites/chessico.png")
pygame.display.set_icon(gameicon)
pygame.display.set_caption('Chess')
# Load the starting positions of chessboard first
pos_load_file(reset=True)
start_game()
# Pre-create dark overlays for visual contrast.
# (15, 20, 35): dark navy rather than near-black — the blue channel is visible at
# lower opacities and keeps the overlay in the space background's color family.
_OVERLAY_COLOR = (15, 20, 35)
_shared_x = initvar.X_GRID_START - 45
_shared_y = initvar.BLACK_X_Y[1] - 5
_undo_bottom = initvar.UNDO_MOVE_BUTTON_TOPLEFT[1] + 78
_captured_row_bottom = initvar.BLACK_CAPTURED_Y + board.Y_GRID_HEIGHT
_shared_bottom = max(_undo_bottom, _captured_row_bottom) + 8
# Width spans from the left of the board area to the right of the panel — one
# continuous surface so board and panel read as the same zone, not two boxes.
_shared_w = (initvar.MOVE_BG_IMAGE_X - 12 + 226) - _shared_x
_shared_h = _shared_bottom - _shared_y
_main_bg_overlay = pygame.Surface((_shared_w, _shared_h))
_main_bg_overlay.fill(_OVERLAY_COLOR)
_main_bg_overlay.set_alpha(88)
# ── Design-system tokens ────────────────────────────────────────────
# Shared across ALL panels (right move-list, Game Setup, player badges,
# popovers) so every surface feels like part of the same system.
_PANEL_FILL = (10, 22, 52) # unified dark navy
_PANEL_BORDER = (72, 100, 148) # steel-blue edge — same as Game Setup
_PANEL_RADIUS = 12 # consistent corner radius
_PANEL_RECT = (initvar.MOVE_BG_IMAGE_X, initvar.MOVE_BG_IMAGE_Y, 202, 628)
# Pre-render the right panel surface once — avoids rebuilding each frame.
_rp_surf = pygame.Surface((_PANEL_RECT[2], _PANEL_RECT[3]), pygame.SRCALPHA)
pygame.draw.rect(_rp_surf, (*_PANEL_FILL, 210), _rp_surf.get_rect(), border_radius=_PANEL_RADIUS)
pygame.draw.rect(_rp_surf, (*_PANEL_BORDER, 215), _rp_surf.get_rect(), 1, border_radius=_PANEL_RADIUS)
_rp_shadow = pygame.Surface((_PANEL_RECT[2] + 8, _PANEL_RECT[3] + 8), pygame.SRCALPHA)
pygame.draw.rect(_rp_shadow, (0, 0, 0, 55), _rp_shadow.get_rect(), border_radius=_PANEL_RADIUS + 3)
# Sidebar: slightly more opaque so the column reads as a grounded panel.
_sidebar_bg_overlay = pygame.Surface((210, initvar.SCREEN_HEIGHT))
_sidebar_bg_overlay.fill(_OVERLAY_COLOR)
_sidebar_bg_overlay.set_alpha(85)
_player_name_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 26, bold=True)
_player_rating_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 17)
_status_label_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 16, bold=True)
_status_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 28, bold=True)
_status_sub_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 20)
_game_mode_title_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 22, bold=True)
_tooltip_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 18)
_itch_notice_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 12, bold=False)
_game_mode_badge_fill = (0, 0, 0, 102)
_game_mode_badge_border = (255, 255, 255, 38)
_game_mode_badge_text = (242, 247, 255)
_game_mode_badge_pad_x = 16
_game_mode_badge_pad_y = 7
_game_mode_badge_bottom_margin = 4
_label_color = (165, 195, 230) # matches "GAME SETUP" label — consistent across panels
_muted_text = (150, 175, 210)
_game_mode_title_by_key = {
"mate_in_1": "Mate in 1",
"mate_in_2": "Mate in 2",
"mate_in_3": "Mate in 3",
"mate_in_4": "Mate in 4",
"pawns_only": "Pawns Only",
"random_setup": "Random Setup",
"chaos_setup": "Chaos Setup",
"peasants_revolt": "Peasant's Revolt",
"light_brigade": "Charge of the Light Brigade",
}
def _fit_font(text, max_width, start_size, min_size, bold=False):
size = start_size
while size >= min_size:
font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, size, bold=bold)
if font.size(text)[0] <= max_width:
return font
size -= 1
return pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, min_size, bold=bold)
def _wrap_text_lines(text, font, max_width):
words = text.split()
if not words:
return []
lines = []
current_line = words[0]
for word in words[1:]:
candidate = f"{current_line} {word}"
if font.size(candidate)[0] <= max_width:
current_line = candidate
else:
lines.append(current_line)
current_line = word
lines.append(current_line)
return lines
_player_badge_hover_info = [] # [(pygame.Rect, full_name), ...] — populated each frame
def _truncate_name(text, font, max_width):
if font.size(text)[0] <= max_width:
return text
ellipsis = "\u2026"
while text and font.size(text + ellipsis)[0] > max_width:
text = text[:-1]
return text + ellipsis
def _draw_tooltip(text, pos):
tip_surf = _tooltip_font.render(text, True, (242, 247, 255))
pad = 6
tip_w = tip_surf.get_width() + pad * 2
tip_h = tip_surf.get_height() + pad * 2
tip_bg = pygame.Surface((tip_w, tip_h), pygame.SRCALPHA)
pygame.draw.rect(tip_bg, (*_PANEL_FILL, 220), tip_bg.get_rect(), border_radius=8)
pygame.draw.rect(tip_bg, (*_PANEL_BORDER, 190), tip_bg.get_rect(), 1, border_radius=8)
tip_bg.blit(tip_surf, (pad, pad))
tx = min(pos[0] + 12, lis.SCREEN.get_width() - tip_w - 4)
ty = max(pos[1] - tip_h - 4, 4)
lis.SCREEN.blit(tip_bg, (tx, ty))
def _draw_help_hint():
if not show_help_hint or pygame.time.get_ticks() >= hint_expire_at or help_overlay_open:
return
hint_text = _tooltip_font.render("Need help?", True, (242, 247, 255))
pad_x = 12
pad_y = 8
hint_w = hint_text.get_width() + pad_x * 2
hint_h = hint_text.get_height() + pad_y * 2
hint_x = help_button.rect.left - hint_w - 12
hint_y = help_button.rect.centery - hint_h // 2
hint_bg = pygame.Surface((hint_w, hint_h), pygame.SRCALPHA)
pygame.draw.rect(hint_bg, (*_PANEL_FILL, 208), hint_bg.get_rect(), border_radius=10)
pygame.draw.rect(hint_bg, (*_PANEL_BORDER, 190), hint_bg.get_rect(), 1, border_radius=10)
hint_bg.blit(hint_text, (pad_x, pad_y))
lis.SCREEN.blit(hint_bg, (hint_x, hint_y))
pointer = [
(hint_x + hint_w, help_button.rect.centery - 6),
(hint_x + hint_w + 8, help_button.rect.centery),
(hint_x + hint_w, help_button.rect.centery + 6),
]
pygame.draw.polygon(lis.SCREEN, (*_PANEL_FILL, 208), pointer)
pygame.draw.polygon(lis.SCREEN, (*_PANEL_BORDER, 190), pointer, 1)
def _draw_itch_notice():
notice_text = "Best experienced on desktop. If playing on itch.io, please use landscape mode."
notice_surf = _itch_notice_font.render(notice_text, True, (255, 255, 255))
notice_surf.set_alpha(204)
shadow_surf = _itch_notice_font.render(notice_text, True, (0, 0, 0))
shadow_surf.set_alpha(178)
notice_x = _shared_x
notice_y = lis.SCREEN.get_height() - notice_surf.get_height() - 16
lis.SCREEN.blit(shadow_surf, (notice_x, notice_y + 1))
lis.SCREEN.blit(shadow_surf, (notice_x, notice_y + 2))
lis.SCREEN.blit(notice_surf, (notice_x, notice_y))
def _get_itch_notice_rect():
if not initvar.ITCH_MODE or pgn_games_modal_open:
return None
notice_text = "Best experienced on desktop. If playing on itch.io, please use landscape mode."
notice_w, notice_h = _itch_notice_font.size(notice_text)
notice_x = _shared_x
notice_y = lis.SCREEN.get_height() - notice_h - 16
return pygame.Rect(notice_x, notice_y, notice_w, notice_h)
def _draw_active_game_mode_title():
if not active_game_mode_key:
return
title_text = _game_mode_title_by_key.get(active_game_mode_key)
if not title_text:
return
title_font = _fit_font(title_text, _shared_w - (_game_mode_badge_pad_x * 2) - 24, 22, 16, bold=True)
title_surf = title_font.render(title_text, True, _game_mode_badge_text)
badge_w = title_surf.get_width() + (_game_mode_badge_pad_x * 2)
badge_h = title_surf.get_height() + (_game_mode_badge_pad_y * 2)
badge_y = initvar.SCREEN_HEIGHT - badge_h - _game_mode_badge_bottom_margin
badge_x = _shared_x + (_shared_w - badge_w) // 2
itch_notice_rect = _get_itch_notice_rect()
if itch_notice_rect is not None:
min_badge_x = itch_notice_rect.right + 16
badge_x = max(badge_x, min_badge_x)
badge_rect = pygame.Rect(badge_x, badge_y, badge_w, badge_h)
badge_surf = pygame.Surface((badge_w, badge_h), pygame.SRCALPHA)
pygame.draw.rect(badge_surf, _game_mode_badge_fill, badge_surf.get_rect(), border_radius=999)
pygame.draw.rect(badge_surf, _game_mode_badge_border, badge_surf.get_rect(), 1, border_radius=999)
lis.SCREEN.blit(badge_surf, badge_rect.topleft)
title_x = badge_rect.x + (badge_rect.width - title_surf.get_width()) // 2
title_y = badge_rect.y + (badge_rect.height - title_surf.get_height()) // 2
lis.SCREEN.blit(title_surf, (title_x, title_y))
def _draw_help_overlay():
_dim = pygame.Surface(lis.SCREEN.get_size(), pygame.SRCALPHA)
_dim.fill((5, 10, 24, 165))
lis.SCREEN.blit(_dim, (0, 0))
title_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 24, bold=True)
body_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 18)
muted_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 16)
content = [
("Quick Help", title_font, (242, 247, 255), 20, False),
("Drag pieces in setup mode to build a position.", body_font, (226, 235, 248), 72, True),
("Use Start Game to switch into play mode.", body_font, (226, 235, 248), None, True),
("Flip rotates the board. Undo and replay controls work in play mode.", body_font, (226, 235, 248), None, True),
("Undo Move also turns off CPU mode for the current game.", body_font, (226, 235, 248), None, True),
]
if initvar.ITCH_MODE:
content.extend([
("This itch build focuses on board setup and play.", body_font, (226, 235, 248), None, True),
("Press Esc or click outside to close.", muted_font, (165, 195, 230), None, True),
])
else:
content.extend([
("In play mode, you can save the PGN of the game you're playing.", body_font, (226, 235, 248), None, True),
("In edit mode, you can load PGN, save positions, and load positions.", body_font, (226, 235, 248), None, True),
("Press Esc or click outside to close.", muted_font, (165, 195, 230), None, True),
])
def _wrap_text(text, font, max_width):
words = text.split()
lines = []
current = ""
for word in words:
candidate = word if not current else f"{current} {word}"
if font.size(candidate)[0] <= max_width:
current = candidate
else:
if current:
lines.append(current)
current = word
if current:
lines.append(current)
return lines
wrapped_content = []
y = 20
max_width = help_panel_width - 40
line_gap = 8
section_gap = 12
for text, font, color, explicit_y, wrap in content:
if explicit_y is not None:
y = explicit_y
wrapped_lines = _wrap_text(text, font, max_width) if wrap else [text]
wrapped_content.append((wrapped_lines, font, color, y))
for wrapped_line in wrapped_lines:
y += font.get_linesize() + line_gap
y += section_gap
panel_height = y + 12
panel_x = help_button.rect.right - help_panel_width
panel_y = help_button.rect.bottom + 14
panel_y = min(panel_y, lis.SCREEN.get_height() - panel_height - 20)
help_panel_rect = pygame.Rect(panel_x, panel_y, help_panel_width, panel_height)
panel = pygame.Surface(help_panel_rect.size, pygame.SRCALPHA)
pygame.draw.rect(panel, (*_PANEL_FILL, 238), panel.get_rect(), border_radius=16)
pygame.draw.rect(panel, (*_PANEL_BORDER, 220), panel.get_rect(), 1, border_radius=16)
for wrapped_lines, font, color, y in wrapped_content:
for wrapped_line in wrapped_lines:
panel.blit(font.render(wrapped_line, True, color), (20, y))
y += font.get_linesize() + line_gap
lis.SCREEN.blit(panel, help_panel_rect.topleft)
return help_panel_rect
def _load_game_mode_position(game_mode_key, json_path, whoseturn):
nonlocal game_modes_modal_open, restore_default_setup_on_stop, pending_start_whoseturn, active_game_mode_key
_reset_board_for_game_mode_load()
loaded_position = load_position_from_json(json_path)
_apply_position_config(loaded_position["config"], fallback_whoseturn=whoseturn)
game_modes_modal_open = False
restore_default_setup_on_stop = False
active_game_mode_key = game_mode_key
def _load_sample_pgn(pgn_path):
nonlocal game_controller, game_modes_modal_open, pgn_games_modal_open, restore_default_setup_on_stop, pending_start_whoseturn, active_game_mode_key
cancel_pending_cpu_move()
start_objects.Dragging.dragging_all_false()
start_objects.Start.restart_start_positions()
if CpuController.cpu_mode:
CpuController.cpu_mode_toggle()
if SwitchModesController.GAME_MODE == SwitchModesController.PLAY_MODE:
stop_game()
game_controller = PgnWriterAndLoader.pgn_load_from_path(play_edit_switch_button, pgn_path)
game_modes_modal_open = False
pgn_games_modal_open = False
restore_default_setup_on_stop = game_controller is not None
pending_start_whoseturn = "white"
active_game_mode_key = None
def _save_position_with_starting_turn(selected_turn):
nonlocal pending_start_whoseturn
pending_start_whoseturn = _normalize_starting_turn(selected_turn)
pos_save_file(_current_position_config())
def _reset_game_mode_sections():
for section in game_mode_sections:
section["expanded"] = False
def _draw_save_position_modal():
nonlocal modal_panel_rect, modal_close_rect, save_turn_button_rects
_dim = pygame.Surface(lis.SCREEN.get_size(), pygame.SRCALPHA)
_dim.fill((5, 10, 24, 185))
lis.SCREEN.blit(_dim, (0, 0))
panel_w = 520
panel_h = 280
panel_x = (lis.SCREEN.get_width() - panel_w) // 2
panel_y = (lis.SCREEN.get_height() - panel_h) // 2
modal_panel_rect = pygame.Rect(panel_x, panel_y, panel_w, panel_h)
modal_close_rect = pygame.Rect(panel_x + panel_w - 52, panel_y + 14, 36, 36)
panel = pygame.Surface((panel_w, panel_h), pygame.SRCALPHA)
pygame.draw.rect(panel, (*_PANEL_FILL, 240), panel.get_rect(), border_radius=18)
pygame.draw.rect(panel, (*_PANEL_BORDER, 220), panel.get_rect(), 1, border_radius=18)
title_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 28, bold=True)
body_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 19)
option_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 22, bold=True)
detail_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 17)
close_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 22, bold=True)
title = title_font.render("Save Position", True, (242, 247, 255))
subtitle = body_font.render("Choose who should move first when this position is loaded.", True, (198, 216, 238))
panel.blit(title, (28, 24))
panel.blit(subtitle, (28, 64))
close_hovered = modal_close_rect.collidepoint(mousepos)
close_bg = (24, 50, 96, 210) if close_hovered else (16, 34, 72, 180)
close_border = (110, 150, 210, 230) if close_hovered else (82, 110, 158, 190)
close_local_rect = pygame.Rect(panel_w - 52, 14, 36, 36)
pygame.draw.rect(panel, close_bg, close_local_rect, border_radius=10)
pygame.draw.rect(panel, close_border, close_local_rect, 1, border_radius=10)
close_text = close_font.render("X", True, (242, 247, 255))
panel.blit(close_text, (close_local_rect.centerx - close_text.get_width() // 2,
close_local_rect.centery - close_text.get_height() // 2 - 1))
save_turn_button_rects = {}
options = (
("white", "White to move", "Save this setup with White starting."),
("black", "Black to move", "Save this setup with Black starting."),
)
button_w = panel_w - 56
button_h = 62
first_y = 112
gap = 18
for index, (turn_key, label, description) in enumerate(options):
local_rect = pygame.Rect(28, first_y + index * (button_h + gap), button_w, button_h)
absolute_rect = local_rect.move(panel_x, panel_y)
save_turn_button_rects[turn_key] = absolute_rect
hovered = absolute_rect.collidepoint(mousepos)
is_selected = pending_start_whoseturn == turn_key
btn_bg = (30, 66, 122, 230) if hovered or is_selected else (18, 42, 86, 192)
btn_border = (170, 214, 255, 235) if hovered or is_selected else (104, 142, 194, 190)
pygame.draw.rect(panel, btn_bg, local_rect, border_radius=12)
pygame.draw.rect(panel, btn_border, local_rect, 1, border_radius=12)
label_surf = option_font.render(label, True, (244, 248, 255))
desc_surf = detail_font.render(description, True, (188, 208, 232))
panel.blit(label_surf, (local_rect.x + 18, local_rect.y + 12))
panel.blit(desc_surf, (local_rect.x + 18, local_rect.y + 36))
lis.SCREEN.blit(panel, modal_panel_rect.topleft)
def _draw_game_modes_modal():
nonlocal modal_panel_rect, modal_close_rect, game_mode_button_rects, game_mode_section_rects
def _wrap_text_lines(text, font, max_width):
words = text.split()
if not words:
return [""]
lines = []
current_line = words[0]
for word in words[1:]:
candidate = f"{current_line} {word}"
if font.size(candidate)[0] <= max_width:
current_line = candidate
else:
lines.append(current_line)
current_line = word
lines.append(current_line)
return lines
_dim = pygame.Surface(lis.SCREEN.get_size(), pygame.SRCALPHA)
_dim.fill((5, 10, 24, 185))
lis.SCREEN.blit(_dim, (0, 0))
title_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 28, bold=True)
option_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 20, bold=True)
detail_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 16)
section_title_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 18, bold=True)
section_helper_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 15)
close_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 22, bold=True)
def _draw_mode_icon(target_surface, mode_key, emoji_text, icon_rect):
style_by_mode = {
"mate_in_1": ((118, 86, 20, 245), (255, 219, 122, 235)),
"mate_in_2": ((118, 86, 20, 245), (255, 219, 122, 235)),
"mate_in_3": ((118, 86, 20, 245), (255, 219, 122, 235)),
"mate_in_4": ((118, 86, 20, 245), (255, 219, 122, 235)),
"pawns_only": ((33, 87, 72, 240), (120, 218, 186, 225)),
"random_setup": ((67, 69, 138, 240), (165, 180, 255, 225)),
"chaos_setup": ((122, 64, 28, 240), (255, 184, 125, 225)),
"peasants_revolt": ((102, 56, 34, 240), (231, 194, 120, 225)),
"light_brigade": ((70, 76, 118, 240), (185, 201, 255, 225)),
}
badge_fill, badge_border = style_by_mode[mode_key]
pygame.draw.rect(target_surface, badge_fill, icon_rect, border_radius=12)
pygame.draw.rect(target_surface, badge_border, icon_rect, 1, border_radius=12)
if emoji_font is not None:
try:
icon_surface, icon_bounds = emoji_font.render(emoji_text)
except (OSError, pygame.error):
icon_surface = None
icon_bounds = None
if icon_surface is not None and icon_surface.get_width() > 0 and icon_surface.get_height() > 0:
icon_pos = (
icon_rect.centerx - icon_surface.get_width() // 2,
icon_rect.centery - icon_surface.get_height() // 2,
)
target_surface.blit(icon_surface, icon_pos)
return
fallback_labels = {
"mate_in_1": "P1",
"mate_in_2": "P2",
"mate_in_3": "P3",
"mate_in_4": "P4",
"pawns_only": "PA",
"random_setup": "RD",
"chaos_setup": "CH",
"peasants_revolt": "PR",
"light_brigade": "LB",
}
fallback_font = pygame.font.SysFont(initvar.UNIVERSAL_FONT_NAME, 13, bold=True)
fallback_surface = fallback_font.render(fallback_labels[mode_key], True, (242, 247, 255))
target_surface.blit(
fallback_surface,
(
icon_rect.centerx - fallback_surface.get_width() // 2,
icon_rect.centery - fallback_surface.get_height() // 2 - 1,
),
)
subtitle_lines = _wrap_text_lines(
"Load mate puzzles or quick variants, including a kings-and-pawns setup.",
detail_font,
428,
)
panel_w = 520
button_w = panel_w - 56
button_padding_top = 14
button_padding_bottom = 16
detail_y_offset = 40
description_line_height = 18
subtitle_y = 58 + (len(subtitle_lines) * 18)
first_y = subtitle_y + 18
section_gap = 16
card_gap = 14
section_header_h = 60
button_layout = []
section_layout = []
current_y = first_y
for section in game_mode_sections:
header_rect = pygame.Rect(28, current_y, button_w, section_header_h)
helper_lines = _wrap_text_lines(section["helper_text"], section_helper_font, button_w - 148)
section_layout.append((section, helper_lines, header_rect))
current_y = header_rect.bottom + 10
if section["expanded"]:
for mode_key, emoji_text, label, mode_type, mode_description, _, _ in section["modes"]:
description_lines = _wrap_text_lines(mode_description, detail_font, button_w - 96)
if mode_key in {"random_setup", "chaos_setup"}:
description_lines.append("Click again to regenerate.")
description_start_y = 40 if mode_type in {"Variant", "Puzzle"} else 58
bottom_padding = 8 if mode_type in {"Variant", "Puzzle"} else button_padding_bottom
button_h = button_padding_top + description_start_y + (len(description_lines) * description_line_height) + bottom_padding
local_rect = pygame.Rect(28, current_y, button_w, button_h)
button_layout.append((mode_key, emoji_text, label, mode_type, description_lines, local_rect))
current_y = local_rect.bottom + card_gap
current_y += section_gap
content_bottom = current_y - section_gap if section_layout else first_y
panel_h = max(420, content_bottom + 28)
panel_h = min(panel_h, lis.SCREEN.get_height() - 60)
panel_x = (lis.SCREEN.get_width() - panel_w) // 2
panel_y = (lis.SCREEN.get_height() - panel_h) // 2
modal_panel_rect = pygame.Rect(panel_x, panel_y, panel_w, panel_h)
modal_close_rect = pygame.Rect(panel_x + panel_w - 52, panel_y + 14, 36, 36)