-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscreens.py
500 lines (401 loc) · 16.1 KB
/
screens.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
import sys
from dataclasses import dataclass
from typing import List, Dict, Tuple, Any
import pygame
from pygame import Surface
from pygame_vkeyboard import VKeyboardLayout, VKeyboard, VKeyboardRenderer
import eztext
# set SIZE of the screen
from assets import ASSETS_DIR
from scores import UserScore
SIZE = (1280, 720)
# define colours
BLUE = 26, 0, 255
ORANGE = 255, 165, 0
BLACK = 0, 0, 0
WHITE = 255, 255, 255
YELLOW = 255, 255, 0
RED = 255, 0, 0
GREEN = 0, 255, 0
top = 0
CLOCK_FONT_PATH = f"{ASSETS_DIR}/digital-7 (mono).ttf"
clock = pygame.time.Clock()
FPS = 30
def rect_is_clicked(rect, click_pos):
click_x, click_y = click_pos
left, top, width, height = rect
return left <= click_x <= left + width and top <= click_y <= top + height
def align_h(label, cols=1, col=0, width=SIZE[0]):
"""
Given a label, cut the width into {cols} and return coordinates of the button
at place {col}
"""
col_width = width / cols
return ((col_width - label.get_width()) / 2) + col_width * col
def align_v(label, rows=1, row=0, height=SIZE[1]):
row_height = height / rows
return ((row_height - label.get_height()) / 2) + row_height * row
@dataclass
class MainMenuCatBox:
rect: Tuple[float, float, float, float]
title: str
rendered_title: Any
rendered_title_coord: Tuple[int, int]
rendered_hiscore: Any
rendered_hiscore_coord: Tuple[int, int]
rendered_username: Any
rendered_username_coord: Tuple[int, int]
class MainMenuGUI:
def __init__(self, categories_highest_score: Dict[str, UserScore]):
self.init_line_pos = 10
# Title "Whack-A-Pi"
fnt_head = pygame.font.Font(None, 175)
self.lab_head = fnt_head.render("Whack-A-Pi", 1, YELLOW)
# Settings icon
self.settings_img = pygame.image.load(
f"{ASSETS_DIR}/settings_small.png"
).convert_alpha()
self.settings_img_coord = (
SIZE[0] - self.settings_img.get_width() - 20,
self.init_line_pos,
)
# Category Box
fnt_title = pygame.font.Font(None, 84)
fnt_score = pygame.font.Font(CLOCK_FONT_PATH, 200)
offset_title_rects = 20
line_pos = self.init_line_pos + self.lab_head.get_height() + offset_title_rects
top = line_pos
max_width = SIZE[0] / 3
max_height = SIZE[1] - top
ranked_categories = [
(cat, user_score) for cat, user_score in categories_highest_score.items()
]
ranked_categories.sort(key=lambda d: d[1].highest_score, reverse=True)
self.cat_boxes: List[MainMenuCatBox] = []
self.crown_img_coord: Tuple[int, int]
for idx, (score_category, user_score) in enumerate(
categories_highest_score.items()
):
left, top, width, height = (
(max_width * idx) + 10,
top,
max_width - 20,
max_height - 80,
)
is_champion_category = score_category == ranked_categories[0][0]
if is_champion_category:
self.crown_img = pygame.image.load(
f"{ASSETS_DIR}/crown.png"
).convert_alpha()
self.crown_img_coord = (
left + (width / 2) - self.crown_img.get_width() / 2,
top - (self.crown_img.get_height() / 2) - 4,
)
line_pos = top # reset the vertical cursor
line_pos += 45
lab_title = fnt_title.render(score_category, 1, WHITE)
lab_title_coord = (align_h(lab_title, 3, idx), line_pos)
line_pos += lab_title.get_height() + 30
lab_score = fnt_score.render(f"{user_score.highest_score:0>3d}", 1, BLUE)
lab_score_coord = (align_h(lab_score, 3, idx), line_pos)
line_pos += lab_score.get_height() + 30
lab_username = fnt_title.render(f"{user_score.username}", 1, ORANGE)
lab_username_coord = (align_h(lab_username, 3, idx), line_pos)
cat_box = MainMenuCatBox(
rect=(left, top, width, height),
title=score_category,
rendered_title=lab_title,
rendered_title_coord=lab_title_coord,
rendered_hiscore=lab_score,
rendered_hiscore_coord=lab_score_coord,
rendered_username=lab_username,
rendered_username_coord=lab_username_coord,
)
self.cat_boxes.append(cat_box)
# HiScores
hiscores_btn_font = pygame.font.Font(None, 60)
self.hiscores_btn = hiscores_btn_font.render("HiScores", 1, YELLOW)
x, y = (
SIZE[0] / 4 - self.hiscores_btn.get_width() / 2,
SIZE[1] - 20 - self.hiscores_btn.get_height(),
)
self.hiscores_btn_coord = (x, y)
self.hiscores_btn_rect = (
10,
y - 15,
SIZE[0] / 2 - 21,
self.hiscores_btn.get_height() + 30,
)
# Recent players
self.recent_scores_btn = hiscores_btn_font.render(
"Recent Players",
1,
YELLOW,
)
x = SIZE[0] / 2 + SIZE[0] / 4 - self.recent_scores_btn.get_width() / 2
self.recent_scores_btn_coord = (x, y)
self.recent_scores_btn_rect = (
SIZE[0] / 2 + 10,
y - 15,
SIZE[0] / 2 - 21,
self.recent_scores_btn.get_height() + 30,
)
def draw(self, screen):
screen.fill(BLACK)
screen.blit(self.lab_head, (align_h(self.lab_head), self.init_line_pos))
# settings icon
screen.blit(
self.settings_img,
self.settings_img_coord,
)
for cat_box in self.cat_boxes:
pygame.draw.rect(screen, WHITE, cat_box.rect, 1)
screen.blit(cat_box.rendered_title, cat_box.rendered_title_coord)
screen.blit(cat_box.rendered_hiscore, cat_box.rendered_hiscore_coord)
screen.blit(cat_box.rendered_username, cat_box.rendered_username_coord)
screen.blit(
self.crown_img,
self.crown_img_coord,
)
# HiScore
screen.blit(self.hiscores_btn, self.hiscores_btn_coord)
pygame.draw.rect(
screen,
YELLOW,
self.hiscores_btn_rect,
1,
)
# Recent Score
screen.blit(self.recent_scores_btn, self.recent_scores_btn_coord)
pygame.draw.rect(
screen,
YELLOW,
self.recent_scores_btn_rect,
1,
)
pygame.display.flip()
def selected_category_box(self, click_pos):
for cat_box in self.cat_boxes:
if rect_is_clicked(cat_box.rect, click_pos):
return cat_box.title
return None
def clicked_settings(self, click_pos):
img_rect = [
*self.settings_img_coord,
self.settings_img.get_width(),
self.settings_img.get_height(),
]
return rect_is_clicked(img_rect, click_pos)
def clicked_hiscores(self, click_pos):
return rect_is_clicked(self.hiscores_btn_rect, click_pos)
def clicked_recent_scores(self, click_pos):
return rect_is_clicked(self.recent_scores_btn_rect, click_pos)
def game_screen(
screen,
elapsed,
score,
cat_champion: UserScore,
overall_champion: UserScore,
wait=False,
):
screen.fill(BLACK) # change the colours if needed
fnt_title = pygame.font.Font(None, 144)
lab_time_title = fnt_title.render("Time", 1, WHITE)
screen.blit(lab_time_title, (align_h(lab_time_title, 2, 0), 15))
fnt_title = pygame.font.Font(None, 144)
lab_score_title = fnt_title.render("Score", 1, WHITE)
screen.blit(lab_score_title, (align_h(lab_score_title, 2, 1), 15))
if wait:
lab_wait = fnt_title.render("Press light when ready", 1, YELLOW)
screen.blit(
lab_wait, (align_h(lab_wait, 1, 0), 15 + lab_score_title.get_height())
)
font = pygame.font.Font(CLOCK_FONT_PATH, 432)
lab_time = font.render(f"{elapsed:0>2d}", 1, ORANGE)
screen.blit(lab_time, (align_h(lab_time, 2, 0), align_v(lab_time)))
lab_score = font.render(f"{score:0>3d}", 1, BLUE)
screen.blit(lab_score, (align_h(lab_score, 2, 1), align_v(lab_score)))
# Dept Champion
fnt_subtitle = pygame.font.Font(None, 60)
lab_hi_title = fnt_subtitle.render("Dept. Hi-Score:", 1, WHITE)
fnt_hiscore = pygame.font.Font(CLOCK_FONT_PATH, 72)
lab_hi_score = fnt_hiscore.render(f"{cat_champion.highest_score:0>3d}", 1, BLUE)
score_top = SIZE[1] - lab_hi_score.get_height() - 80
hi_top = score_top + (lab_hi_score.get_height() - lab_hi_title.get_height()) / 2
screen.blit(lab_hi_title, (align_h(lab_hi_title, 4, 2) + 25, hi_top))
screen.blit(lab_hi_score, (align_h(lab_hi_score, 4, 3), score_top))
# Global Champion
fnt_subtitle2 = pygame.font.Font(None, 40)
lab_hi_title2 = fnt_subtitle2.render("Global Hi-Score:", 1, WHITE)
fnt_hiscore2 = pygame.font.Font(CLOCK_FONT_PATH, 52)
lab_hi_score2 = fnt_hiscore2.render(
f"{overall_champion.highest_score:0>3d}", 1, BLUE
)
score_top = SIZE[1] - lab_hi_score.get_height() - 20
hi_top = score_top + (lab_hi_score.get_height() - lab_hi_title.get_height()) / 2
screen.blit(lab_hi_title2, (align_h(lab_hi_title, 4, 2) + 25, hi_top))
screen.blit(lab_hi_score2, (align_h(lab_hi_score, 4, 3), score_top))
pygame.display.flip()
def _draw_win_screen(screen):
screen.fill(BLACK, (0, 0, SIZE[0] / 2, SIZE[1]))
fnt_head = pygame.font.Font(None, 144)
lab_head = fnt_head.render("High Score!", 1, YELLOW)
screen.blit(lab_head, (align_h(lab_head, 2, 0), 15))
lab_btn = fnt_head.render(
"Submit",
1,
YELLOW,
)
x = align_h(lab_btn, 2, 0)
y = SIZE[1] - 30 - lab_btn.get_height()
screen.blit(lab_btn, (x, y))
return pygame.draw.rect(
screen,
YELLOW,
(x - 15, y - 15, lab_btn.get_width() + 30, lab_btn.get_height() + 30),
1,
)
def _box_clicked(item, pos: Tuple[int, int]):
return item.top <= pos[1] <= item.bottom and item.left <= pos[0] <= item.right
class QuickPickButton:
def __init__(self, value, rendered_btn_txt, x, y):
self.rendered_btn_txt = rendered_btn_txt
self.value = value
self.btn_label_x = x
self.btn_label_y = y
self.left = self.btn_label_x - 15
self.top = self.btn_label_y - 15
self.width = self.rendered_btn_txt.get_width() + 30
self.height = self.rendered_btn_txt.get_height() + 30
@property
def right(self):
return self.left + self.width
@property
def bottom(self):
return self.top + self.height
def draw(self, screen):
screen.blit(self.rendered_btn_txt, (self.btn_label_x, self.btn_label_y))
pygame.draw.rect(
screen,
YELLOW,
(self.left, self.top, self.width, self.height),
1,
)
def win_screen(screen, recent_usernames: List[str]) -> List[str]:
"""Display the Win screen where user can enter his username"""
line_pos = SIZE[1] / 3
max_username_len = 12 # Fits main screen
firstname_input = eztext.Input(
maxlength=max_username_len,
color=WHITE,
focuscolor=YELLOW,
prompt="Username: ",
x=15,
y=line_pos,
hasfocus=True,
)
submit_btn = _draw_win_screen(screen)
## Keyboard button
keyboard_img = pygame.image.load(f"{ASSETS_DIR}/keyboard-64.png").convert_alpha()
keyboard_coord = (firstname_input.x + 450, firstname_input.y - 30)
keyboard_box = keyboard_img.get_rect().move(*keyboard_coord)
# QuickPick usernames buttons
quickpick_btns = []
x_subd = 8
y_subd = 8
qp_pos = [((x_subd, xi), (y_subd, yi)) for yi in (3, 4, 5) for xi in range(3)]
for idx, username in enumerate(recent_usernames[:9]):
qp_font = pygame.font.Font(None, 30)
qp_btn = qp_font.render(username, 1, YELLOW)
h_cols, v_cols = qp_pos[idx]
quickpick_btns.append(
QuickPickButton(
username,
qp_btn,
x=align_h(qp_btn, *h_cols) + 20,
y=align_v(qp_btn, *v_cols),
)
)
# vKeyboard
# I couldn't manage to draw the keyboard directly on screen because
# it was interfering with the _draw_win_screen and keyboard was being overwritten
# so I switch to using a separate surface that I can then move to the right location,
# the downside of this is that I need to tweak the events afterwards so that events are also shifted
def consumer(text):
firstname_input.value = text
surf = Surface((SIZE[0] / 2, 280))
layout = VKeyboardLayout(
VKeyboardLayout.QWERTY, allow_special_chars=False, height_ratio=1
)
vkeyboard = VKeyboard(surf, consumer, layout, renderer=VKeyboardRenderer.DARK)
vkeyboard.disable()
vkeyboard_offset = (0, quickpick_btns[0].top)
while True:
clock.tick(FPS)
events = pygame.event.get()
if vkeyboard.is_enabled():
# vKeyboard is draw in a separate surface that is not placed in (0, 0)
# but vkeyboard isnot aware of this, so it's expecting the clicks to be
# positioned as if the keyboard was placed in (0, 0)
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN:
# Hack - For some reason I can't deepcopy(events) so
# I'm modifying the event.pos directly and permanently, this works fine
# as the rest of the events aren't listening on pygame.MOUSEBUTTONDOWN
# which is used by the vkeyboard so it is not interfering
event.pos = [x - off for x, off in zip(event.pos, vkeyboard_offset)]
vkeyboard.update(events)
submit_score = False
for event in events:
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos()
submit_btn_clicked = _box_clicked(submit_btn, pos)
if submit_btn_clicked:
submit_score = True
if _box_clicked(keyboard_box, pos):
if vkeyboard.is_enabled():
vkeyboard.set_text("")
vkeyboard.disable()
else:
vkeyboard.enable()
if not vkeyboard.is_enabled():
for quickpick_btn in quickpick_btns:
if _box_clicked(quickpick_btn, pos):
firstname_input.value = quickpick_btn.value
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_F12:
pygame.quit()
sys.exit()
if event.key == pygame.K_RETURN:
submit_score = True
if event.type == pygame.QUIT:
print(f"Event: QUIT")
pygame.quit()
sys.exit()
if submit_score:
if firstname_input.value != "":
return [firstname_input.value]
else:
print("Missing required input value")
submit_btn = _draw_win_screen(screen)
firstname_input.update(events)
firstname_input.draw(screen)
screen.blit(keyboard_img, keyboard_coord)
if vkeyboard.is_enabled():
vkeyboard.draw(surface=surf, force=True)
screen.blit(surf, (0, quickpick_btns[0].top))
else:
# username QuickPick
for quickpick_btn in quickpick_btns:
quickpick_btn.draw(screen)
pygame.display.flip()
def lose_screen(screen):
screen.fill(BLACK, (0, 0, SIZE[0] / 2, SIZE[1]))
fnt_head = pygame.font.Font(None, 144)
lab_head = fnt_head.render("Click", 1, YELLOW)
screen.blit(lab_head, (align_h(lab_head, 2, 0), align_v(lab_head, 3, 0)))
lab_head = fnt_head.render("to", 1, YELLOW)
screen.blit(lab_head, (align_h(lab_head, 2, 0), align_v(lab_head, 3, 1)))
lab_head = fnt_head.render("Continue", 1, YELLOW)
screen.blit(lab_head, (align_h(lab_head, 2, 0), align_v(lab_head, 3, 2)))
pygame.display.flip()