-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.py
1594 lines (1377 loc) · 57.8 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
#!/usr/bin/env python
"""
Simple, arcade space-shooter with pixel graphics made of basic Sprites. Written
on Python 3.6 with Arcade 2.0.8 module.
To save best scores shelve module is used, and scores are saved in a distinct
file in the config_files directory. I also used pyautogui to get screen
resolution.
"""
__author__ = "Rafał Trąbski"
__copyright__ = "Copyright 2019"
__credits__ = []
__license__ = "Share Alike Attribution-NonCommercial-ShareAlike 4.0"
__version__ = "1.0.0"
__maintainer__ = "Rafał Trąbski"
__email__ = "[email protected]"
__status__ = "Development"
import os
import math
import string
import random
import shelve
import arcade
import pyautogui
from functools import partial
from simple_arcade_menu import SharedVariable, Cursor, Menu, SubMenu, Button, \
Slider, CheckBox
from config_loader.config_loader import load_config_from_file
# constants:
TITLE = "Red Invaders"
# TODO: adjustment o window size to the different screen sizes [ ]
SCREEN_WIDTH = pyautogui.size()[0] # int(2048*0.9)
SCREEN_HEIGHT = pyautogui.size()[1] # int(1280*0.9)
SPRITES_SCALE = int(SCREEN_WIDTH / SCREEN_HEIGHT) * 1.5
FPS = 45 # frames per second used by arcade.window to refresh the screen
MARGIN, SCORE_STRIPE = 40 * SPRITES_SCALE, 40
BACKGROUND_SPEED = 0.3
STARS_DENSITY = 1
RED, WHITE = arcade.color.RED, arcade.color.WHITE
YELLOW, BLUE = arcade.color.YELLOW_ORANGE, arcade.color.ELECTRIC_BLUE
STARS_COLORS = (WHITE,)*4 + (BLUE,)*2 + (YELLOW,)*2 + (RED,)
STAR_SIZES = (1,)*4 + (2,)*2 + (3,)
BACKGROUND_COLOR, GREEN = arcade.color.BLACK, arcade.color.BRIGHT_GREEN
PATH = os.path.dirname(os.path.abspath(__file__)) # os.getcwd()
GRAPHICS_PATH = PATH + "/graphics/"
SOUNDS_PATH = PATH + "/sounds/"
CONFIG_PATH = PATH + "/config_files/"
CONFIG_FILE = "game_config.txt"
SCORES_FILE = "best_scores.data"
SPACESHIP_SPEED = 15
SPACESHIP_STRAFE = 10
LASER_GUN_SINGLE = "laser_single"
LASER_GUN_LEFT = "laser_left"
LASER_GUN_RIGHT = "laser_right"
TURRETS, TURRET_SMALL = "turrets", "turret_small"
UPWARD = 0.0
DOWNWARD = 180.0
EXPLOSION = "explosion_sound"
HIT_SOUND = "hit.wav"
ROCKET_SOUND = "rocket"
POWERUP_SOUND = "powerup.wav"
POWERUP_TIME = 1800
POWERUP_CHANCE = 0
POWERUP_ROCKETS_1, POWERUP_ROCKETS_2 = "powerup_rockets_1", "powerup_rockets_2"
POWERUP_ROCKETS_3, POWERUP_LASER_DUAL = "powerup_rockets_3", "powerup_laser_dual"
POWERUP_LASER_STRONG, POWERUP_SHIELD = "powerup_laser_fast", "powerup_shield"
TEXTURE, HEALTH, SHIELD, ROCKETS = "texture", "health", "shield", "rockets"
SPEED, WEAPON, PLAYER, HOSTILES = "speed", "weapon", "player", "hostiles"
POWERUPS, LEVELS, RATINGS, SCORES = "powerups", "levels", "ratings", "scores"
LASERS, DAMAGES, SOUNDS, TYPES = "lasers", "damages", "sounds", "types"
ROF, KINETIC = "rof", "kinetics"
MAIN_MENU, INSTRUCTIONS, OPTIONS_MENU = "main", "instructions_menu", "options"
MIN_DISTANCE, MAX_DISTANCE = "preferred_min_distance", "preferred_max_distance"
for _ in ("game", "settings", "player", "hostiles", "weapons", "levels",
"powerups"):
globals()[_] = None
# global dict of sounds used in game:
sounds = {}
def get_image_path(filename: str):
"""
Produce TESTS_PATH to the texture, which name is provided as parameter.
:param filename: str -- name of the texture file to be loaded without
extension
:return: str -- absolute TESTS_PATH of texture
"""
return GRAPHICS_PATH + filename + ".png"
def get_sound_path(filename: str):
"""
Produce TESTS_PATH to the sound file, which name is provided as parameter.
:param filename: str -- name of the sound file
:return: str -- absolute TESTS_PATH of sound file
"""
return SOUNDS_PATH + filename
def play_sound(sound: str):
"""
Play sound by arcade.sound module. Sounds are global arcade.sound objects.
:param sound: str -- name of the sound file without .wav extension
"""
if sound not in sounds.keys():
sounds[sound] = arcade.load_sound(get_sound_path(sound))
arcade.play_sound(sounds[sound])
class SpaceObject(arcade.Sprite):
"""
Each object generated in the game is a SpaceObject. It is basically a
wrapper used to correctly spawn arcade.Sprite object with usage of
helper function get_image_path().
"""
def __init__(self, filename: str, size: int = 1):
# this is what we need this base-class for:
super().__init__(get_image_path(filename), SPRITES_SCALE * size)
def update(self):
# guarantee that angle would be in range 0 to 360 degrees
self.angle = self.angle % 360
super().update()
class Spaceship(SpaceObject):
"""
Each spaceship in game is an instance of this class, even player ship.
"""
def __init__(self, filename: str):
"""
Create new Spaceship instance. IMPORTANT: arcade.Sprite requires
passing a basic texture filename as a first argument. Pass it
without '.png' extension - Spaceobject class provides it automatically.
:param filename: str -- name of texture file for a Sprite basic texture
(IMPORTANT: without extension!)
"""
super().__init__(filename)
self.main_weapon = None
self.secondary_weapon = None
self.rate_of_fire = None
self.last_shot = None
self.gun_slots = []
self.rockets = 0
self.last_shot = 0
self.shield = 0
self.health = 10
self.hit = False
self.shield_hit = False
def rearm(self, weapon: str):
"""
Change weapon used by the ship, modify gun slots positions and rate of
fire.
:param weapon: str -- name of weapon to arm ship with
"""
if weapon in weapons[LASERS]:
self.main_weapon = weapon
self.rate_of_fire = weapons[ROF][weapon]
if not self.gun_slots:
self.gun_slots = [[LASER_GUN_SINGLE, self.top, self.center_x]]
elif len(self.gun_slots) == 1:
self.gun_slots = [[LASER_GUN_LEFT, self.top, self.left],
[LASER_GUN_RIGHT, self.top, self.right]]
else:
pass
elif weapon in weapons[KINETIC]:
self.main_weapon = weapon
self.rate_of_fire[weapon] = weapons[ROF][weapon]
pass
else:
self.secondary_weapon = weapon
def shoot(self):
"""
Handles a single weapon shot initializing creation of new Projectile
instance.
"""
for slot in self.gun_slots:
play_sound(weapons[SOUNDS][self.main_weapon])
if isinstance(self, PlayerShip):
power = self.powerup_damage_mod
else:
power = 1
game.projectiles.append(
Projectile(self.main_weapon, power, self.angle, slot))
self.last_shot = game.game_time
def launch_rocket(self):
"""
Handle launching a rocket.
"""
play_sound(weapons[SOUNDS][self.secondary_weapon])
game.projectiles.append(
Projectile(self.secondary_weapon, 1, self.angle,
self.gun_slots[0]))
self.rockets -= 1
def damage(self, damage: int):
"""
Handle the damage dealt to the Spaceship object. First eat shield, then
take health, then destroy ship.
"""
if self.shield > damage:
self.shield -= damage
if not self.shield_hit:
self.shield_hit = True
self.set_texture(-2)
hit_color = RED if self == game.player else GREEN
game.create_hint("Shield hit!", self.center_x, self.center_y,
0, 0, hit_color, 10, 1)
else:
self.health -= (damage - self.shield)
self.shield = 0
if not self.hit:
self.hit = True
self.set_texture(-1)
hit_color = RED if self == game.player else GREEN
game.create_hint("Hit!", self.center_x, self.center_y, 0, 0,
hit_color, 10, 1)
self.kill() if self.health < 1 else play_sound(HIT_SOUND)
def update(self):
super().update()
if self.hit or self.shield_hit:
self.clear_hit_texture()
for slot in self.gun_slots:
slot[1] = self.top if self.angle == UPWARD else self.bottom
if slot[0] == LASER_GUN_SINGLE:
slot[2] = self.center_x
elif slot[0] == LASER_GUN_LEFT:
slot[2] = self.left
else:
slot[2] = self.right
self.obey_margins() # shots does not obey screen margins
def clear_hit_texture(self):
"""Replace 'hit' texture with normal one, after ship being hit."""
if self.shield > 0:
self.shield_hit = False
else:
self.hit = False
self.set_texture(0)
def obey_margins(self):
"""
Guarantee that no Spaceship would go out the game window.
"""
if self.center_x < MARGIN:
self.center_x = MARGIN
elif self.center_x > SCREEN_WIDTH - MARGIN:
self.center_x = SCREEN_WIDTH - MARGIN
if self.center_y < MARGIN + SCORE_STRIPE:
self.center_y = MARGIN + SCORE_STRIPE
elif self.center_y > SCREEN_HEIGHT - MARGIN:
self.center_y = SCREEN_HEIGHT - MARGIN
def kill(self):
super().kill()
game.explosions.append(Explosion(self.center_x, self.center_y))
class PlayerShip(Spaceship):
"""
Subclass for the player ship.
"""
RIGHT, LEFT, UP, DOWN, STOP = (SPACESHIP_STRAFE, -SPACESHIP_STRAFE,
SPACESHIP_SPEED, -SPACESHIP_SPEED, 0)
def __init__(self, textures_list: list):
super().__init__("player_ship/" + textures_list[0])
self.powerups = {POWERUP_LASER_DUAL: [False, 0],
POWERUP_LASER_STRONG: [False, 0]}
self.powerup_damage_mod = 1
self.center_x = SCREEN_WIDTH / 2
self.center_y = SCREEN_HEIGHT / 2
self.rearm(player[WEAPON])
self.load_textures(textures_list[1:])
self.rockets = player[ROCKETS]
if self.rockets: self.rearm(weapons[ROCKETS][1])
self.shooting = False
self.overheat = 0
self.horizontal = PlayerShip.STOP
self.vertical = PlayerShip.STOP
def load_textures(self, textures_list: list):
"""
Set up all textures for a playership sprite. Ship texture changes
accordingly to themovementnt direction.
"""
textures = ["player_ship/" + texture for texture in textures_list]
[self.append_texture(
arcade.load_texture(get_image_path(texture), scale=SPRITES_SCALE))
for texture in textures]
def update_texture(self):
"""
Toggle through self.textures accordingly to display corrects engines
working (keys on keyboard pressed).
"""
if self.change_y > 0:
if self.change_x > 0:
self.set_texture(2) # key D or RIGHT
elif self.change_x < 0:
self.set_texture(3) # key A o LEFT
else:
self.set_texture(1) # key W or UP
elif self.change_y < 0:
if self.change_x > 0:
self.set_texture(7) # key D
elif self.change_x < 0:
self.set_texture(8) # key A
else:
self.set_texture(6) # key S or DOWN
else:
if self.change_x > 0:
self.set_texture(5) # key D
elif self.change_x < 0:
self.set_texture(4) # key A
else:
self.set_texture(0) # no key pressed
def toggle_shooting(self):
"""
Switch between 'shooting' and 'not-shooting' modes. If self.shooting is
True, PlayerShip would fire it's main weapon as fast as it's ROF
variable permits for, and as long as self.overheat is not >= 100.
"""
self.shooting = not self.shooting
def update(self):
super().update()
# set the movement accordingly to the keys pressed by player:
self.update_movement()
self.check_for_collisions()
# update texture accordingly to the movement (to show work of engines):
self.update_texture()
self.manage_powerups()
if all((self.shooting, self.last_shot is not None,
game.game_time - self.last_shot >= self.rate_of_fire)):
game.shots_fired += 1
self.last_shot = game.game_time
self.overheat += 5 # TODO: overheating system [ ]
self.shoot()
def update_movement(self):
"""
Set the movement speed values accordingly to the key pressed by the
player.
"""
self.change_x = self.horizontal
self.change_y = self.vertical
def check_for_collisions(self):
"""
Check if player ship collides with hostile ships or meteorites (?). If
so, destroy it.
"""
hit_list = arcade.check_for_collision_with_list(self, game.hostiles)
if not game.god_mode:
for hit in hit_list:
hit.kill()
self.kill()
break
def manage_powerups(self):
"""
Check each active power-up effect if it's duration surpassed booster
game_time limit. If so, terminate it.
"""
for booster in self.powerups:
if booster[0]:
if self.powerups[booster][1] == 0:
self.end_powerup(booster)
else:
self.powerups[booster][1] -= 1
def apply_powerup(self, booster_type: str):
"""
Apply a powerup effect to the player's ship.
"""
hints = {POWERUP_ROCKETS_1: "ROCKETS +1",
POWERUP_ROCKETS_2: "ROCKETS +2",
POWERUP_ROCKETS_3: "ROCKETS +3",
POWERUP_LASER_DUAL: "DUAL LASER CANNON +30 sec.",
POWERUP_LASER_STRONG: "STRONGER LASER CANON +30sec",
POWERUP_SHIELD: "ENERGETIC SHIELD +50"}
if booster_type == POWERUP_LASER_DUAL:
if not self.powerups[POWERUP_LASER_DUAL][0]:
self.powerups[POWERUP_LASER_DUAL][0] = True
self.rearm(weapons[LASERS][0])
self.rearm(weapons[LASERS][0])
self.powerups[POWERUP_LASER_DUAL][1] += POWERUP_TIME
elif booster_type == POWERUP_LASER_STRONG:
if not self.powerups[POWERUP_LASER_STRONG][0]:
self.powerups[POWERUP_LASER_STRONG][0] = True
self.powerups[POWERUP_LASER_STRONG][1] += POWERUP_TIME
self.powerup_damage_mod += 0.25
elif booster_type == POWERUP_ROCKETS_1:
self.rearm(weapons[ROCKETS][1])
self.rockets += 1
elif booster_type == POWERUP_ROCKETS_2:
self.rearm(weapons[ROCKETS][1])
self.rockets += 2
elif booster_type == POWERUP_ROCKETS_3:
self.rearm(weapons[ROCKETS][1])
self.rockets += 3
elif booster_type == POWERUP_SHIELD:
self.shield += 50
game.create_hint(hints[booster_type], color=GREEN, size=25, time=2)
def end_powerup(self, booster):
"""
Remove powerup effect after 30 seconds.
"""
if booster == POWERUP_LASER_DUAL:
self.main_weapon = None
self.gun_slots = []
self.rearm(weapons[LASERS][0])
else:
self.powerup_damage_mod = 1
self.powerups[booster][0] = False
def kill(self):
super().kill()
game.if_new_high_score()
class Hostile(Spaceship):
"""
Subclass for enemies. They can do many funny things, like avoiding player's
shots.
"""
def __init__(self, difficulty: int):
max_enemy = difficulty + 1 if difficulty <= len(
hostiles[HOSTILES]) else len(hostiles[HOSTILES])
hostile = random.choice(hostiles[HOSTILES][
0:max_enemy]) # TODO: better enemies spawning?
super().__init__("hostiles/" + hostile)
self.model = hostile
self.speed = hostiles[SPEED][hostile]
self.health = hostiles[HEALTH][hostile]
self.shield = hostiles[SHIELD][hostile]
# tricky, lesser number, higher chance that hostile will evade:
self.evasiveness = 40 - difficulty
self.avoiding = False
self.targeted_position = None
self.dangerous = None
self.playerX, self.playerY = None, None
self.turrets = self.install_turrets()
self.append_texture(arcade.load_texture(
get_image_path("hostiles/" + hostile + "_shield"),
scale=SPRITES_SCALE))
self.append_texture(
arcade.load_texture(get_image_path("hostiles/" + hostile + "_hit"),
scale=SPRITES_SCALE))
for i in range(hostiles[WEAPON][hostile][0]):
self.rearm(hostiles[WEAPON][hostile][1])
def install_turrets(self):
"""
If hostile ship has turrets, spawn correct Sprites, and place them in
proper positions.
:return: None or list of turrets (SpaceObject instances)
"""
if self.model in hostiles[TURRETS]:
installed_turrets = []
for turret in hostiles[TURRETS][self.model]:
new_turret = Turret(turret[0], turret[1], turret[2], turret[3],
turret[4], turret[5])
new_turret.center_x = self.left + turret[2]
new_turret.center_y = self.top - turret[3]
new_turret.angle = self.angle
installed_turrets.append(new_turret)
game.turrets.append(new_turret)
return installed_turrets
return None
def update(self):
super().update()
self.playerX, self.playerY = game.player.center_x, game.player.center_y
if self.in_danger():
self.evade()
if (not self.avoiding or not self.targeted_position) \
and random.randint(1, 100) > 75: self.maneuvre()
if not self.avoiding or not self.targeted_position:
self.aim_at_player()
# if in line with a player, enemy fires it's weapon:
if game.game_time - self.last_shot > self.rate_of_fire and abs(
self.center_x - game.player.center_x) < 50:
self.shoot()
self.update_speed() # each enemy ship has it's own speed modifier
if self.turrets:
self.handle_turrets()
def damage(self, damage: int):
game.hits += 1
super().damage(damage)
def in_danger(self):
"""
Check if there is a player-shot projectile in line of this enemy ship.
"""
self.avoiding = False
for projectile in game.projectiles:
if projectile.angle == UPWARD:
if projectile.center_y < self.center_y:
if abs(self.center_x - projectile.center_x) < 75:
# there is the tricky part!
if random.randint(1, 100) > self.evasiveness:
self.dangerous = projectile
return True
return self.avoiding
def evade(self):
"""
Check best direction to avoid being hit.
"""
if not self.avoiding:
if self.center_x + 100 >= SCREEN_WIDTH - MARGIN or \
self.center_x < self.dangerous.center_x:
self.change_x = -SPACESHIP_STRAFE
elif self.center_x < MARGIN + 100 or \
self.center_x > self.dangerous.center_x:
self.change_x = SPACESHIP_STRAFE
else:
self.change_x = random.choice(
(SPACESHIP_SPEED, -SPACESHIP_SPEED))
self.avoiding = True
def maneuvre(self):
"""
Makes ship doing random maneuvers to add mess to hostiles movement.
"""
min_distance, max_distance = hostiles[MIN_DISTANCE][self.model], \
hostiles[MAX_DISTANCE][self.model]
target_x, target_y = (random.randint(MARGIN, SCREEN_WIDTH - MARGIN),
SCREEN_HEIGHT * random.uniform(min_distance,
max_distance))
self.targeted_position = (target_x, target_y)
if abs(self.center_x - target_x) <= 50 and abs(
self.center_y - target_y) < 50:
self.targeted_position = False
return
if self.center_x < target_x:
self.change_x = SPACESHIP_STRAFE
elif self.center_x > target_x:
self.change_x = -SPACESHIP_STRAFE
if self.center_y < target_y:
self.change_y = SPACESHIP_STRAFE
elif self.center_y > target_y:
self.change_y = -SPACESHIP_SPEED
def aim_at_player(self):
"""
Try to move Hostile left or right to position it just above player's
ship.
"""
if abs(self.center_x - self.playerX) > SPRITES_SCALE / 2:
if self.center_x < self.playerX:
self.change_x = SPACESHIP_STRAFE
elif self.center_x > self.playerX:
self.change_x = -SPACESHIP_STRAFE
else:
self.change_x = 0
def handle_turrets(self):
"""
If hostile ship has at least 1 turret object attached to it, handle
their position, rotation and shooting at the player.
"""
for i in range(len(self.turrets)):
turret = self.turrets[i]
# position:
turret.center_x = self.center_x + turret.offset_x
turret.center_y = self.center_y - turret.offset_y
# rotation - aiming at player:
radians = math.atan2(self.playerX - self.center_x,
self.playerY - self.center_y)
turret.angle = -math.degrees(radians)
# shooting at player:
if game.game_time - turret.last_shot > turret.rate_of_fire:
self.turret_shot(turret)
turret.last_shot = game.game_time
@staticmethod
def turret_shot(turret):
"""
Each turret shots independently from it's ship.
:param turret: Turret instance
"""
play_sound(weapons[SOUNDS][turret.gun])
shot = Projectile(turret.gun, 1, turret.angle,
["", turret.center_y, turret.center_x])
game.projectiles.append(shot)
def update_speed(self):
"""
Each enemy ship has it's own speed modifier: self.speed which is used
to modify base speed.
"""
self.change_x *= self.speed
self.change_y *= self.speed
def kill(self):
if self.turrets:
for turret in self.turrets:
turret.kill()
super().kill()
score = hostiles[SCORES][self.model]
game.score += score
game.destroyed += 1
game.create_hint(str(score), self.center_x, self.center_y, 0, -5,
GREEN, 12 + ((score / 10) % 10))
self.spawn_power_up()
def spawn_power_up(self):
"""
Create new PowerUp instance when hostile spaceship is destroyed and
additional conditions are met.
"""
chance = (POWERUP_CHANCE
+ hostiles[SCORES][self.model] / 10
- game.difficulty
+ (game.game_time - PowerUp.last_spawn) / FPS)
if random.randint(1, 100) <= chance:
PowerUp(self.center_x, self.center_y)
class Projectile(SpaceObject):
"""
Basic class for all kind of 'shots' fired in game by the player and his
enemies.
"""
def __init__(self, type_: str, power: int, angle: float,
gun_position: list):
"""
Initialize new Projectile object, when player or enemy fires it's
weapon.
:param type_: str -- type of the shot
:param power: float -- damage modifier
:param angle: float -- angle the shot was fired
:param gun_position: list [int, int] -- x and y coordinates of firing
point
"""
super().__init__("shots/" + type_, power)
self.type_ = type_
self.angle = angle
self.target, self.marker = None, None
self.damage = weapons[DAMAGES][type_]
self.speed = weapons[SPEED][type_]
self.center_x = gun_position[2]
self.center_y = gun_position[1]
self.change_x, self.change_y = self.calculate_speed_vector()
def calculate_speed_vector(self):
"""
Calculate proper elements of the speed vector of projectile fired from
gun. Required for rotating turrets.
:return: float, float -- x and y velocities
"""
radians = math.radians(self.angle)
velocity = weapons[SPEED][self.type_]
change_y = math.cos(radians)
change_x = -math.sin(radians)
return change_x * velocity, change_y * velocity
def update(self):
super().update()
# delete each projectile which goes off the screen:
self.check_if_on_the_screen()
if self.type_ in weapons[ROCKETS]: # rockets are fancy - they turn!
self.rocket_autoaim()
self.check_for_hits()
def draw(self):
super().draw()
if self.type_ in weapons[ROCKETS] and self.target:
pass
def rocket_autoaim(self):
"""
Method used only by 'rockets'. They make turns towards enemies.
"""
# acquire target if has any and there are possible targets
if not self.target and len(game.hostiles) > 0:
if self.angle == UPWARD: # if rocket fired by player
# TODO: rockets ignoring targets already acquired by other
# rockets and take next one [ ][ ], test it [ ]
# closest enemy ship:
self.target = arcade.get_closest_sprite(self, game.hostiles)[0]
else:
self.target = game.player
if self.target: # making turns towards the target:
if self.center_x < self.target.center_x:
self.change_x = SPACESHIP_STRAFE
elif self.center_x > self.target.center_x:
self.change_x = -SPACESHIP_STRAFE
if not self.marker:
self.marker = True
game.add_target_marker(self, self.target)
def check_if_on_the_screen(self):
"""
Destroy a Projectile if it went off the screen to save memory.
"""
condition_a = 0 > self.center_y or self.center_y > SCREEN_HEIGHT
condition_b = 0 > self.center_x or self.center_x > SCREEN_WIDTH
if condition_a or condition_b: self.kill()
def check_for_hits(self):
"""
Check if a Projectile hit any hostile ship (if shot by player) or
player ship (if shot by hostile ship). If so, deal the damage and
destroy Projectile instance.
"""
if self.type_.startswith("player"):
hit_list = arcade.check_for_collision_with_list(self,
game.hostiles)
else:
hit_list = arcade.check_for_collision_with_list(self, game.players)
for hit in hit_list:
hit.damage(self.damage)
self.kill()
break
class Turret(SpaceObject):
def __init__(self, filename: str, gun: str, offset_x: int, offset_y: int,
rof: int, rot: int):
"""
Initialize new Turret instance fo a Spaceship object.
:param filename: str -- name o the turret
:param gun: str -- name of the weapon model
:param offset_x: int -- offset from ship.center_x in pixels
:param offset_y: int -- offset from ship.center_y in pixels
:param rof: int -- rate of fire
:param rot: int -- rotation speed
"""
super().__init__("hostiles/" + filename)
self.gun = gun
self.rate_of_fire = rof
self.rotation_speed = rot
self.last_shot = 0
self.offset_x = offset_x
self.offset_y = offset_y
class PowerUp(SpaceObject):
"""
All kinds of collectible powerups available to use by player.
"""
last_spawn = 0 # spawn time kept to update spawning chance
def __init__(self, pos_x: float, pos_y: float):
self.type_ = random.choice(powerups[POWERUPS])
super().__init__("powerups/" + self.type_)
self.center_x = pos_x
self.center_y = pos_y
self.change_y = -SPACESHIP_STRAFE
PowerUp.last_spawn = game.game_time
game.powerups.append(self)
def update(self):
super().update()
if 0 > self.center_y:
self.kill()
if arcade.check_for_collision(self, game.player):
play_sound(POWERUP_SOUND)
game.player.apply_powerup(self.type_)
self.kill()
class Explosion(SpaceObject):
"""
This object is spawned when something explodes.
"""
textures_list = []
for i in range(1, 40):
tex = f"explosion/explosion{i:04d}"
textures_list.append(arcade.load_texture(get_image_path(tex)))
def __init__(self, x, y):
super().__init__("explosion/explosion0000")
self.textures = Explosion.textures_list
self.center_y = y
self.center_x = x
self.current_texture = 0
self.detonation = int(game.game_time)
play_sound(random.choice(("explosion.wav", "explosion_2.wav")))
def update(self):
super().update()
self.current_texture += 1
if self.current_texture < len(self.textures):
self.set_texture(self.current_texture)
else:
self.kill()
class Game(arcade.Window):
"""
Basic class creating main game window and managing the game.
"""
def __init__(self, width, height, title, fullscreen, resizeable,
test: bool = False):
"""
Initialization of new game window and game logic.
:param width: int -- vertical height of game window
:param height: int -- horizontal size of game window
:param title: str -- title of window displayed s window name
:param fullscreen: bool -- if game should be started in full-screen
:param resizeable: bool -- if player can resize the window
"""
super().__init__(width, height, title, fullscreen, resizeable)
self.in_menu = False # game starts in the menu
self.cursor = Cursor(self, GRAPHICS_PATH, "/cursors/cursor")
self.menu = None
arcade.set_background_color(BACKGROUND_COLOR)
self.set_update_rate(1 / FPS)
self.difficulty = 0
self.next_difficulty_raise = 0
# Additional elements displayed on the screen:
self.hints = None
self.stars = None
self.targets_markers = None
self.players = None
self.hostiles = None
self.projectiles = None
self.powerups = None
self.turrets = None
self.explosions = None
# all the arcade.spriteLists would be put into this list:
self.sprites_lists = None
self.player = None
self.player_name = ""
self.paused = False
# we have two 'times' because we need to keep time updating when game
# is paused or in scores table
self.game_time, self.pause_time = 0.0, 0.0
self.shots_fired = 0
self.hits = 0
self.destroyed = 0
self.score = 0
self.best_scores = None
self.should_display_scores = False
self.new_score_index = None
# game mode in which stronger enemies are spawned in larger amounts
# when time flows:
self.challenge_mode = SharedVariable(True)
self.god_mode = False
if not test:
self.setup_menus()
def __setattr__(self, key, value):
self.__dict__[key] = value
def setup_menus(self):
"""
Create new Menu object as current game menu.
"""
# top-level menu:
elements, background = self.create_main_menu()
main_menu = SubMenu(name=MAIN_MENU, menu_elements=elements,
background=background, main=True)
# initialize Menu object and add all the SubMenus:
self.menu = Menu(self, main_menu)
# hwo-to-play instructions submenu:
elements, background = self.create_instructions_submenu()
instructions = SubMenu(name=INSTRUCTIONS,
menu_elements=elements, background=background)
# game options submenu:
elements = self.create_options_submenu()
options = SubMenu(name=OPTIONS_MENU, menu_elements=elements)
self.menu.add_submenu(instructions)
self.menu.add_submenu(options)
self.in_menu = True
def create_main_menu(self):
"""Generate top-level SubMenu."""
# initialize Buttons which we require in our game main-menu:
padding, pos_x, pos_y = MARGIN * 3, SCREEN_WIDTH / 2, SCREEN_HEIGHT
start_game_button = Button("START GAME", pos_x, pos_y - padding,
function=self.setup_new_game)
game_options_button = Button("OPTIONS", pos_x, pos_y - (padding * 2),
function=self.show_options_menu)
how_to_play_button = Button("HOW TO PLAY", pos_x,
pos_y - (padding * 3),
function=self.show_instructions_menu)
quit_game_button = Button("QUIT GAME", pos_x, pos_y - (padding * 4),
function=arcade.close_window)
# put them into the list which will be passed to the Menu class:
elements = [start_game_button, game_options_button, how_to_play_button,
quit_game_button]
# create background texture for our main menu:
background = arcade.load_texture(
GRAPHICS_PATH + "/menu/menu_background.jpg")
return elements, background
def create_instructions_submenu(self):
"""Generate game instructions SubMenu."""
elements = [
Button("BACK", MARGIN, SCREEN_HEIGHT - MARGIN,
function=partial(self.menu.toggle_submenu, MAIN_MENU))]
background = arcade.load_texture(
GRAPHICS_PATH + "/menu/instruction_black.png")
return elements, background
def create_options_submenu(self):
difficulty_slider = Slider(object_=self,
attribute="difficulty",
start_value=self.difficulty,
attribute_min=0,
attribute_max=10,
pos_x=SCREEN_WIDTH / 2,
pos_y=SCREEN_HEIGHT / 2)
arcade_checkbox = CheckBox(object_=self,
attribute="challenge_mode",
start_value=self.challenge_mode,
pos_x=SCREEN_WIDTH / 2,
pos_y=SCREEN_HEIGHT / 1.5)
elements = [
Button("BACK", MARGIN, SCREEN_HEIGHT - MARGIN,
function=partial(self.menu.toggle_submenu, MAIN_MENU)),
difficulty_slider, arcade_checkbox]
return elements
def setup_new_game(self):
"""
Setup all game variables. Used when new game is started and when game
is restarted after player's death.
"""
self.in_menu = False
self.hints = []
self.stars = self.create_stars()
self.targets_markers = []