-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlauncher.py
773 lines (690 loc) · 27.2 KB
/
launcher.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
"""Open pysimgame main menu.
This is the launcher script for the game.
The main menu loop.
"""
import os
import pathlib
import sys
from typing import Dict, List, Tuple, Union
import pygame
import pygame_gui
from pygame import display, mouse, time
from pygame_gui.elements import UIButton, UILabel, UITextEntryLine
from pygame_gui.ui_manager import UIManager
from pygame_gui.windows import UIColourPickerDialog
from pysimgame import PYSDGAME_SETTINGS
from pysimgame.game_manager import GameManager
from pysimgame.new_game import error_popup, get_available_games, import_game
from pysimgame.regions_display import RegionComponent, validate_regions_dict
from pysimgame.utils import logging
from pysimgame.utils.directories import THEMES_DIR, find_theme_file
from pysimgame.utils.dynamic_menu import UIColumnContainer, UIFormLayout
from pysimgame.utils.gui_utils import get_new_close_button, set_button_color
from pysimgame.utils.logging import logger
FPS = PYSDGAME_SETTINGS["FPS"]
pygame.init()
MAIN_DISPLAY = display.set_mode(PYSDGAME_SETTINGS["Resolution"])
BACK_GROUND_COLOR = "black"
CLOCK = time.Clock()
UI_MANAGER = UIManager(
PYSDGAME_SETTINGS["Resolution"],
theme_path=find_theme_file(PYSDGAME_SETTINGS["Themes"]["Main Menu"]),
)
REGIONS_DICT: Dict[str, RegionComponent] = {}
# A close button that can be used to return to the previous menu
CLOSE_BUTTON = get_new_close_button(UI_MANAGER)
CLOSE_BUTTON.hide() # Hidden for the main start
# Helpers for buttons positions
n_buttons = 3 # Number of buttons
x_size = PYSDGAME_SETTINGS["Resolution"][0]
y_size = PYSDGAME_SETTINGS["Resolution"][1]
x_center = int(x_size / 2)
button_width = x_size / 4
button_left = x_center - button_width / 2
y_positions = [(0.6 + i) * y_size / (n_buttons + 1) for i in range(n_buttons)]
button_height = y_size / 4 / n_buttons
buttons: List[UIButton] = []
##############################################
# Adds widgets buttons and their next loops
##############################################
buttons.append(
load_game_button := UIButton(
pygame.Rect(button_left, y_positions[0], button_width, button_height),
"Load Game",
UI_MANAGER,
tool_tip_text="Load an existing saved game.",
object_id="#main_menu_button",
)
)
buttons.append(
new_game_button := UIButton(
pygame.Rect(button_left, y_positions[1], button_width, button_height),
"New Game",
UI_MANAGER,
tool_tip_text="Create a new game.",
object_id="#main_menu_button",
)
)
buttons.append(
import_model_button := UIButton(
pygame.Rect(button_left, y_positions[2], button_width, button_height),
"Import Game Model",
UI_MANAGER,
tool_tip_text=(
"Import a new kind of game from a pysd compatible model file."
),
object_id="#main_menu_button",
)
)
def start_template_loop():
"""Use as a template for a loop function."""
continue_loop = True
while continue_loop:
time_delta = CLOCK.tick(PYSDGAME_SETTINGS["FPS"]) / 1000.0
events = pygame.event.get()
# Look for quit events
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.USEREVENT:
logger.debug(event)
UI_MANAGER.process_events(event)
# Handles the actions for pygame widgets
UI_MANAGER.update(time_delta)
# Draw methods
MAIN_DISPLAY.fill(BACK_GROUND_COLOR)
UI_MANAGER.draw_ui(MAIN_DISPLAY)
display.update()
def start_regions_loop(background_image_filepath: pathlib.Path = None):
"""Menu for selecting the region."""
continue_loop = True
FIRST_POINT: Tuple[int, int] = None
LEFT_WAS_PRESSED: bool = False
DRAW_MODE: bool = True # If the user is drawing smth
DRAWN_POINTS: List[Tuple] = []
REGIONS_UI_MANAGER = UIManager(
PYSDGAME_SETTINGS["Resolution"],
theme_path=find_theme_file(PYSDGAME_SETTINGS["Themes"]["Main Menu"]),
)
main_display_size = MAIN_DISPLAY.get_size()
menu_width = 200
name_width = 160
icons_width = 20
big_buttons_height = 60
# Surface to show the background image
background_surface = (
pygame.Surface(
(main_display_size[0] - menu_width, main_display_size[1])
)
if background_image_filepath is None
else pygame.image.load(background_image_filepath)
)
# Surface to show the regions on top of it
regions_surface = pygame.Surface(
background_surface.get_size(), pygame.SRCALPHA
)
background_anchor = (0, 0)
new_region_button = UIButton(
pygame.Rect(-menu_width, 0, menu_width, big_buttons_height),
"New Region",
REGIONS_UI_MANAGER,
tool_tip_text="Create a new region",
anchors={
"left": "right",
"right": "right",
"top": "top",
"bottom": "bottom",
},
)
stop_drawing_button = UIButton(
pygame.Rect(
-menu_width,
-2 * big_buttons_height,
menu_width,
big_buttons_height,
),
"Validate polygon",
REGIONS_UI_MANAGER,
tool_tip_text="Stop the current polygon drawing",
anchors={
"left": "right",
"right": "right",
"top": "bottom",
"bottom": "bottom",
},
)
stop_drawing_button.hide()
validate_regions_button = UIButton(
pygame.Rect(
-menu_width,
-big_buttons_height,
menu_width,
big_buttons_height,
),
"Validate regions",
REGIONS_UI_MANAGER,
anchors={
"left": "right",
"right": "right",
"top": "bottom",
"bottom": "bottom",
},
)
regions_container = UIColumnContainer(
pygame.Rect(
-menu_width,
big_buttons_height,
menu_width + 20,
MAIN_DISPLAY.get_size()[1] - big_buttons_height,
),
REGIONS_UI_MANAGER,
anchors={
"left": "right",
"right": "right",
"top": "top",
"bottom": "bottom",
},
object_id="regions_container",
)
# Add something to remeber the components
regions_container.component_rows = []
def _add_region_line(region_component: RegionComponent = None):
if region_component is None:
# Create a region component
name = "Region {}"
i = 0
# Ensure the name is not already present
while name.format(i) in REGIONS_DICT:
i += 1
# Find optimal equidistant triangle using x = sqrt(3)/2*y
# (0,0), (x, 0), (x/2, y)
region_component = RegionComponent(
regions_surface,
pygame.Color(255, 0, 0),
name=name.format(i),
)
# Text Box for the region's name
region_component.text_box = UITextEntryLine(
pygame.Rect(0, 0, name_width, 30),
REGIONS_UI_MANAGER,
container=regions_container,
)
region_component.text_box.set_text(region_component.name)
region_component.text_box.region_component = region_component
# Button for region's color selection
region_component.color_button = UIButton(
pygame.Rect(name_width, 0, icons_width, 30),
"",
REGIONS_UI_MANAGER,
container=regions_container,
object_id="color_button",
)
# Button for adding polygon
region_component.new_button = UIButton(
pygame.Rect(name_width + icons_width, 0, icons_width, 30),
"+",
REGIONS_UI_MANAGER,
container=regions_container,
object_id="new_poly_button",
)
# Set the color of the button to the one of the region
set_button_color(region_component.color_button, region_component.color)
region_component.color_button.region_component = region_component
region_component.new_button.region_component = region_component
REGIONS_DICT[region_component.name] = region_component
regions_container.add_row(
region_component.text_box,
region_component.color_button,
region_component.new_button,
)
for region in REGIONS_DICT.values():
# Add existing regions
_add_region_line(region)
# Also set the surface for drawing
region.surface = regions_surface
while continue_loop:
time_delta = CLOCK.tick(PYSDGAME_SETTINGS["FPS"]) / 1000.0
events = pygame.event.get()
# Look for quit events
for event in events:
REGIONS_UI_MANAGER.process_events(event)
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
if event.ui_element == new_region_button:
# Add a new region to be drawn
_add_region_line()
elif event.ui_element == stop_drawing_button:
# Exit the draw mode
DRAW_MODE = False
# Change available button settings
stop_drawing_button.hide()
validate_regions_button.show()
elif event.ui_element == validate_regions_button:
# Register whether the regions chosen are a valid set
valid_set = validate_regions_dict(REGIONS_DICT)
# Create a new dict to store the regions
if valid_set:
# Register the region
new_REGIONS_DICT = {
region.name: region
for region in REGIONS_DICT.values()
}
# Assign the regions to the MAIN dict
REGIONS_DICT.clear()
for key, item in new_REGIONS_DICT.items():
REGIONS_DICT[key] = item
# finish start_regions_loop
return
else: # Not valid
# Problems will already be displayed
# by validate_regions_dict()
# TODO could indicate in the UI what to change
pass
elif (
event.ui_object_id == "regions_container.color_button"
):
# Start a color selection window
color_picker = UIColourPickerDialog(
pygame.Rect(160, 50, 420, 400),
REGIONS_UI_MANAGER,
window_title="Change Colour of {}".format(
event.ui_element.region_component.name
),
initial_colour=pygame.Color(255, 0, 0),
)
color_picker.region = event.ui_element.region_component
elif (
event.ui_object_id
== "regions_container.new_poly_button"
):
# Start to draw a polygon
DRAW_MODE = True
FIRST_POINT = None
event.ui_element.region_component.polygons.append(
[] # New list to store the new polygon
)
# Current polygon points to that list
DRAWN_POINTS = (
event.ui_element.region_component.polygons[-1]
)
stop_drawing_button.show()
validate_regions_button.hide()
elif (
event.user_type
== pygame_gui.UI_COLOUR_PICKER_COLOUR_PICKED
):
event.ui_element.region.color = event.colour
set_button_color(
event.ui_element.region.color_button,
event.colour,
)
elif event.user_type == pygame_gui.UI_TEXT_ENTRY_CHANGED:
text_entry: UITextEntryLine = event.ui_element
text_entry.region_component.name = text_entry.get_text()
if DRAW_MODE:
# Finds out user mouse movement
LEFT_PRESSED = mouse.get_pressed()[0] # 0 is left button
if not LEFT_PRESSED and LEFT_WAS_PRESSED: # Release
# Add the point to polygon
position = mouse.get_pos()
if FIRST_POINT is None:
FIRST_POINT = position
bg_size = regions_surface.get_size()
if position[0] > bg_size[0] or position[1] > bg_size[1]:
pass # out of the drawing screen
else:
# Add the click position to the drawn polygon
DRAWN_POINTS.append(position)
LEFT_WAS_PRESSED = LEFT_PRESSED
# Handles the actions for pygame widgets
REGIONS_UI_MANAGER.update(time_delta)
# Draw methods
MAIN_DISPLAY.fill(BACK_GROUND_COLOR)
MAIN_DISPLAY.blit(background_surface, background_anchor)
regions_surface.fill(pygame.Color(255, 255, 255, 0))
for key, region in REGIONS_DICT.items():
region.show()
MAIN_DISPLAY.blit(regions_surface, background_anchor)
REGIONS_UI_MANAGER.draw_ui(MAIN_DISPLAY)
display.update()
def start_newgame_loop() -> None:
"""Start a loop for the new game menu.
Will never return if a new game starts, unless the player chooses to
return to main menu.
"""
continue_loop = True
CLOSE_BUTTON.show()
available_games_container = UIColumnContainer(
pygame.Rect(x_size / 3, y_size / 3, x_size / 3, y_size / 2),
UI_MANAGER,
object_id="#games_container",
)
for game in get_available_games():
available_games_container.add_row(
button := UIButton(
pygame.Rect(0, 0, x_size / 4, 50),
game,
UI_MANAGER,
container=available_games_container,
object_id="gamename_button",
)
)
button.game = game
start_button = UIButton(
pygame.Rect(x_size / 3, y_size / 3, x_size / 3, y_size / 5),
"START",
UI_MANAGER,
)
start_button.hide()
while continue_loop:
time_delta = CLOCK.tick(PYSDGAME_SETTINGS["FPS"]) / 1000.0
events = pygame.event.get()
# Look for quit events
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
if event.ui_element == CLOSE_BUTTON:
CLOSE_BUTTON.hide()
available_games_container.hide()
del available_games_container
return None
if event.ui_element == start_button:
# Start the game
CLOSE_BUTTON.hide()
start_button.hide()
del start_button
game_manager = GameManager()
game_manager.start_new_game(_selected_game)
logging.debug("game finished, returning to menu")
del game_manager
return
if (
event.ui_object_id
== "#games_container.gamename_button"
):
_selected_game = event.ui_element.game
available_games_container.hide()
start_button.show()
else:
logger.info("Pressed {}".format(event))
UI_MANAGER.process_events(event)
# Handles the actions for pygame widgets
UI_MANAGER.update(time_delta)
# Draw methods
MAIN_DISPLAY.fill(BACK_GROUND_COLOR)
UI_MANAGER.draw_ui(MAIN_DISPLAY)
display.update()
def start_import_model_loop() -> Union[str, None]:
"""Game loop for importing new model.
:return: The name of the imported game or None if no game was imported
"""
continue_loop = True
UI_MANAGER = UIManager(
MAIN_DISPLAY.get_size(),
theme_path=find_theme_file(PYSDGAME_SETTINGS["Themes"]["Main Menu"]),
)
layout = UIFormLayout(MAIN_DISPLAY.get_rect(), UI_MANAGER)
layout.add_row("Import New Model")
layout.add_row("") # Empty row
layout.add_row("") # Empty row
layout.add_row("From Local Files")
layout.add_row("") # Empty row
layout.add_row(
"Game Name",
game_name_entry := UITextEntryLine(
pygame.Rect(0, 0, 100, 100),
UI_MANAGER,
container=layout,
parent_element=layout,
),
)
layout.add_row(
"Model File Path",
model_file_name_entry := UILabel(
pygame.Rect(0, 0, 100, 100),
"",
UI_MANAGER,
container=layout,
parent_element=layout,
),
choose_model_file_button := UIButton(
pygame.Rect(0, 0, 100, 100),
"Choose Model File",
UI_MANAGER,
container=layout,
parent_element=layout,
),
)
model_filepath = None
layout.add_row(
"Custom Theme File Path",
file_name_entry := UILabel(
pygame.Rect(0, 0, 100, 100),
"",
UI_MANAGER,
container=layout,
parent_element=layout,
),
choose_theme_file_button := UIButton(
pygame.Rect(0, 0, 100, 100),
"Choose Theme File",
UI_MANAGER,
container=layout,
parent_element=layout,
),
)
theme_filepath = None
layout.add_row(
"Background Image",
background_file_name_entry := UILabel(
pygame.Rect(0, 0, 100, 100),
"",
UI_MANAGER,
container=layout,
parent_element=layout,
),
choose_background_file_button := UIButton(
pygame.Rect(0, 0, 100, 100),
"Choose Image",
UI_MANAGER,
container=layout,
parent_element=layout,
),
)
background_filepath = None
layout.add_row(
"Regions",
define_regions_button := UIButton(
pygame.Rect(0, 0, 100, 100),
"Define",
UI_MANAGER,
container=layout,
parent_element=layout,
),
)
layout.add_row("") # Empty row
layout.add_row("Download")
layout.add_row("") # Empty row
layout.add_row("Not Available Yet")
launch_import_button = UIButton(
pygame.Rect(-250, -150, 200, 100),
"Launch Import",
UI_MANAGER,
tool_tip_text="Will try to import the model into pysimgame",
anchors={
"left": "right",
"right": "right",
"top": "bottom",
"bottom": "bottom",
},
object_id="#launch_import_button",
starting_height=1000, # Ensure will show on top of the others
)
close_button = get_new_close_button(UI_MANAGER)
while continue_loop:
time_delta = CLOCK.tick(PYSDGAME_SETTINGS["FPS"]) / 1000.0
events = pygame.event.get()
# Look for quit events
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
if event.ui_element == choose_model_file_button:
# Choose the file
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
model_filepath = pathlib.Path(
filedialog.askopenfilename(
filetypes=[
("Vensim Model", "*.mdl"),
("Python PySD", "*.py"),
("XMILE", "*.xmile"),
("All Files", "*.*"),
],
title="Choose Model File",
initialdir=os.environ["HOMEPATH"],
)
)
if os.path.isfile(model_filepath):
# Show the file name selected
model_file_name_entry.set_text(model_filepath.name)
elif event.ui_element == choose_theme_file_button:
# Choose the file
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
theme_filepath = pathlib.Path(
filedialog.askopenfilename(
filetypes=[
("Pygamegui theme file", "*.json"),
("All Files", "*.*"),
],
title="Choose Theme File",
initialdir=THEMES_DIR,
)
)
if os.path.isfile(theme_filepath):
# Show the file name selected
file_name_entry.set_text(theme_filepath.stem)
elif event.ui_element == choose_background_file_button:
# Choose the file
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
background_filepath = pathlib.Path(
filedialog.askopenfilename(
filetypes=[
(
"Image Formats Supported by Pygame",
[
"*.jpg",
"*.jpeg",
"*.png",
"*.gif",
"*.bmp",
"*.pcx",
"*.tga",
"*.tif",
"*.lbm",
"*.pbm",
"*.ppm",
"*.xpm",
],
),
("All Files", "*.*"),
],
title="Choose Theme File",
initialdir=os.environ["HOMEPATH"],
)
)
if os.path.isfile(background_filepath):
# Show the file name selected
background_file_name_entry.set_text(
background_filepath.name
)
elif event.ui_element == define_regions_button:
start_regions_loop(theme_filepath)
# Change the name of the button, now that the
# regions have been assigned
define_regions_button.set_text("Overwrite")
logger.debug(
"Regions defined: {}".format(REGIONS_DICT)
)
elif event.ui_element == close_button:
return None
elif event.ui_element == launch_import_button:
try:
game_name = game_name_entry.get_text()
logger.info("[START] Import new game.")
import_game(
game_name,
model_filepath,
REGIONS_DICT,
)
except Exception as exception:
# Could not create the new game
# Pop the error message to the user
error_popup(exception)
# Log the exception
logger.error("[FAILED] Import new game.")
logger.exception(exception)
else:
# Game was created normally
logger.info(
"[SUCCESS] Imported new game: {}.".format(
game_name
)
)
# Remove the UI Manager of this loop
del UI_MANAGER
return game_name # Exit the import game loop
UI_MANAGER.process_events(event)
# Handles the actions for pygame widgets
UI_MANAGER.update(time_delta)
# Draw methods
MAIN_DISPLAY.fill(BACK_GROUND_COLOR)
UI_MANAGER.draw_ui(MAIN_DISPLAY)
display.update()
##############################################
# Starts the game main loop
##############################################
while True:
time_delta = CLOCK.tick(PYSDGAME_SETTINGS["FPS"]) / 1000.0
events = pygame.event.get()
# Look for quit events
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
for button in buttons:
button.hide()
if event.ui_element == load_game_button:
logger.info("Hello load_game_button!")
if event.ui_element == new_game_button:
start_newgame_loop()
if event.ui_element == import_model_button:
start_import_model_loop()
for button in buttons:
button.show()
UI_MANAGER.process_events(event)
# Handles the actions for pygame widgets
UI_MANAGER.update(time_delta)
# Draw methods
MAIN_DISPLAY.fill(BACK_GROUND_COLOR)
UI_MANAGER.draw_ui(MAIN_DISPLAY)
display.update()