-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
1528 lines (1254 loc) · 68.1 KB
/
game.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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Main game for Hilbert's Hotel.
Manages game loop, updating all entities and display.
"""
import random
import math
import numpy as np
import os
import json
import cProfile
import sys
import pygame
import pygame.freetype
import scripts.entities as _entities
import scripts.characters as _characters
import scripts.utilities as _utilities
import scripts.tilemap as _tilemap
import scripts.clouds as _clouds
import scripts.particle as _particle
import scripts.spark as _spark
class Game:
def __init__(self, fullscreen = False, screen_size = (1080, 720)):
# Pygame specific parameters and initialisation
pygame.init()
game_version = '0.8.0'
pygame.display.set_caption(f'Hilbert\'s Hotel v{game_version}')
self.text_font = pygame.font.SysFont('Wingdings', 32, bold=True)
self.text_font = pygame.font.Font('data/font.ttf', 8)
self.clock = pygame.time.Clock()
# Define all general game parameters and load in assets
self.is_fullscreen = fullscreen
self.screen_width = screen_size[0]
self.screen_height = screen_size[1]
_utilities.initialise_main_screen(self)
_utilities.initialise_game_params(self)
self.load_game_assets()
self.player = _entities.Player(self, (0, 0), (8, 12))
self.tilemap = _tilemap.Tilemap(self, tile_size=16)
def load_menu(self):
self.sfx['ambience'].play(-1)
save_slots = [0, 1, 2]
save_info = self.get_save_info()
hover_slot = 1
deleting = 0
selected = (86, 31, 126)
not_selected = (1, 1, 1)
self.clouds = _clouds.Clouds(self.assets['clouds'], count=30)
background = pygame.transform.scale(self.assets['menuBackground'], (self.screen_width / 2, self.screen_height / 2))
foreground = pygame.transform.scale(self.assets['menuForeground'], (self.screen_width / 2, self.screen_height / 2))
while self.in_menu:
self.display_outline.fill((0, 0, 0, 0))
self.display_outline.blit(background, (0, 0))
self.hud_display.fill((0, 0, 0, 0))
self.clouds.update()
self.clouds.render(self.display_outline, offset=self.render_scroll)
self.display_outline.blit(foreground, (0, 0))
# Delete save if held for 5 secs
if deleting:
deleting = max(deleting - 1, 0)
if deleting == 0:
self.delete_save(hover_slot % len(save_slots))
save_info = self.get_save_info()
# Displaying menu HUD:
display_slot = hover_slot % len(save_slots)
self.draw_text('Hilbert\'s Hotel', (self.screen_width * (1/2), 45), self.text_font, selected, scale = 8, mode='center')
self.draw_text('Select: X', (self.screen_width * (2/4) - 75, self.screen_height - 20), self.text_font, not_selected, scale = 2, mode='center')
self.draw_text('Delete: Z', (self.screen_width * (2/4) + 75, self.screen_height - 20), self.text_font, not_selected, scale = 2, mode='center')
self.draw_text('Quit Game: Q', (self.screen_width * 0.9, self.screen_height - 20), self.text_font, not_selected, scale = 2, mode='center')
self.draw_text('Fullscreen: F', (self.screen_width * 0.1, self.screen_height - 20), self.text_font, not_selected, scale = 2, mode='center')
for n in range(0, len(save_slots)):
if self.saved_characters[n]:
image = self.saved_characters[n].copy()
if n == hover_slot and deleting:
image.set_alpha(deleting)
self.display_outline.blit(image, ((self.screen_width * (2/4) - 160 + 130*n)/2, (self.screen_height - 135)/2))
else:
self.draw_text('No Data', (self.screen_width * (2/4) - 130 + 130*n, self.screen_height - 90), self.text_font,
selected if display_slot == n else not_selected, mode='center', scale = 3)
self.draw_text('< >', (self.screen_width * (2/4) - 128 + 130*display_slot, self.screen_height - 90), self.text_font,
selected, mode='center', scale = 8)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
hover_slot -= 1
if deleting:
deleting = 0
if event.key == pygame.K_RIGHT:
hover_slot += 1
if deleting:
deleting = 0
if event.key == pygame.K_x:
save_slot = hover_slot % len(save_slots)
self.game_running = True
self.run(save_slot)
if event.key == pygame.K_z and self.saved_characters[display_slot]:
deleting = 255
if event.key == pygame.K_f:
self.is_fullscreen = not self.is_fullscreen
self.toggle_fullscreen()
if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_z:
deleting = 0
self.display.blit(self.display_outline, (0, 0))
self.screen.blit(pygame.transform.scale(self.display, self.screen.get_size()), (0, 0))
self.screen.blit(pygame.transform.scale(self.hud_display, self.screen.get_size()), (0, 0))
pygame.display.update()
self.clock.tick(self.fps)
self.interraction_frame_z = False
self.end_game()
def set_player_colours(self):
#When not starting a new game, no options to change colour, just alter assets and jump straight in.
if self.creation_done:
default_player_colours = {
'shirt': (74, 94, 132),
'front Leg': (51, 20, 0),
'back Leg': (38, 15, 0),
'tie': (2, 2, 2),
'belt': (5, 5, 5),
'skin': (175, 168, 151),
'eye': (0, 1, 104),
}
for clothing_type in default_player_colours.keys():
_utilities.alter_character_colour(self, default_player_colours[clothing_type], self.player_colours[clothing_type])
_utilities.alter_character_colour(self, (150, 143, 126), tuple((max(1, c - 25) for c in self.player_colours['skin'])))
return
self.dummy_player = _entities.PlayerCustomise(self, (799, 567), (16, 16))
background = pygame.transform.scale(self.assets['backgroundcustom'], (self.screen_width / 2, self.screen_height / 2))
self.tilemap.tilemap = {
f'{x};39': {"type": "normal", "variant": 1, "pos": [x, 39]}
for x in range(42, 60)
}
customising_colours = True
selected = (255, 255, 255)
not_selected = (150, 150, 150)
player_render_scale = 5
darkness = 0
reducing_player = False
height_index = 0
selection_indices = {
'shirt': 0,
'front Leg': 0,
'back Leg': 0,
'tie': 0,
'belt': 0,
'skin': 0,
'eye': 0,
}
while customising_colours:
# Background
self.display.blit(background, (0, 0))
self.display_outline.fill((0, 0, 0, 0))
self.hud_display.fill((0, 0, 0, 0))
self.darkness_surface.fill((0, 0, 0, darkness))
if not reducing_player:
self.draw_text('Who are you?', (self.screen_width / 2 - 275, self.screen_height / 2 - 150), self.text_font, (255, 255, 255), scale = 4, mode='center')
self.draw_text('Confirm: X', (self.screen_width / 2 - 275, self.screen_height / 2 + 160), self.text_font, (255, 255, 255), scale = 4, mode='center')
for n, piece in enumerate(list(selection_indices.keys())):
text_col = selected if piece == _utilities.index_to_value(height_index, list(selection_indices.keys())) else not_selected
self.draw_text(f'{piece.capitalize()}:', (self.screen_width / 2 + 275, self.screen_height / 2 - 350 + 100*n), self.text_font, text_col, mode='center', scale = 2)
for offset, colour in enumerate(range(selection_indices[piece]-2, selection_indices[piece]+3)):
circle_size = 25 - 3*abs(offset - 2)
pygame.draw.circle(self.hud_display, (255, 255, 255), (self.screen_width / 2 + 125 + offset*75, self.screen_height / 2 - 300 + 100*n), circle_size)
pygame.draw.circle(self.hud_display, _utilities.index_to_value(selection_indices[piece] - 2 + offset, self.player_colours_options[piece]), (self.screen_width / 2 + 125 + offset*75, self.screen_height / 2 - 300 + 100*n), circle_size-2)
#Triangle indicators
tri_point = (self.screen_width / 2 + 475, self.screen_height / 2 - 300 + 100*(height_index % 7))
pygame.draw.lines(self.hud_display, selected, False, [(tri_point[0], tri_point[1]-10),
(tri_point[0]+10, tri_point[1]),
(tri_point[0], tri_point[1]+10)], 5)
tri_point = (self.screen_width / 2 + 75, self.screen_height / 2 - 300 + 100*(height_index % 7))
pygame.draw.lines(self.hud_display, selected, False, [(tri_point[0], tri_point[1]-10),
(tri_point[0]-10, tri_point[1]),
(tri_point[0], tri_point[1]+10)], 5)
self.tilemap.move_tiles_customise()
self.tilemap.render_colour_screen(self.display_outline, offset=self.render_scroll)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and not reducing_player:
self.sfx['blip'].play()
clothing_type = _utilities.index_to_value(height_index, list(selection_indices.keys()))
if clothing_type != 'confirm':
current_colour = _utilities.index_to_value(selection_indices[clothing_type], self.player_colours_options[clothing_type])
new_colour = _utilities.index_to_value(selection_indices[clothing_type] - 1, self.player_colours_options[clothing_type])
_utilities.alter_character_colour(self, current_colour, new_colour)
self.player_colours[clothing_type] = new_colour
selection_indices[_utilities.index_to_value(height_index, list(selection_indices.keys()))] -= 1
if event.key == pygame.K_RIGHT and not reducing_player:
self.sfx['blip'].play()
clothing_type = _utilities.index_to_value(height_index, list(selection_indices.keys()))
if clothing_type != 'confirm':
current_colour = _utilities.index_to_value(selection_indices[clothing_type], self.player_colours_options[clothing_type])
new_colour = _utilities.index_to_value(selection_indices[clothing_type] + 1, self.player_colours_options[clothing_type])
_utilities.alter_character_colour(self, current_colour, new_colour)
self.player_colours[clothing_type] = new_colour
selection_indices[_utilities.index_to_value(height_index, list(selection_indices.keys()))] += 1
if event.key == pygame.K_UP and not reducing_player:
self.sfx['dashClick'].play()
height_index -= 1
if event.key == pygame.K_DOWN and not reducing_player:
self.sfx['dashClick'].play()
height_index += 1
if event.key == pygame.K_x:
reducing_player = True
_utilities.alter_character_colour(self, (150, 143, 126), tuple((max(1, c - 25) for c in self.player_colours['skin'])))
self.dummy_player.set_action('idle')
if event.key == pygame.K_f:
self.is_fullscreen = not self.is_fullscreen
self.toggle_fullscreen()
if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
self.__init__(fullscreen = self.is_fullscreen, screen_size=(self.screen_width, self.screen_height))
self.load_menu()
if reducing_player:
player_render_scale = max(player_render_scale - 0.01, 1)
self.scroll[0] += ((self.dummy_player.rect().x + (self.dummy_player.size[0] * min(player_render_scale, 3) / 2)) - self.screen_width / 4 - self.scroll[0]) / 15
self.scroll[1] += ((self.dummy_player.rect().y + (self.dummy_player.size[1] * min(player_render_scale, 3) / 2)) - self.screen_height / 4 - self.scroll[1]) / 15
self.render_scroll = (int(self.scroll[0]), int(self.scroll[1]))
darkness =min(darkness + 3, 255)
if player_render_scale <= 1:
self.creation_done = True
customising_colours = False
self.dummy_player.update(self.tilemap, (0, 0))
self.display_outline.blit(self.darkness_surface, (0, 0))
self.dummy_player.render(self.display_outline, offset=self.render_scroll, scale = min(player_render_scale, 3))
self.display.blit(self.display_outline, (0, 0))
self.screen.blit(pygame.transform.scale(self.display, self.screen.get_size()), (0, 0))
self.screen.blit(pygame.transform.scale(self.hud_display, self.screen.get_size()), (0, 0))
pygame.display.update()
self.clock.tick(self.fps)
def run(self, save_slot):
self.save_slot = save_slot
self.load_game(self.save_slot)
self.set_player_colours()
self.in_menu = False
self.sfx['lobby_music'].play(-1)
self.sfx['ambience'].stop()
self.tilemap.load_tilemap('lobby')
self.load_level()
#####################################################
######################GAME LOOP######################
#####################################################
while self.game_running:
# Camera movement
self.scroll[0] += (self.player.rect().centerx - self.screen_width / 4 - self.scroll[0]) / 15
self.scroll[1] += (self.player.rect().centery - self.screen_height / 4 - self.scroll[1]) / 15
self.render_scroll = (int(self.scroll[0]), int(self.scroll[1]))
# Background
self.display.blit(self.background, (0, 0))
self.display_outline.fill((0, 0, 0, 0))
self.hud_display.fill((0, 0, 0, 0))
self.darkness_surface.fill((0, 0, 0, self.cave_darkness))
self.screenshake = max(0, self.screenshake - 1)
#Sync movement with framerate with dt
#Its not really a dt, but more a scale factor
#TODO change 60 back to self.fps
self.dt = 60 / max(15, min(self.clock.get_fps(), 60))
if not self.paused:
self.clouds.update()
self.clouds.render(self.display_outline, offset=self.render_scroll)
# RENDER AND UPDATE ALL THE THINGS
for portal in self.portals:
if not self.paused:
portal.update(self.tilemap)
portal.render(self.display_outline, offset=self.render_scroll)
for enemy in self.enemies.copy():
if not self.paused:
if enemy.update(self.tilemap, (0, 0)):
self.enemies.remove(enemy)
self.player.updatenearest_enemy()
enemy.render(self.display_outline, offset=self.render_scroll)
for boss in self.bosses.copy():
if not self.paused:
if boss.update(self.tilemap, (0, 0)):
self.bosses.remove(boss)
boss.render(self.display_outline, offset=self.render_scroll)
for character in self.characters.copy():
if not self.paused:
character.update(self.tilemap)
character.render(self.display_outline, offset=self.render_scroll)
for spawn_point in self.spawn_points:
if not self.paused:
spawn_point.update(self.tilemap)
spawn_point.render(self.display_outline, offset=self.render_scroll)
if not self.dead:
if not self.paused:
self.player.update(self.tilemap, (self.movement[1] - self.movement[0], 0))
self.player.render(self.display_outline, offset=self.render_scroll)
for projectile in self.projectiles.copy():
if projectile.update(self):
self.projectiles.remove(projectile)
for rect in self.potplants:
if random.random() < 0.01 and not self.paused:
pos = (rect.x + rect.width * random.random(),
rect.y + rect.height * random.random())
self.particles.append(_particle.Particle(self, 'leaf', pos, vel=[0, random.uniform(0.2, 0.4)], frame=random.randint(0, 10)))
for currency_item in self.currency_entities.copy():
if not self.paused:
if currency_item.update(self.tilemap, (0, 0)):
self.currency_entities.remove(currency_item)
currency_item.render(self.display_outline, offset=self.render_scroll)
self.tilemap.render(self.display_outline, offset=self.render_scroll)
for extra_entity in self.extra_entities.copy():
if not self.paused:
if extra_entity.update(self.tilemap):
self.extra_entities.remove(extra_entity)
extra_entity.render(self.display_outline, offset=self.render_scroll)
for spark in self.sparks.copy():
if not self.paused:
if spark.update(self, offset=self.render_scroll):
self.sparks.remove(spark)
spark.render(self.display_outline, offset=self.render_scroll)
display_outline_mask = pygame.mask.from_surface(self.display_outline)
display_outline_sillhouette = display_outline_mask.to_surface(setcolor=(0, 0, 0, 180), unsetcolor=(0, 0, 0, 0))
for offset in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
self.display.blit(display_outline_sillhouette, offset)
for particle in self.particles.copy():
particle.render(self.display_outline, offset=self.render_scroll)
if not self.paused:
kill = particle.update()
if particle.type == 'leaf':
particle.pos[0] += math.sin(particle.animation.frame * 0.035 + particle.randomness) * 0.2
if kill:
self.particles.remove(particle)
# Displaying HUD and text:
if self.display_hud:
self.display_hud_text()
# Level transition
if self.transition > 30:
self.tilemap.load_tilemap(self.next_level)
self.previous_level = self.current_level
self.current_level = self.next_level
self.current_level = self.next_level
self.load_level()
self.dead = False
elif self.transition < 31 and self.transition != 0:
self.transition += 1
# Remove interaction frames
self.interraction_frame_z = False
self.interraction_frame_f = False
self.interraction_frame_a = False
self.interraction_frame_s = False
self.interraction_frame_v = False
self.interraction_frame_q = False
# Event handler
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.floors['infinite'] = 1
# Add important items left on ground:
for currency in self.currency_entities:
type = str(currency.currency_type) + 's'
if type in self.not_lost_on_death:
self.wallet[type] += currency.value
self.save_game(self.save_slot)
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.movement[0] = True
if event.key == pygame.K_RIGHT:
self.movement[1] = True
if event.key == pygame.K_UP:
if not self.paused and self.player.jump() and abs(self.player.dashing) < 50:
self.sfx['jump'].play()
self.movement[2] = True
if event.key == pygame.K_DOWN:
self.movement[3] = True
self.player.gravity = 0.12 if self.level_style == 'space' else 0.2
if event.key == pygame.K_x:
if not self.paused:
self.player.dash()
if event.key == pygame.K_z:
self.interraction_frame_z = True
if event.key == pygame.K_a:
self.interraction_frame_a = True
if event.key == pygame.K_s:
self.interraction_frame_s = True
if event.key == pygame.K_v:
self.interraction_frame_v = True
if event.key == pygame.K_f:
self.interraction_frame_f = True
if event.key == pygame.K_q:
self.interraction_frame_q = True
if event.key == pygame.K_d:
self.display_hud = not self.display_hud
if event.key == pygame.K_ESCAPE:
if not self.talking and not self.dead:
self.paused = not self.paused
# DEBUGGING
if event.key == pygame.K_r:
self.transition_to_level(self.current_level)
if event.key == pygame.K_m:
self.game_running = False
if event.key == pygame.K_t:
for currency in self.wallet:
self.wallet[currency] += 20
if event.key == pygame.K_k:
for e in self.enemies.copy():
e.kill()
self.enemies.remove(e)
for c in self.extra_entities.copy():
if c.type == 'crate':
c.kill()
self.extra_entities.remove(c)
if event.key ==pygame.K_j:
for c in self.currency_entities.copy():
self.wallet_temp[str(c.currency_type) + 's'] += c.value
self.currency_entities.remove(c)
if event.key == pygame.K_p:
self.fps = 20 if self.fps == 60 else 60
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
self.movement[0] = False
if event.key == pygame.K_RIGHT:
self.movement[1] = False
if event.key == pygame.K_UP:
self.movement[2] = False
if event.key == pygame.K_DOWN:
self.movement[3] = False
self.player.gravity = 0.075 if self.level_style == 'space' else 0.12
if self.dead:
self.darkness_surface.fill(
(0, 0, 0, max(self.min_pause_darkness, self.cave_darkness)))
self.draw_text('YOU DIED', (self.screen_width / 4, self.screen_height / 4 - 30), self.text_font, (200, 0, 0), scale = 2, mode='center')
self.draw_text(self.death_message, (self.screen_width / 4, self.screen_height / 4 - 10), self.text_font, (200, 0, 0), mode='center')
self.draw_text('Deaths: ' + str(self.death_count), (self.screen_width / 4, self.screen_height / 4 + 15), self.text_font, (200, 0, 0), mode='center')
self.draw_text('Press z to Alive Yourself', (self.screen_width / 4, self.screen_height / 4 + 30), self.text_font, (200, 0, 0), mode='center')
if self.interraction_frame_z:
self.transition_to_level('lobby')
# Darkness effect blit:
if self.cave_darkness or self.paused or self.dead:
self.display_outline.blit(self.darkness_surface, (0, 0))
self.display.blit(self.display_outline, (0, 0))
screenshake_offset = (random.random() * self.screenshake - self.screenshake / 2, random.random() * self.screenshake - self.screenshake / 2) if self.screenshake_on else (0, 0)
self.display.blit(self.hud_display, screenshake_offset)
self.screen.blit(pygame.transform.scale(self.display, self.screen.get_size()), screenshake_offset)
# Level transition circle
if self.transition:
transition_surface = pygame.Surface(self.screen.get_size())
pygame.draw.circle(transition_surface, (255, 255, 255), (self.screen.get_width() // 2, self.screen.get_height() // 2), (30 - abs(self.transition)) * (self.screen.get_width() / 30))
transition_surface.set_colorkey((255, 255, 255))
self.screen.blit(transition_surface, (0, 0))
pygame.display.update()
self.clock.tick(self.fps)
#####################################################
####################GAME LOOP END####################
#####################################################
def end_game(self):
self.run_text(self.ending_texts[self.end_type], 'ending')
self.game_ending = True
while self.game_ending:
self.hud_display.fill((1, 1, 1))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_z:
self.interraction_frame_z = True
self.display_text()
if not self.talking:
self.in_menu = True
self.game_ending = False
self.interraction_frame_z = False
self.display.blit(self.display_outline, (0, 0))
self.screen.blit(pygame.transform.scale(self.display, self.screen.get_size()), (0, 0))
self.screen.blit(pygame.transform.scale(self.hud_display, self.screen.get_size()), (0, 0))
pygame.display.update()
self.clock.tick(self.fps)
self.__init__(fullscreen = self.is_fullscreen, screen_size=(self.screen_width, self.screen_height))
self.load_menu()
def update_dialogues(self):
"""Update next available dialogue for all present characters.
Args:
none
Returns:
none
"""
for character in self.characters:
# Update which dialogue the character is up to.
dialogue = self.dialogue_history[str(character.name)]
character.new_dialogue = False
for index in range(int(len(dialogue) / 2)):
if dialogue[str(index) + 'said']:
character.current_dialogue_index = index
# Checks to see if the player has the required currency to unlock new dialogues.
for index in character.currency_requirements:
if index > character.current_dialogue_index + 1:
break
individual_success = True
success = True
for i, trade in enumerate(character.currency_requirements[index]):
# To unlock dialogue you need to fulfill requirement/s:
individual_success = self.check_currency_requirement(trade, self.wallet, index, character.current_dialogue_index, character)
if individual_success:
character.current_trade_ability[i] = True
else:
character.current_trade_ability[i] = False
success = False
# SPECIAL CASES:
# e.g. dont unlock dialogue if in wrong floor etc.
character_move_to_lobby = ['Noether', 'Curie', 'Planck', 'Lorenz', 'Franklin', 'Rubik', 'Cantor', 'Melatos']
if (character.name in character_move_to_lobby) & (index >= 1) & (self.current_level != 'lobby'):
success = False
if success:
self.dialogue_history[character.name][str(index) + 'available'] = True
elif index > character.current_dialogue_index + 1 or not self.dialogue_history[character.name][str(index) + 'said']:
self.dialogue_history[character.name][str(index) + 'available'] = False
# Check to see if new dialogue is available:
for index in range(int(len(dialogue) / 2)):
if dialogue[str(index) + 'available'] and not dialogue[str(index) + 'said']:
character.new_dialogue = True
def check_currency_requirement(self, trade, wallet, index, character_index, character):
"""Determine whether a trade requirement is met from a specific character.
Args:
trade: the specific trade in questionin character's currency_requirements
wallet: library of player's currencies.
index: index of specific trade in character's currency_requirements.
character_index: character's current_dialogue_index
character: the character's name as a string.
Returns:
boolean
"""
# If you havent reached the dialogue, it is not available
if index > character_index + 1:
return False
# Purchasing things
if trade[0] == 'purchase':
if wallet[trade[1]] < trade[2]:
return False
# Specifically prime num
elif trade[0] == 'prime':
if not _utilities.is_prime(wallet[trade[1]]):
return False
# Specifically prime num over a value
elif trade[0] == 'primePurchase':
if not _utilities.is_prime(wallet[trade[1]]) or wallet[trade[1]] < trade[3]:
return False
# Beat a specific floor of a level:
elif trade[0] == 'floor':
# Check for maximum infinite floor
if trade[1] == 'infinite':
if self.infinite_floor_max < trade[2]:
return False
# Else check against current floor levels
elif self.floors[trade[1]] < trade[2] + 1:
return False
# Specifically prime num floor
elif trade[0] == 'primeFloor':
if trade[1] == 'infinite':
if not _utilities.is_prime(self.infinite_floor_max):
return False
elif not _utilities.is_prime(self.floors[trade[1]]):
return False
# Also the previous dialogue needs to have been said:
if index != 0:
if not self.dialogue_history[character.name][str(index - 1) + 'said']:
return False
# You can probably access the dialogue.
return True
def display_text(self):
"""Displays game.current_text_list one character at a time.
Args:
none
Returns:
none
"""
# Each frame an extra character is added to the displayed text.
# If the length of a line is larger than self.max_characters_line, it creates a new line IF there is a space to not chop words.
if self.text_length < self.text_length_end and self.current_text_index < self.end_text_index:
if self.current_text_list[self.current_text_index][self.text_length] == ' ' and len(self.display_text_list[-1]) > self.max_characters_line:
self.display_text_list.append('')
else:
self.display_text_list[-1] = self.display_text_list[-1] + self.current_text_list[self.current_text_index][self.text_length]
self.text_length += 1
if self.text_length == self.text_length_end - 1:
self.sfx['textBlip'].fadeout(50)
# If all text in current chunk is displayed, move to next chunk.
if self.interraction_frame_z and self.text_length > 1:
if self.text_length == self.text_length_end:
self.sfx['textBlip'].play(fade_ms=50)
self.current_text_index += 1
self.text_length = 0
# Only shallow copy needed
self.display_text_list = self.talking_object[:]
try:
self.text_length_end = len(self.current_text_list[self.current_text_index])
except IndexError:
pass
# Fills in current text if the player is impatient
else:
# Im sure this while loop will always end, right?
self.sfx['textBlip'].fadeout(50)
while self.text_length < self.text_length_end:
if self.current_text_list[self.current_text_index][self.text_length] == ' ' and len(self.display_text_list[-1]) > self.max_characters_line:
self.display_text_list.append('')
else:
self.display_text_list[-1] = self.display_text_list[-1] + self.current_text_list[self.current_text_index][self.text_length]
self.text_length += 1
# When to end the dialogue:
if self.current_text_index >= self.end_text_index:
self.sfx['textBlip'].fadeout(50)
self.talking = False
self.paused = False
self.update_dialogues()
# Actually display the text (and icon):
for n in range(len(self.display_text_list)):
self.draw_text(str(self.display_text_list[n]), (self.screen_width / 4, (self.screen_height / 4 - 25)-15 + 24*n), self.text_font, (255, 255, 255), scale = 2, mode='center')
if self.display_icon in self.characters_met.keys():
char_img = self.assets[f'{self.display_icon.lower()}/idle'].images[0]
char_img = pygame.transform.scale(char_img, (char_img.get_width() * 3, char_img.get_height() * 3))
self.hud_display.blit(char_img, ((self.screen_width / 4) - char_img.get_width() / 2, self.screen_height / 4 - 80 - char_img.get_height() / 2))
elif self.display_icon:
icon = self.display_icons[self.display_icon]
icon = pygame.transform.scale(icon, (icon.get_width() * 2, icon.get_height() * 2))
self.hud_display.blit(icon, ((self.screen_width / 4) - icon.get_width() / 2, self.screen_height / 4 - 70 - icon.get_height() / 2))
def check_encounter(self, entity):
"""Determine if the player has encountered entity before.
If not, run text for introduction.
Args:
entity: Interracted entity name.
Returns:
none
"""
if not self.encounters_check[entity] and not self.dead:
self.run_text('New!', entity)
self.encounters_check[entity] = True
def load_level(self):
"""Changes currently loaded level to game.next_level.
Args:
none
Returns:
none
"""
# Save game:
self.save_game(self.save_slot)
# Add important items left on ground:
for currency in self.currency_entities:
type = str(currency.currency_type) + 's'
if type in self.not_lost_on_death:
self.wallet[type] += currency.value
self.particles = []
self.projectiles = []
self.currency_entities = []
self.sparks = []
self.clouds = _clouds.Clouds(self.assets['clouds'], count=15 if self.level_style == 'heaven' else 0)
self.player.dashing = 0
if self.next_level != 'infinite':
self.infinite_floor_max = max(self.floors['infinite'], self.infinite_floor_max)
self.floors['infinite'] = 1
if self.dead:
self.health = self.max_health
self.infinite_mode_active = False
for currency in self.wallet:
self.wallet_temp[currency] = 0 if not self.infinite_mode_active else int(self.wallet_temp[currency] / 2)
self.wallet[currency] += self.wallet_temp[currency]
self.wallet_temp[currency] = 0
elif not self.dead and not self.infinite_mode_active:
for currency in self.wallet:
self.wallet[currency] += self.wallet_temp[currency]
self.wallet_temp[currency] = 0
if not self.initialising_game and (self.current_level == 'lobby') and self.previous_level not in ['lobby', 'infinite', 'final']:
self.floors[self.previous_level] += 1
elif not self.dead and self.infinite_mode_active and self.previous_level == 'infinite':
self.floors[self.previous_level] += 1
self.player.light_size = min(90 + self.wallet['eyes'], 200)
# Spawn in entities
self.enemies = []
self.bosses = []
self.portals = []
self.characters = []
self.extra_entities = []
self.spawn_points = []
self.potplants = []
# Spawn in leaf particle spawners
self.potplants = []
for plant in self.tilemap.extract([('potplants', 0), ('potplants', 1), ('potplants', 2), ('potplants', 3), ('decor', 8), ('decor', 9)], keep=True):
self.potplants.append(pygame.Rect(plant['pos'][0], plant['pos'][1], self.tilemap.tilesize if plant['type'] == 'potplants' else self.tilemap.tilesize*2, self.tilemap.tilesize))
# Replaces spawn tile with an actual object of the entity:
for spawner in self.tilemap.extract('spawners'):
# Player
if spawner['variant'] == 0:
# Spawn at spawn_point if one is active, else default spawn pos.
if self.spawn_point and self.current_level == 'lobby':
self.player.pos[0], self.player.pos[1] = self.spawn_point[0], self.spawn_point[1]
else:
self.player.pos = spawner['pos']
self.player.air_time = 0
self.player.pos[0] += 4
self.player.pos[1] += 4
# Spawns characters if met OR in their world
elif self.entity_info[spawner['variant']]['type'] == 'character':
if self.characters_met[self.entity_info[spawner['variant']]['name']] or self.current_level != 'lobby':
self.characters.append(self.entity_info[spawner['variant']]['object'](self, spawner['pos'], (8, 15)))
# Spawns Enemies
elif self.entity_info[spawner['variant']]['type'] == 'enemy':
self.enemies.append(self.entity_info[spawner['variant']]['object'](self, spawner['pos'], self.entity_info[spawner['variant']]['size']))
# Spawns Bosses
elif self.entity_info[spawner['variant']]['type'] == 'boss':
self.bosses.append(self.entity_info[spawner['variant']]['object'](self, spawner['pos'], self.entity_info[spawner['variant']]['size']))
# Spawns Entities
elif self.entity_info[spawner['variant']]['type'] == 'extra_entity':
self.extra_entities.append(self.entity_info[spawner['variant']]['object'](self, spawner['pos'], self.entity_info[spawner['variant']]['size']))
# Spawns Spawn Points
elif self.entity_info[spawner['variant']]['type'] == 'spawn_point':
self.spawn_points.append(self.entity_info[spawner['variant']]['object'](self, spawner['pos'], self.entity_info[spawner['variant']]['size']))
# Replaces spawn tile with an actual object of the portal:
for portal in self.tilemap.extract('spawnersPortal'):
if self.portals_met[self.portal_info[portal['variant']]]:
self.portals.append(_entities.Portal(self, portal['pos'], (self.tilemap.tilesize, self.tilemap.tilesize), self.portal_info[portal['variant']]))
self.dead = False
self.player.velocity = [0, 0]
self.player.set_action('idle')
self.player.updatenearest_enemy()
self.screenshake = 0
self.transition = -30
self.scroll = [self.player.rect().centerx - self.screen_width / 4,
self.player.rect().centery - self.screen_height / 4]
self.background = pygame.transform.scale(self.assets[f'{self.heaven_hell + self.current_level}Background'], (self.screen_width / 2, self.screen_height / 2))
# Level Specifics
if self.current_level == 'lobby':
self.cave_darkness = 0
self.remove_broken_tunnels()
elif self.level_style == 'normal':
self.cave_darkness = random.randint(self.cave_darkness_range[0], self.cave_darkness_range[1])
elif self.level_style in ['grass', 'aussie', 'heaven']:
self.cave_darkness = 0
elif self.level_style in ['spooky', 'space', 'hell']:
self.cave_darkness = random.randint(self.cave_darkness_range[1]-50, self.cave_darkness_range[1])
elif self.level_style in ['rubiks']:
self.cave_darkness = 100
elif self.level_style in ['final']:
self.cave_darkness = 200
_utilities.set_area_music(self, self.level_style, self.previous_level)
# Gravity:
self.player.gravity = 0.12
if self.level_style == 'space':
self.player.gravity = 0.075
for enemy in self.enemies:
enemy.gravity = 0.075
for boss in self.bosses:
boss.gravity = 0.075
self.update_dialogues()
self.initialising_game = False
def draw_text(self, text, pos, font, colour=(0, 0, 0), scale=1, mode='topleft'):
"""Displays text onto the game.hud_display.
Args:
text: string of text to display.
pos: tuple of text coordinates.
font: text font
colour: triple of RGB values.
offset: offset from coordinates.
scale: resizes text.
mode: Determines where on the text the pos is. Can be: 'topleft', 'center', 'right'.
Returns:
none
"""
x_adj = 0
y_adj = 0
img = font.render(str(text), True, colour)
if scale != 1:
img = pygame.transform.scale(img, (img.get_width() * scale, img.get_height() * scale))
if mode == 'center':
x_adj = img.get_width() / 2
y_adj = img.get_height() / 2
elif mode == 'right':
x_adj = img.get_width()
y_adj = img.get_height()
self.hud_display.blit(img, (pos[0] - x_adj, pos[1] - y_adj))
def display_hud_text(self):
"""Displays all the HUD info onto game.hud_display as text.
Args:
none
Returns:
none
"""
text_col = (200, 200, 200) if not self.dead else (200, 0, 0)
if pygame.time.get_ticks() % 60 == 0:
self.display_fps = round(self.clock.get_fps())
hud_width = self.screen_width / 2
hud_height = self.screen_height / 2
self.draw_text('FPS: ' + str(self.display_fps), (hud_width - 10,
hud_height - 5), self.text_font, text_col, mode='right')
if self.current_level != 'lobby':
self.draw_text('Floor: ' + str(self.floors[self.current_level]), (
hud_width - 10, 20), self.text_font, text_col, mode='right')
self.draw_text('Enemies Remaining: ' + str(len(self.enemies) + len(self.bosses)),
(hud_width / 2, 30), self.text_font, text_col, mode='center')
else:
self.draw_text('Floor: Lobby', (hud_width - 10, 20),
self.text_font, text_col, mode='right')
# Display Wallet
depth = 0
for currency in self.wallet:
if self.wallet[currency] > 0 or self.wallet_temp[currency] > 0:
if self.infinite_mode_active:
extra = (' (' + str(self.wallet_gained_amount[currency]) + ' gained)' if (self.dead) else '')
else:
extra = (' (' + str(self.walletlost_amount[currency]) + ' lost)' if (self.dead and currency not in self.not_lost_on_death) else '')
currency_display = str(self.wallet[currency]) + (' + ('+str(self.wallet_temp[currency])+')' if (self.current_level != 'lobby' and not self.dead and self.wallet_temp[currency]) else '') + extra
self.hud_display.blit(self.display_icons[currency], (5, 5 + depth*15))
self.draw_text(currency_display, (25, 5 + depth*15), self.text_font, text_col)
depth += 1
# Display Player Health
for n in range(self.max_health + self.temporary_health):
if n < self.health:
heart_img = self.assets['heart']
elif n < self.max_health:
heart_img = self.assets['heartEmpty']
else:
heart_img = self.assets['heartTemp']
self.hud_display.blit(heart_img, (hud_width / 2 - ((self.max_health + self.temporary_health) * 15) / 2 + n * 15, 5))
# Display Boss Health once active
for index, boss in enumerate(self.bosses):
if boss.active: