Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
787 lines (588 loc) · 25.9 KB
/
Copy pathmain.py
File metadata and controls
787 lines (588 loc) · 25.9 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
# Set DPI awareness before SDL/Pygame creates a window on Windows.
import sys
if sys.platform == "win32":
try:
import ctypes
ctypes.windll.shcore.SetProcessDpiAwareness(2) # per-monitor DPI aware
except (AttributeError, OSError, ValueError):
try:
ctypes.windll.user32.SetProcessDPIAware()
except (AttributeError, OSError):
pass
import pygame
import json
from pathlib import Path
from engine.game import Game
from engine.ai.basic_ai import BasicAI
from engine.ai.learning_ai import LearningAI
from engine.ai.advanced_ai import AdvancedAI
from ui.renderer import Renderer
from ui.input_manager import InputManager
from ui.menu_state import MenuState
from ui.menu_renderer import MenuRenderer
from network.multiplayer_client import MultiplayerClient
from network.client_game_adapter import ClientGameAdapter
from network.live_sync import LiveSync
from ui.multiplayer_hud import MultiplayerHUD
from ui.multiplayer_result import MultiplayerResult
pygame.init()
WIDTH, HEIGHT = 1200, 900
# Render the existing fixed-coordinate UI to a virtual canvas. The actual
# decorated Windows window can resize independently without clipping the board.
from ui.viewport import Viewport
from ui.native_scene import draw_native_scene
from ui.native_overlays import draw_multiplayer_hud, draw_match_result
ICON_PATH = Path(__file__).resolve().parent / "logo/logo.png"
if ICON_PATH.is_file():
creator_icon = pygame.image.load(str(ICON_PATH))
pygame.display.set_icon(creator_icon)
else:
print(f"Creator icon not found: {ICON_PATH}")
viewport = Viewport(WIDTH, HEIGHT)
window = pygame.display.set_mode(viewport.initial_size(), pygame.RESIZABLE)
screen = pygame.Surface((WIDTH, HEIGHT)).convert()
pygame.display.set_caption("Creator")
icon_path = Path(__file__).resolve().parent / "logo/logo.png"
if icon_path.exists():
icon_surface = pygame.image.load(str(icon_path))
pygame.display.set_icon(icon_surface)
menu_state = MenuState()
# Menu is rasterized directly at its final pixel size, not scaled as a bitmap.
menu_surface = pygame.Surface((WIDTH, HEIGHT)).convert()
menu_renderer = MenuRenderer(menu_surface, menu_state)
game = None
renderer = None
input_manager = None
multiplayer = None
network_game = None
network_renderer = None
network_input_manager = None
network_selected_pawn_id = None
network_sync = None
multiplayer_hud = MultiplayerHUD(screen)
multiplayer_result = MultiplayerResult(screen)
clock = pygame.time.Clock()
running = True
ai_turn_delay_ms = 1500
last_ai_step_time = 0
last_lobby_poll = 0
lobby_poll_interval_ms = 500
def start_game():
global game, renderer, input_manager, last_ai_step_time
global network_game, network_renderer
global network_input_manager, network_selected_pawn_id
global network_sync
network_game = None
network_renderer = None
network_input_manager = None
network_selected_pawn_id = None
network_sync = None
last_ai_step_time = pygame.time.get_ticks()
ai_controller = None
if menu_state.selected_mode == "AI":
if menu_state.selected_difficulty == "EASY":
ai_controller = BasicAI(team="RED")
elif menu_state.selected_difficulty == "LEARNING":
ai_controller = LearningAI(team="RED")
elif menu_state.selected_difficulty == "ADVANCED":
ai_controller = AdvancedAI(team="RED")
game = Game(ai_controller=ai_controller)
if menu_state.selected_pattern:
pattern_file = (
Path(__file__).resolve().parent
/ "patterns"
/ menu_state.selected_pattern
)
if pattern_file.exists():
with open(pattern_file, "r") as f:
data = json.load(f)
game.pattern.name = data["name"]
game.pattern.size = data["size"]
game.pattern.grid = data["grid"]
renderer = Renderer(screen, game)
input_manager = InputManager(renderer)
menu_state.current_state = MenuState.IN_GAME
def start_network_game():
global game, renderer, input_manager
global network_game, network_renderer
global network_input_manager, network_selected_pawn_id
global network_sync
if multiplayer is None:
return False
response = multiplayer.get_state()
if (
response is None
or response.get("type") != "GAME_STATE"
):
return False
game = None
renderer = None
input_manager = None
network_game = ClientGameAdapter(
multiplayer.game_state
)
network_renderer = Renderer(
screen,
network_game
)
network_input_manager = InputManager(
network_renderer
)
network_selected_pawn_id = None
network_sync = LiveSync(
multiplayer,
network_game,
interval_ms=500
)
menu_state.current_state = MenuState.IN_GAME
return True
def refresh_network_game():
global network_selected_pawn_id
if network_game is None:
return
network_game.refresh()
network_selected_pawn_id = None
if network_sync is not None:
network_sync.acknowledge_local_update()
def network_roll():
if multiplayer is None or network_game is None:
return False
if network_game.game_over or (multiplayer.room_status or {}).get("paused"):
return False
if network_game.current_player is None:
return False
if network_game.current_player.team != multiplayer.team:
return False
if (
multiplayer.game_state.turn_phase
!= "WAITING_FOR_ROLL"
):
return False
response = multiplayer.roll()
if (
response is None
or response.get("type") != "GAME_STATE"
):
return False
refresh_network_game()
return True
while running:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.VIDEORESIZE:
window = pygame.display.set_mode((max(640, event.w), max(480, event.h)), pygame.RESIZABLE)
viewport.resize(window.get_size())
continue
if event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP, pygame.MOUSEMOTION):
event = viewport.translate_event(event)
if event is None:
continue
if event.type == pygame.QUIT:
running = False
elif menu_state.current_state != MenuState.IN_GAME:
if event.type == pygame.KEYDOWN and event.key == pygame.K_h:
menu_state.show_help = not menu_state.show_help
continue
if menu_state.show_help:
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
menu_state.show_help = False
continue
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
if menu_state.current_state in (MenuState.AI_PATTERN,):
menu_state.current_state = MenuState.AI_DIFFICULTY
elif menu_state.current_state in (MenuState.ROOM_PATTERN, MenuState.ROOM_JOIN):
menu_state.current_state = MenuState.ROOM_CHOICE
else:
if multiplayer is not None:
multiplayer.disconnect()
multiplayer = None
menu_state.reset()
menu_state.status_message = ""
continue
if event.type == pygame.MOUSEBUTTONDOWN:
pos = event.pos
for btn_key, rect in menu_renderer.buttons.items():
if not rect.collidepoint(pos):
continue
if btn_key == "BACK":
if menu_state.current_state in (
MenuState.AI_DIFFICULTY,
MenuState.ROOM_CHOICE,
MenuState.LOBBY_WAITING,
):
if multiplayer is not None:
multiplayer.disconnect()
multiplayer = None
menu_state.reset()
elif (
menu_state.current_state
== MenuState.AI_PATTERN
):
menu_state.current_state = (
MenuState.AI_DIFFICULTY
)
elif menu_state.current_state in (
MenuState.ROOM_PATTERN,
MenuState.ROOM_JOIN,
):
menu_state.current_state = (
MenuState.ROOM_CHOICE
)
break
if btn_key == "MODE_ONLINE":
menu_state.status_message = "Global matchmaking is not available yet. Choose AI or Friend Room."
elif btn_key == "MODE_AI":
menu_state.status_message = ""
menu_state.selected_mode = "AI"
menu_state.current_state = (
MenuState.AI_DIFFICULTY
)
elif btn_key == "MODE_FRIEND ROOM":
menu_state.status_message = ""
menu_state.selected_mode = "ROOM"
menu_state.current_state = (
MenuState.ROOM_CHOICE
)
elif btn_key.startswith("DIFF_"):
menu_state.selected_difficulty = (
btn_key.replace("DIFF_", "")
)
menu_state.current_state = (
MenuState.AI_PATTERN
)
elif btn_key == "ROOM_CREATE":
menu_state.room_action = "CREATE"
menu_state.current_state = (
MenuState.ROOM_PATTERN
)
elif btn_key == "ROOM_JOIN":
menu_state.room_action = "JOIN"
menu_state.current_state = (
MenuState.ROOM_JOIN
)
elif btn_key.startswith("CATEGORY_"):
menu_state.pattern_category = btn_key.replace("CATEGORY_", "")
menu_state.pattern_page = 0
candidates = [f for f in menu_state.available_patterns
if menu_state.pattern_category_for(f) == menu_state.pattern_category]
if candidates:
menu_state.selected_pattern = candidates[0]
elif btn_key.startswith("PAGE_"):
candidates = [f for f in menu_state.available_patterns
if menu_state.pattern_category_for(f) == menu_state.pattern_category]
pages = max(1, (len(candidates) + 19) // 20)
delta = -1 if btn_key == "PAGE_PREV" else 1
menu_state.pattern_page = max(0, min(pages - 1, menu_state.pattern_page + delta))
elif btn_key.startswith("PATTERN_"):
menu_state.selected_pattern = (
btn_key.replace("PATTERN_", "")
)
elif btn_key == "CONFIRM_START":
if menu_state.selected_mode == "AI":
start_game()
elif (
menu_state.selected_mode == "ROOM"
and menu_state.room_action == "CREATE"
):
multiplayer = MultiplayerClient()
if multiplayer.connect():
response = multiplayer.create_room()
if (
response is not None
and response.get("type")
== "ROOM_JOINED"
):
selection = multiplayer.set_pattern(menu_state.selected_pattern)
if not selection or selection.get("type") != "LOBBY_STATE":
menu_state.status_message = "Could not set room pattern: " + str((selection or {}).get("data", {}).get("message", "network error"))
multiplayer.disconnect()
multiplayer = None
continue
menu_state.room_code_input = (
multiplayer.room_code
)
menu_state.current_state = (
MenuState.LOBBY_WAITING
)
else:
menu_state.status_message = (response or {}).get("message", "Could not create room. Check the server.")
multiplayer.disconnect()
multiplayer = None
else:
menu_state.status_message = "Cannot connect to the multiplayer server. Start it first."
multiplayer = None
else:
menu_state.current_state = (
MenuState.LOBBY_WAITING
)
elif btn_key == "SUBMIT_JOIN":
if len(menu_state.room_code_input) == 6:
multiplayer = MultiplayerClient()
if multiplayer.connect():
response = multiplayer.join_room(
menu_state.room_code_input
)
if (
response is not None
and response.get("type")
== "ROOM_JOINED"
):
if multiplayer.get_lobby() and multiplayer.lobby_state:
menu_state.selected_pattern = multiplayer.lobby_state.get("pattern_file")
menu_state.room_code_input = (
multiplayer.room_code
)
menu_state.current_state = (
MenuState.LOBBY_WAITING
)
else:
menu_state.status_message = (response or {}).get("message", "Room not found or unavailable.")
multiplayer.disconnect()
multiplayer = None
else:
menu_state.status_message = "Cannot connect to the multiplayer server. Start it first."
multiplayer = None
elif btn_key == "TOGGLE_READY":
if multiplayer is not None and multiplayer.lobby_state:
team_info = multiplayer.lobby_state["players"][multiplayer.team]
response = multiplayer.set_ready(not team_info["ready"])
if response and response.get("type") == "LOBBY_STATE":
menu_state.lobby_data = multiplayer.lobby_state
elif btn_key == "LAUNCH_GAME":
if (
menu_state.selected_mode == "ROOM"
and multiplayer is not None
):
start_network_game()
else:
start_game()
break
elif (
event.type == pygame.KEYDOWN
and menu_state.current_state == MenuState.ROOM_JOIN
):
if event.key == pygame.K_BACKSPACE:
menu_state.room_code_input = (
menu_state.room_code_input[:-1]
)
elif (
len(menu_state.room_code_input) < 6
and event.unicode.isalnum()
):
menu_state.room_code_input += (
event.unicode.upper()
)
else:
# -----------------------------------------
# NETWORK GAMEPLAY
# -----------------------------------------
if network_game is not None:
if event.type == pygame.MOUSEBUTTONDOWN:
if network_game.game_over:
if multiplayer_result.menu_button.collidepoint(event.pos):
multiplayer.disconnect()
multiplayer = None
network_game = None
network_renderer = None
network_input_manager = None
network_sync = None
network_selected_pawn_id = None
menu_state.reset()
elif multiplayer_result.rematch_button.collidepoint(event.pos):
status = multiplayer.room_status or {}
if not status.get("paused"):
current_vote = status.get("rematch", {}).get(multiplayer.team, False)
multiplayer.set_rematch(not current_vote)
continue
if (multiplayer.room_status or {}).get("paused"):
continue
if (
network_game.current_player is None
or network_game.current_player.team
!= multiplayer.team
):
continue
phase = multiplayer.game_state.turn_phase
if (
phase == "WAITING_FOR_ROLL"
and network_renderer.dice_button.collidepoint(
event.pos
)
):
network_roll()
continue
cell = network_input_manager.get_clicked_cell(
event.pos
)
if cell is None:
continue
row, col = cell
if phase not in (
"WAITING_FOR_SELECTION",
"WAITING_FOR_MOVE",
):
continue
clicked_pawn = network_game.board.get_pawn(
row,
col
)
if (
clicked_pawn is not None
and clicked_pawn.team == multiplayer.team
and clicked_pawn.active
):
network_selected_pawn_id = clicked_pawn.id
network_game.selected_pawn = clicked_pawn
continue
if network_selected_pawn_id is not None:
if (
row,
col
) in network_game.get_valid_moves():
response = multiplayer.move(
pawn_id=network_selected_pawn_id,
row=row,
col=col
)
if (
response is not None
and response.get("type")
== "GAME_STATE"
):
refresh_network_game()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
network_roll()
elif event.key == pygame.K_r:
if network_sync.poll(force=True):
network_selected_pawn_id = None
continue
# -----------------------------------------
# LOCAL / AI GAMEPLAY
# -----------------------------------------
if event.type == pygame.MOUSEBUTTONDOWN:
if game.game_over:
if renderer.rematch_button.collidepoint(
event.pos
):
start_game()
continue
if renderer.menu_button.collidepoint(
event.pos
):
game = None
renderer = None
input_manager = None
menu_state.reset()
continue
continue
ai_turn = (
game.ai_controller is not None
and game.current_player.team
== game.ai_controller.team
)
if ai_turn:
continue
if renderer.dice_button.collidepoint(
event.pos
):
game.roll_dice()
continue
cell = input_manager.get_clicked_cell(
event.pos
)
if cell is not None:
row, col = cell
game.handle_click(row, col)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
ai_turn = (
game.ai_controller is not None
and game.current_player.team
== game.ai_controller.team
)
if not game.game_over and not ai_turn:
game.roll_dice()
elif event.key == pygame.K_ESCAPE:
game = None
renderer = None
input_manager = None
menu_state.reset()
# -----------------------------------------
# RENDERING
# -----------------------------------------
if (
menu_state.current_state == MenuState.LOBBY_WAITING
and menu_state.selected_mode == "ROOM"
and multiplayer is not None
and current_time - last_lobby_poll >= lobby_poll_interval_ms
):
last_lobby_poll = current_time
try:
response = multiplayer.get_lobby()
if response and response.get("type") == "LOBBY_STATE":
menu_state.lobby_data = multiplayer.lobby_state
menu_state.lobby_team = multiplayer.team
if multiplayer.lobby_state.get("started"):
start_network_game()
except (OSError, ConnectionError, TimeoutError):
pass
if menu_state.current_state != MenuState.IN_GAME:
viewport.resize(window.get_size())
menu_w = max(1, round(WIDTH * viewport.scale))
menu_h = max(1, round(HEIGHT * viewport.scale))
if menu_surface.get_size() != (menu_w, menu_h):
menu_surface = pygame.Surface((menu_w, menu_h)).convert()
menu_renderer.set_display_surface(menu_surface, viewport.scale)
menu_renderer.draw()
window.fill((8, 16, 26))
window.blit(menu_surface, viewport.offset)
else:
if network_game is not None:
if network_sync is not None:
changed = network_sync.poll()
if changed:
network_selected_pawn_id = None
network_renderer.draw()
multiplayer_hud.draw(
multiplayer,
network_game,
network_sync
)
multiplayer_result.draw(multiplayer, network_game)
else:
if (
game.ai_controller is not None
and not game.game_over
and game.current_player.team
== game.ai_controller.team
):
if (
current_time - last_ai_step_time
>= ai_turn_delay_ms
):
game.step_ai()
last_ai_step_time = current_time
renderer.draw()
if menu_state.current_state == MenuState.IN_GAME:
viewport.resize(window.get_size())
active_renderer = network_renderer if network_game is not None else renderer
active_game = network_game if network_game is not None else game
window.fill((8, 16, 26))
if active_game is not None and not active_game.game_over:
draw_native_scene(window, viewport, active_renderer)
if network_game is not None:
draw_multiplayer_hud(window, viewport, multiplayer, network_game, network_sync)
else:
# Draw the finished board underneath the result, then render the
# result panel and typography directly at physical resolution.
# The legacy result overlay is fully covered by the new overlay.
viewport.present(screen, window)
if active_game is not None:
draw_match_result(window, viewport, active_game, active_renderer,
multiplayer if network_game is not None else None)
pygame.display.flip()
clock.tick(60)
if multiplayer is not None:
multiplayer.disconnect()
pygame.quit()