-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstates.py
733 lines (611 loc) · 22.6 KB
/
states.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
""" define game states and menus """
from collections.abc import Callable
from abc import ABC, abstractmethod
import pygame
from entitys import Paddle, Ball
import settings
class State(ABC):
""" abstract class for the state stack """
def __init__(self, game) -> None:
self.game = game
self.prev_state: State
@abstractmethod
def update(self, keys: set[str]) -> None:
""" abstract state method
each state must have an update method """
@abstractmethod
def render(self, canvas: pygame.Surface) -> None:
""" abstract state method
each state must have a render method """
def enter_state(self) -> None:
""" append itself to the stack """
if len(self.game.stack) > 1:
self.prev_state = self.game.stack[-1]
self.game.stack.append(self)
def exit_state(self) -> None:
""" pop itself form the stack """
if len(self.game.stack) > 1:
self.game.stack.pop()
else:
# the stack shall NEVER be empty
# idk maybe quit the game ?
pass
class Menu(State, ABC):
""" Parent class of all menus, handel buttons and labels rendering.
The first button declared is the bottom one.
Exactly one button shall be set selected.
The labels can be placed anywhere """
class Label:
""" text to put anywhere on a menu """
def __init__(
self,
text: str,
font: pygame.font.Font,
pos: tuple[int, int],
) -> None:
self.font = font
self.text = text
self.pos = pos
self.update(new_text=self.text, pos=pos)
def update(self, new_text: str, pos: tuple[int, int]) -> None:
""" recreate an image and a frect
arg new_text is a string, will be rendered using self.font
"""
self.image: pygame.Surface = self.font.render(new_text, False, settings.FONT_COLOR)
self.frect: pygame.FRect = self.image.get_frect()
self.frect.center = pos
def render(self, canvas: pygame.Surface) -> None:
""" bruh it's just a blit """
canvas.blit(self.image, self.frect)
class Button:
""" button to pass to the menu.
a method must be associated to each button. """
def __init__(
self,
text: str,
function: Callable[[], None],
font: pygame.font.Font,
selected: bool = False,
) -> None:
self.text = text
self.function = function
self.font = font
self.selected = selected
self.image: pygame.Surface = self.font.render(self.text, False, color=(0, 0, 0))
self.frect: pygame.FRect = self.image.get_frect()
def update(self) -> None:
""" add ">button<" arround the button if selected """
if self.selected:
self.image = self.font.render(('>' + self.text + '<'), False, color=(50, 50, 50))
else:
self.image = self.font.render(self.text, False, color=(0, 0, 0))
self.frect = self.image.get_frect()
def render(self, canvas: pygame.Surface, dest: tuple[float, float]) -> None:
""" i hate you pylint """
canvas.blit(self.image, dest=dest)
def __init__(
self,
game,
background_color: settings.Color,
is_transparent: bool = False
) -> None:
super().__init__(game)
self.__name__: str = 'Menu'
# background
self.background_color = background_color
self.is_transparent = is_transparent
# font
self.font = pygame.font.Font('font/PixeloidSans.ttf', 30)
self.bold_font = pygame.font.Font('font/PixeloidSansBold.ttf', 35)
self.big_font = pygame.font.Font('font/PixeloidSansBold.ttf', 80)
# create buttons and labels list for each child
self.buttons: list[Menu.Button] = []
self.labels: list[Menu.Label] = []
def update(self, keys: set[str]) -> None:
""" move the selected/focus across buttons
and apply action if a button is pressed """
# exit the menu if ESC is pressed
if 'ESCAPE' in keys:
keys.remove('ESCAPE')
self.exit_state()
for i, button in enumerate(self.buttons):
if 'UP' in keys and button.selected and i != len(self.buttons) - 1:
keys.remove('UP')
self.buttons[i + 1].selected = True
button.selected = False
self.buttons[i + 1].update()
button.update()
break
if 'DOWN' in keys and button.selected and i != 0:
keys.remove('DOWN')
self.buttons[i - 1].selected = True
self.buttons[i - 1].update()
button.selected = False
button.update()
break
# button action
if 'RETURN' in keys and button.selected:
keys.remove('RETURN')
button.function()
# break
def render(self, canvas: pygame.Surface) -> None:
""" blit buttons, labels and a background to the given surface """
# background
if self.is_transparent:
self.prev_state.render(canvas=canvas)
# not optimized but avoid needing to reload the stack every resolution change
transparent_background = pygame.Surface(size=(settings.WIDTH, settings.HEIGHT))
transparent_background.fill(self.background_color)
transparent_background.set_alpha(settings.TRANSPARENCY_ALPHA)
canvas.blit(source=transparent_background, dest=(0, 0))
else:
canvas.fill(self.background_color)
# blit the buttons
for i, button in enumerate(self.buttons):
# center this shit was a pain in the ass
x = settings.WIDTH // 2 - button.frect.width // 2
y = (
(settings.HEIGHT // 2 - (button.frect.height // 2) * ((3 * i) + 1)) +
(len(self.buttons) // 2) * button.frect.height
)
button.render(canvas, (x, y))
# blit the labels
for label in self.labels:
label.render(canvas)
class Gameplay(State):
""" main part of the game.
is a state on the stack
"""
def __init__(self, game) -> None:
super().__init__(game)
self.__name__: str = 'Gameplay'
self.field: pygame.Surface = pygame.transform.scale(
surface=pygame.image.load(
file='assets/Field/field3.png'
).convert(),
size=(settings.WIDTH, settings.HEIGHT)
)
# reset score
settings.score['RIGHT'] = 0
settings.score['LEFT'] = 0
self.last_score = settings.score.copy()
self.score_font = pygame.font.Font('font/PixeloidSansBold.ttf', 50)
self.score_left_image: pygame.Surface = self.score_font.render(
text=str(settings.score['LEFT']),
antialias=False,
color=settings.SCORE_COLOR
)
self.score_right_image: pygame.Surface = self.score_font.render(
text=str(settings.score['RIGHT']),
antialias=False,
color=settings.SCORE_COLOR
)
# add itself to the stack
self.enter_state()
# create objects
self.paddles: list[Paddle] = []
self.paddles.append(Paddle(
pos=(settings.WIDTH / 10, settings.HEIGHT / 2),
keybinds=settings.P1Keys,
))
self.paddles.append(Paddle(
pos=(settings.WIDTH * 0.9, settings.HEIGHT / 2),
keybinds=settings.P2Keys,
))
self.ball = Ball(pos=(settings.WIDTH/2, settings.HEIGHT/2))
def update(self, keys: set[str]) -> None:
""" update the balls, powerups and paddle """
# update the paddles
for paddle in self.paddles:
paddle.update(keys=keys)
self.ball.update(self.paddles)
# only update score images if the score change
# also check if someone won
if self.last_score != settings.score:
self.score_left_image = self.score_font.render(
text=str(settings.score['LEFT']),
antialias=False,
color=settings.SCORE_COLOR
)
self.score_right_image = self.score_font.render(
text=str(settings.score['RIGHT']),
antialias=False,
color=settings.SCORE_COLOR
)
self.last_score = settings.score.copy()
# check win
for score in settings.score.values():
if score >= settings.WIN_SCORE:
Win(self.game)
# process keys press
if 'ESCAPE' in keys:
keys.remove('ESCAPE') # prevent the pause to immediately quit
Pause(self.game)
if 'p' in keys and settings.CHEATS:
keys.remove('p')
Win(self.game)
def render(self, canvas: pygame.Surface) -> None:
""" blit paddles to the given surface """
canvas.blit(source=self.field, dest=(0,0))
if settings.SHOW_HITBOX:
pygame.draw.line(
surface=canvas,
color='#ff0000',
start_pos=(settings.WIDTH / 2, 0),
end_pos=(settings.WIDTH / 2, settings.HEIGHT)
)
self.ball.render(canvas=canvas)
# render the paddles
for paddle in self.paddles:
paddle.render(canvas=canvas)
# blit score label
canvas.blit(
source=self.score_left_image,
dest=(
(settings.WIDTH / 4) - (self.score_left_image.width/2),
self.score_left_image.height
)
)
canvas.blit(
source=self.score_right_image,
dest=(
(settings.WIDTH / 4) * 3 - (self.score_right_image.width/2),
self.score_right_image.height
)
)
def __repr__(self) -> str:
""" return the type of the state """
return 'Gameplay'
class Mainmenu(Menu):
""" this is the first state in the stack """
def __init__(self, game) -> None:
super().__init__(game, settings.MAINMENU_BACKGROUND_COLOR)
# enter state
self.enter_state()
# init buttons
self.buttons.extend([
Menu.Button(
text='exit',
function=self.exit_game,
font=self.font,
), # exit
Menu.Button(
text='settings',
function=self.to_settings,
font=self.font,
), # settings
Menu.Button(
text='difficulties',
function=self.to_difficulties_choice,
font=self.font,
), # difficulties
Menu.Button(
text='play',
function=self.play,
font=self.font,
selected=True
), # play
])
for button in self.buttons:
button.update()
# create labels
self.labels.append(Menu.Label(
text='MAIN MENU',
font=self.big_font,
pos=(settings.WIDTH // 2, settings.HEIGHT // 10),
)) # main menu
def to_difficulties_choice(self) -> None:
""" create new Difficulties state """
Difficulties(self.game)
def to_settings(self) -> None:
""" new Settings state """
Settings(self.game)
def play(self) -> None:
""" new gameplay state """
Gameplay(self.game)
def exit_game(self) -> None:
""" set game.running to false """
self.game.running = False
class Gameover(Menu):
""" gameover state, is a Menu.
shows score
"""
def __init__(self, game) -> None:
super().__init__(game, settings.GAMEOVER_BACKGROUND_COLOR)
# append itself to the stack
self.enter_state()
# create buttons
self.buttons.append(Menu.Button(
text='menu',
function=self.to_menu,
font=self.font
)) # menu
self.buttons.append(Menu.Button(
text='replay',
function=self.replay,
font=self.font,
selected=True
)) # replay
for button in self.buttons:
button.update()
# create labels
self.labels.append(Menu.Label(
text='GAME OVER',
font=self.big_font,
pos=(settings.WIDTH // 2, settings.HEIGHT // 10)
)) # GAME OVER
self.labels.append(Menu.Label(
text=f'score : {settings.score['RIGHT']}-{settings.score['LEFT']}',
font=self.bold_font,
pos=(settings.WIDTH // 2, (settings.HEIGHT // 16) * 11)
)) # score : 99
def to_menu(self) -> None:
""" go back to the mainmenu by poping the states stack """
# stack : mainmenu > gameplay > gameover
self.exit_state() # back to gameplay
self.exit_state() # back to menu
def replay(self) -> None:
""" create a new Gameplay state and modify the state stack """
# stack : mainmenu > gameplay > gameover
self.exit_state() # back to gameplay
self.exit_state() # back to menu
Gameplay(self.game)
class Win(Menu):
""" Win state,
show score
"""
def __init__(self, game) -> None:
super().__init__(game, settings.WIN_BACKGROUND_COLOR)
# append itself to the stack
self.enter_state()
# create buttons
self.buttons.append(Menu.Button(
text='menu',
function=self.to_menu,
font=self.font,
)) # menu
self.buttons.append(Menu.Button(
text='replay',
function=self.replay,
font=self.font,
selected=True
)) # replay
for button in self.buttons:
button.update()
# create labels
self.labels.extend([
Menu.Label(
text='YOU WON !!!',
font=self.big_font,
pos=(settings.WIDTH // 2, settings.HEIGHT // 10),
), # YOU WON
Menu.Label(
text=f'score : {settings.score['LEFT']}-{settings.score['RIGHT']}',
font=self.bold_font,
pos=(settings.WIDTH // 2, (settings.HEIGHT // 16) * 11),
), # score : 090
])
def to_menu(self) -> None:
""" pop stack twice """
self.exit_state() # back to gameplay
self.exit_state() # back to menu
def replay(self) -> None:
""" recreate a gamplay state """
self.exit_state() # back to menu
Gameplay(self.game)
class Pause(Menu):
""" is a state of the stack,
background transparent, so you can see the last frame of the last state
"""
def __init__(self, game) -> None:
super().__init__(game, settings.PAUSE_BACKGROUND_COLOR, is_transparent=True)
# append itself to the stack
self.enter_state()
self.buttons.append(Menu.Button(
text='menu',
function=self.to_mainmenu,
font=self.font
)) # menu
self.buttons.append(Menu.Button(
text='resume',
function=self.resume,
font=self.font,
selected=True
)) # resume
# buttons are not updated each frame
# first update after being append
for button in self.buttons:
button.update()
# labels
self.labels.append(Menu.Label(
text='Pause',
font=self.big_font,
pos=(settings.WIDTH // 2, settings.HEIGHT // 10)
)) # settings
self.labels.append(Menu.Label(
text=f'score : {settings.score['LEFT']}-{settings.score['RIGHT']}',
font=self.bold_font,
pos=(settings.WIDTH // 2, int(settings.HEIGHT * 0.8))
)) # score : 999
def resume(self) -> None:
""" after pause restart a counter """
self.exit_state()
def to_mainmenu(self) -> None:
""" exit state twice"""
# the stack :
# >main>gameplay>pause
self.exit_state()
# >main>gameplay
self.exit_state()
# >main
class Settings(Menu):
""" settings menu, give access to resolution, difficulties """
def __init__(self, game) -> None:
super().__init__(game, settings.SETTINGS_BACKGROUND_COLOR, is_transparent=False)
# append itself to the stack
self.enter_state()
# create buttons
self.buttons.extend([
Menu.Button(
text='sound',
function=self.to_sound_settings,
font=self.font,
), # sound
Menu.Button(
text='resolution',
function=self.to_resolution_settings,
font=self.font,
selected=True
), # resolution
])
for button in self.buttons:
button.update()
# Title
self.labels.append(Menu.Label(
text='Settings',
font=self.big_font,
pos=(settings.WIDTH // 2, settings.HEIGHT // 10)
)) # settings Title
def to_sound_settings(self) -> None:
""" not implemented yet """
print('Coming (not) Soon !')
def to_resolution_settings(self) -> None:
""" create new Resolution state """
Resolution(self.game)
class Difficulties(Menu):
""" select a difficulties.
Change values in settings
"""
def __init__(self, game) -> None:
super().__init__(game, background_color=settings.SETTINGS_BACKGROUND_COLOR)
self.enter_state()
# buttons
self.buttons.extend([
Menu.Button(
text='hard',
function=self.hard,
font=self.font
), # hard
Menu.Button(
text='Normal',
function=self.normal,
font=self.font,
selected=True
), # normal
Menu.Button(
text='Easy',
function=self.easy,
font=self.font
), # easy
])
for button in self.buttons:
button.update()
def hard(self) -> None:
""" change settings values to tweak speeds and stuff """
settings.BALL_SPEED = 6
settings.PADDLE_SPEED = 7
settings.POWERUP_SPEED = 5
settings.POWERUP_BIG_PADLLE_DURATION = 5
settings.BALL_MULTIPLYER = 1
settings.MAX_BOUNCE_ANGLE = 120
settings.POWERUP_PADDLE_CHANCE = 7
settings.POWERUP_BALL_CHANCE = 3
settings.POWERUP_PADDLE_SIZE = 1.1
self.exit_state()
def normal(self) -> None:
""" change settings values to tweak speeds and stuff """
settings.BALL_SPEED = 5
settings.PADDLE_SPEED = 8
settings.POWERUP_SPEED = 2
settings.POWERUP_BIG_PADLLE_DURATION = 10
settings.BALL_MULTIPLYER = 2
settings.MAX_BOUNCE_ANGLE = 60
settings.POWERUP_PADDLE_CHANCE = 10
settings.POWERUP_BALL_CHANCE = 10
settings.POWERUP_PADDLE_SIZE = 1.2
self.exit_state()
def easy(self) -> None:
""" change settings values to tweak speeds and stuff """
settings.BALL_SPEED = 4
settings.PADDLE_SPEED = 8
settings.POWERUP_SPEED = 1
settings.POWERUP_BIG_PADLLE_DURATION = 15
settings.BALL_MULTIPLYER = 3
settings.MAX_BOUNCE_ANGLE = 45
settings.POWERUP_PADDLE_CHANCE = 25
settings.POWERUP_BALL_CHANCE = 15
settings.POWERUP_PADDLE_SIZE = 1.4
self.exit_state()
class Resolution(Menu):
""" change settings.WIDTH and settings.HEIGHT.
Also toggle fullscreen
"""
def __init__(self, game) -> None:
super().__init__(game, background_color=settings.SETTINGS_BACKGROUND_COLOR)
self.enter_state()
# buttons
self.buttons.extend([
Menu.Button(
text='512x256',
function=self.res_512x256,
font=self.font,
), # 512x256
Menu.Button(
text='1024x512',
function=self.res_1024x512,
font=self.font,
), # 1024x512
Menu.Button(
text='Toggle fullscreen',
function=self.toggle_fullscreen,
font=self.font,
selected=True
), # fullscreen
])
for button in self.buttons:
button.update()
# label
self.labels.append(Menu.Label(
text='Resolutions',
font=self.big_font,
pos=(settings.WIDTH // 2, settings.HEIGHT // 10)
)) # resolution title
def toggle_fullscreen(self) -> None:
""" re-set the pygame display,
change settings screen size (wich whould be a constant hum...)
update the labels of each state in the stack
"""
# recreate the display
if self.game.fullscreen:
self.game.display = pygame.display.set_mode(
size=(settings.WIDTH_BACKUP, settings.HEIGHT_BACKUP)
)
settings.WIDTH, settings.HEIGHT = settings.WIDTH_BACKUP, settings.HEIGHT_BACKUP
self.game.fullscreen = False
else:
self.game.display = pygame.display.set_mode(size=(0, 0), flags=pygame.FULLSCREEN)
settings.WIDTH, settings.HEIGHT = self.game.display.get_size()
self.game.fullscreen = True
# update labels for every Menu state in the stack
self.update_labels()
def update_labels(self):
""" update the labels positions for every Menu state in the stack """
for state in self.game.stack:
if state.__name__ != 'Menu':
continue
for label in state.labels:
label.update(new_text=label.text, pos=(settings.WIDTH/2, settings.HEIGHT*0.1))
def res_512x256(self) -> None:
""" recreate the pygame display at a given size
and update settings.WIDTH and settings.HEIGHT
"""
self.game.display = pygame.display.set_mode(size=(512, 256))
settings.WIDTH, settings.HEIGHT = 512, 256
self.update_labels()
def res_1024x512(self) -> None:
""" recreate the pygame display at a given size
and update settings.WIDTH and settings.HEIGHT
"""
self.game.display = pygame.display.set_mode(size=(1024, 512))
settings.WIDTH, settings.HEIGHT = 1024, 512
self.update_labels()