-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
290 lines (241 loc) · 9.42 KB
/
main.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
import time
import traceback
import sys
from enum import Enum
import os
import glob
import random
import pygame
from assets import ASSETS_DIR
from hiscore_menu import init_hiscore_menu
from screens import game_screen, SIZE, lose_screen, win_screen, MainMenuGUI
from react import GameEngine
from scores import ScoreRepository
## Mock GPIO
# from gpiozero import Device
# from gpiozero.pins.mock import MockFactory
#
# Device.pin_factory = MockFactory()
##
from settings_menu import init_settings_menu
clock = pygame.time.Clock()
FPS = 30
GAME_TIME = 30
HISCORE_THRESHOLD = 5
SCORE_FILE = "scores.json"
class GAME_MODE(Enum):
MAIN_MENU = 1
INITGAME = 2
GAME = 3
POSTGAME = 4
class GameContext:
def __init__(self, current_mode: GAME_MODE):
self.current_mode = current_mode
def on_click(
main_menu: MainMenuGUI, game_engine, game_ctx, score_repo: ScoreRepository
):
click_pos = pygame.mouse.get_pos()
print("on_click", click_pos)
categories_highest_score = score_repo.get_highest_scores_by_cat
game_category = None
if game_ctx.current_mode == GAME_MODE.MAIN_MENU:
game_category = main_menu.selected_category_box(click_pos)
if game_category:
game_ctx.current_mode = GAME_MODE.INITGAME
pygame.display.flip()
else:
showmainscreen_cb = lambda: show_mainscreen(
game_engine, categories_highest_score
)
if main_menu.clicked_hiscores(click_pos) or main_menu.clicked_recent_scores(
click_pos
):
rank_by_hiscore = main_menu.clicked_hiscores(click_pos)
sorted_scores = (
score_repo.ranked_user_scores
if rank_by_hiscore
else score_repo.recent_user_scores
)
menu = init_hiscore_menu(
on_close_cb=showmainscreen_cb, hiscores=sorted_scores
)
menu.mainloop(
surface=screen,
disable_loop=False,
fps_limit=30,
)
pygame.display.flip()
elif main_menu.clicked_settings(click_pos):
game_engine.stop_idle()
menu = init_settings_menu(
on_close_cb=showmainscreen_cb, game_engine=game_engine
)
menu.mainloop(
surface=screen,
disable_loop=False,
fps_limit=30,
)
pygame.display.flip()
elif game_ctx.current_mode == GAME_MODE.POSTGAME:
game_ctx.current_mode = GAME_MODE.MAIN_MENU
game_category = None
show_mainscreen(game_engine, categories_highest_score)
return game_category
def show_mainscreen(game_engine, categories_highest_score) -> MainMenuGUI:
print("show_mainscreen")
game_engine.start_idle()
main_menu = MainMenuGUI(categories_highest_score)
main_menu.draw(screen)
print("out of show_mainscreen")
return main_menu
def play_music(mp3_path: str) -> None:
print(f"Playing {mp3_path}...")
if os.path.exists(mp3_path):
pygame.mixer.music.load(mp3_path)
pygame.mixer.music.play()
print("done playing music")
else:
print(f"fake play music {mp3_path}")
def play_random_music_from_dir(sound_dir):
sounds = glob.glob(os.path.join(sound_dir, "*.wav"))
play_music(random.choice(sounds))
def main():
run_button_thread = bool(int(os.environ.get("BUTTON_THREAD", 0)))
_disabled_btn_idx = os.environ.get("DISABLED_BTN")
disabled_btn_idx = int(_disabled_btn_idx) if _disabled_btn_idx else None
game_ctx = GameContext(current_mode=GAME_MODE.MAIN_MENU)
score_repo = ScoreRepository(filepath=SCORE_FILE, backup_files=False)
game_engine = GameEngine(game_time=GAME_TIME, disabled_btn_idx=disabled_btn_idx)
main_menu = show_mainscreen(
game_engine, categories_highest_score=score_repo.get_highest_scores_by_cat
)
game_category = None
print("start main while loop")
prev_mode = game_ctx.current_mode
played_boxing_bell = False
while True:
clock.tick(FPS)
if prev_mode != game_ctx.current_mode:
print(f"SWITCHED TO MODE {game_ctx.current_mode}")
prev_mode = game_ctx.current_mode
if game_ctx.current_mode == GAME_MODE.INITGAME:
# Game waiting for user hitting the first button
played_boxing_bell = False
game_engine.stop_idle()
print("game_screen")
highest_cat_user_score = score_repo.get_highest_scores_by_cat[game_category]
game_screen(
screen,
GAME_TIME,
0,
highest_cat_user_score,
overall_champion=score_repo.overall_champion,
wait=True,
)
if run_button_thread:
game_engine.start_loop_btn_thread()
print("game_engine.ready_wait")
if game_engine.ready_wait(min(60, GAME_TIME)):
play_random_music_from_dir(f"{ASSETS_DIR}/launch_game")
while pygame.mixer.music.get_busy():
time.sleep(0.1)
last_elapsed = -1
last_score = -1
play_music("mi.mp3")
game_ctx.current_mode = GAME_MODE.GAME
game_engine.start_game()
else:
game_ctx.current_mode = GAME_MODE.MAIN_MENU
game_category = None
main_menu = show_mainscreen(
game_engine,
categories_highest_score=score_repo.get_highest_scores_by_cat,
)
elif game_ctx.current_mode == GAME_MODE.GAME:
# Game starting
elapsed = int(round(GAME_TIME - game_engine.elapsed_time(), 0))
game_result = game_engine.game_result
game_is_finished = elapsed < 0
if game_is_finished:
highest_cat_user_score = score_repo.get_highest_scores_by_cat[
game_category
]
game_screen(
screen,
0,
game_result.score,
highest_cat_user_score,
overall_champion=score_repo.overall_champion,
)
# play_music("airhorn.mp3")
# while pygame.mixer.music.get_busy():
# time.sleep(0.1)
if game_result.score >= HISCORE_THRESHOLD:
play_music(f"{ASSETS_DIR}/successful-horn.wav")
# Player Achieved more than the threshold and can register
user_infos = win_screen(
screen, recent_usernames=score_repo.recent_gamers_usernames
)
firstname = user_infos[0]
score_repo.update_user_score(
cat=game_category,
username=firstname,
score=game_result.score,
mean_hit_time=game_result.mean_hit_time,
)
game_ctx.current_mode = GAME_MODE.MAIN_MENU
game_category = None
show_mainscreen(
game_engine,
categories_highest_score=score_repo.get_highest_scores_by_cat,
)
else:
play_music(f"{ASSETS_DIR}/funny-clown-horn.wav")
lose_screen(screen)
game_ctx.current_mode = GAME_MODE.POSTGAME
else:
screen_need_refresh = (
elapsed != last_elapsed or game_result.score != last_score
)
if screen_need_refresh:
game_screen(
screen,
elapsed,
game_result.score,
score_repo.get_highest_scores_by_cat[game_category],
overall_champion=score_repo.overall_champion,
)
last_elapsed = elapsed
last_score = game_result.score
beat_a_champion = (
0 < game_result.score >= highest_cat_user_score.highest_score
)
if beat_a_champion and not played_boxing_bell:
play_music(f"{ASSETS_DIR}/BoxingBell.wav")
played_boxing_bell = True
for event in pygame.event.get():
if event.type == pygame.QUIT:
print(f"Event: QUIT")
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
print(f"Event: KEYDOWN")
if event.key == pygame.K_F12:
print(f"Event: K_F12")
game_engine.stop_idle()
game_engine.stop_game()
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONUP:
new_game_category = on_click(
main_menu, game_engine, game_ctx, score_repo
)
game_category = game_category or new_game_category
try:
pygame.init()
screen = pygame.display.set_mode(SIZE)
main()
except BaseException as e:
traceback.print_exception(*sys.exc_info())
pygame.quit()
sys.exit()