-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspace_shooter.py
More file actions
3169 lines (2697 loc) · 139 KB
/
space_shooter.py
File metadata and controls
3169 lines (2697 loc) · 139 KB
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
import pygame
import sys
import random
import math
from pygame.locals import *
import os
from barrier_goliath import BarrierGoliath
import create_assets
# Set SDL audio driver to a fallback before initializing
#os.environ['SDL_AUDIODRIVER'] = 'dummy' # This uses a dummy audio driver
# Initialize pygame
pygame.init()
pygame.mixer.init() # Initialize sound mixer
# Load sounds
try:
shoot_sound = pygame.mixer.Sound("assets/sounds/laser.wav")
shoot_sound.set_volume(0.3) # Set to 30% volume to avoid being too loud
except:
print("Warning: Could not load sound files")
shoot_sound = None
# Get the user's screen info for proper fullscreen
screen_info = pygame.display.Info()
SCREEN_WIDTH = screen_info.current_w
SCREEN_HEIGHT = screen_info.current_h
# Game design constants (internal resolution)
WIDTH = int(SCREEN_WIDTH * 0.8)
HEIGHT = int(SCREEN_HEIGHT * 0.8)
FPS = 60
# Calculate centering offset for gameplay elements
OFFSET_X = (SCREEN_WIDTH - WIDTH) // 2
OFFSET_Y = (SCREEN_HEIGHT - HEIGHT) // 2
# Create fullscreen display at native resolution
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.FULLSCREEN)
pygame.display.set_caption("Xbacab")
clock = pygame.time.Clock()
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
DARK_BLUE = (0, 0, 128)
LIGHT_BLUE = (173, 216, 230)
# Load game assets
def load_image(name, scale=1):
try:
image = pygame.image.load(name).convert_alpha()
size = image.get_size()
scaled_image = pygame.transform.scale(image, (int(size[0] * scale), int(size[1] * scale)))
return scaled_image
except pygame.error:
# Create a default image if the file is not found
surf = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.rect(surf, BLUE, (0, 0, 50, 50))
pygame.draw.line(surf, RED, (0, 0), (50, 50), 3)
pygame.draw.line(surf, RED, (50, 0), (0, 50), 3)
return surf
# Create resource folders
if not os.path.exists("assets"):
os.makedirs("assets")
# Player class
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
try:
self.image = load_image("assets/images/player_ship.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((50, 40), pygame.SRCALPHA)
pygame.draw.polygon(self.image, BLUE, [(0, 40), (25, 0), (50, 40)])
self.rect = self.image.get_rect()
# Position player within the original game coordinates (no offset)
self.rect.centerx = WIDTH // 2
self.rect.bottom = HEIGHT - 20
self.speedx = 0
self.speedy = 0
# Adjust stats based on difficulty
if game_state.difficulty == "easy":
self.health = 200
self.max_health = 200
self.energy = 150
self.max_energy = 150
self.energy_regen = 0.7
self.max_drones = 6 # More drones on easy
elif game_state.difficulty == "normal":
self.health = 150
self.max_health = 150
self.energy = 100
self.max_energy = 100
self.energy_regen = 0.5
self.max_drones = 4 # Standard drones
elif game_state.difficulty == "hard":
self.health = 100
self.max_health = 100
self.energy = 80
self.max_energy = 80
self.energy_regen = 0.3
self.max_drones = 3 # Fewer drones on hard
self.shield_active = False
self.shield_strength = 50
self.shoot_delay = 100 # 200ms = 5 shots per second
self.last_shot = 0
self.special_delay = 2000
self.last_special = 0
self.hyper_dash_active = False
self.hyper_dash_duration = 500
self.hyper_dash_start = 0
self.invincible = False
self.invincible_duration = 1000
self.invincible_start = 0
self.weapon_level = 1
self.weapon_type = "normal" # normal, spread, laser, homing
self.drones = 0
self.drone_list = []
# Add dying state
self.dying = False
self.dying_start = 0
self.dying_duration = 1500
self.blink_interval = 150
self.visible = True
# Track mouse position for laser aiming
self.mouse_pos = (WIDTH // 2, 0)
def update(self):
# Check if dying
if self.dying:
now = pygame.time.get_ticks()
# Blink effect
if (now - self.dying_start) % self.blink_interval < self.blink_interval // 2:
self.visible = True
else:
self.visible = False
# Check if dying animation is complete
if now - self.dying_start > self.dying_duration:
return True # Player is fully dead
return False # Still in dying animation
# Natural health regeneration in easy mode
if game_state.difficulty == "easy":
self.health = min(self.max_health, self.health + 0.02) # Slowly regenerate health
# Update keyboard controls
keystate = pygame.key.get_pressed()
# Update energy
if self.shield_active:
self.energy -= 0.5
if self.energy <= 0:
self.shield_active = False
# Movement
self.speedx = 0
self.speedy = 0
# Regular movement
speed_factor = 2.5 if self.hyper_dash_active else 1
base_speed = 8
if keystate[K_LEFT] or keystate[K_a]:
self.speedx = -base_speed * speed_factor
if keystate[K_RIGHT] or keystate[K_d]:
self.speedx = base_speed * speed_factor
if keystate[K_UP] or keystate[K_w]:
self.speedy = -base_speed * speed_factor
if keystate[K_DOWN] or keystate[K_s]:
self.speedy = base_speed * speed_factor
# Update position
self.rect.x += self.speedx
self.rect.y += self.speedy
# Keep the player within bounds of the screen
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
if self.rect.bottom > HEIGHT:
self.rect.bottom = HEIGHT
if self.rect.top < 0:
self.rect.top = 0
# Automatically shoot
now = pygame.time.get_ticks()
# Space or mouse button check is now handled in the main game loop
# SWAPPED: Energy shield is now E key
if keystate[K_e] and self.energy > 0:
self.shield_active = True
self.energy -= 1
else:
self.shield_active = False
# Energy regeneration
if not self.shield_active and self.energy < self.max_energy:
self.energy += self.energy_regen
# Check hyper dash status
if self.hyper_dash_active:
if now - self.hyper_dash_start > self.hyper_dash_duration:
self.hyper_dash_active = False
# Check invincibility status
if self.invincible:
if now - self.invincible_start > self.invincible_duration:
self.invincible = False
def shoot(self):
# Check if enough time has passed since last shot (CPS limit)
now = pygame.time.get_ticks()
if now - self.last_shot < self.shoot_delay:
return # Don't shoot if firing too quickly
# Update last shot time
self.last_shot = now
# Now handle the actual shooting based on weapon type
if self.weapon_type == "normal":
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
# Add additional bullets based on weapon level
if self.weapon_level >= 2:
bullet1 = Bullet(self.rect.left + 10, self.rect.top + 10)
bullet2 = Bullet(self.rect.right - 10, self.rect.top + 10)
all_sprites.add(bullet1, bullet2)
bullets.add(bullet1, bullet2)
if self.weapon_level >= 3:
bullet3 = Bullet(self.rect.left + 5, self.rect.top + 20)
bullet4 = Bullet(self.rect.right - 5, self.rect.top + 20)
all_sprites.add(bullet3, bullet4)
bullets.add(bullet3, bullet4)
# Drones also shoot normal bullets - let their own logic handle it
for drone in self.drone_list:
drone.shoot()
elif self.weapon_type == "spread":
for angle in range(-30, 31, 30):
bullet = SpreadBullet(self.rect.centerx, self.rect.top, angle)
all_sprites.add(bullet)
bullets.add(bullet)
# Drones also shoot spread bullets - let their own logic handle it
for drone in self.drone_list:
drone.shoot()
elif self.weapon_type == "bouncing":
# Create a bouncing bullet that targets enemies
bullet = BouncingBullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
# Drones also shoot bouncing bullets
for drone in self.drone_list:
drone.shoot()
elif self.weapon_type == "homing":
# Number of homing missiles based on weapon level
num_missiles = self.weapon_level
# Create homing missiles with slight angle variations
for i in range(num_missiles):
# Slight offset to left/right for multiple missiles
if num_missiles > 1:
offset_x = self.rect.width * (i/(num_missiles-1) - 0.5) # Spread across ship width
else:
offset_x = 0
bullet = HomingBullet(self.rect.centerx + offset_x, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
# Drones also shoot homing bullets
for drone in self.drone_list:
drone.shoot()
def hyper_dash(self):
now = pygame.time.get_ticks()
if now - self.last_special > self.special_delay:
self.hyper_dash_active = True
self.invincible = True
self.hyper_dash_start = now
self.invincible_start = now
self.last_special = now
def add_drone(self):
if len(self.drone_list) < self.max_drones:
drone = Drone(self, len(self.drone_list))
self.drone_list.append(drone)
all_sprites.add(drone)
return True
return False
def hit(self, damage):
if not self.invincible:
if self.shield_active:
# Shield absorbs damage
return False
else:
self.health -= damage
if self.health <= 0:
# Return True to indicate player death
return True
return False
# Drone Class
class Drone(pygame.sprite.Sprite):
def __init__(self, player, position):
pygame.sprite.Sprite.__init__(self)
try:
self.image = load_image("assets/images/drone.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
pygame.draw.circle(self.image, BLUE, (10, 10), 10)
self.rect = self.image.get_rect()
self.player = player
self.position = position # Index in drone list
def update(self, *args):
# Position drones in formation around the player
# For up to 4 drones, place them in cardinal positions
# For more than 4, place them in circular formation
if len(self.player.drone_list) <= 4:
# Simple formation for 1-4 drones
if self.position == 0: # Left
self.rect.right = self.player.rect.left - 15
self.rect.centery = self.player.rect.centery
elif self.position == 1: # Right
self.rect.left = self.player.rect.right + 15
self.rect.centery = self.player.rect.centery
elif self.position == 2: # Top
self.rect.centerx = self.player.rect.centerx
self.rect.bottom = self.player.rect.top - 15
elif self.position == 3: # Bottom
self.rect.centerx = self.player.rect.centerx
self.rect.top = self.player.rect.bottom + 15
else:
# Circular formation for 5+ drones
angle = (360 / len(self.player.drone_list)) * self.position
radius = 50 # Distance from player
rad_angle = math.radians(angle)
self.rect.centerx = self.player.rect.centerx + int(math.sin(rad_angle) * radius)
self.rect.centery = self.player.rect.centery - int(math.cos(rad_angle) * radius)
def shoot(self):
# First check player's current weapon type
if self.player.weapon_type == "normal":
if(random.random() < 0.7):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
elif self.player.weapon_type == "spread":
for angle in range(-15, 16, 15):
if(random.random() < 0.3):
bullet = SpreadBullet(self.rect.centerx, self.rect.top, angle)
all_sprites.add(bullet)
bullets.add(bullet)
elif self.player.weapon_type == "bouncing":
if(random.random() < 0.5):
# Always fire bouncing bullets when player has bouncing weapon type
bullet = BouncingBullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
elif self.player.weapon_type == "homing":
if(random.random() < 0.2): # 40% chance to fire
bullet = HomingBullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
# Bullet class
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
try:
self.image = load_image("assets/images/bullet.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((5, 15))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.speedy = -15
# Play shoot sound
try:
if shoot_sound:
shoot_sound.play()
except:
pass
def update(self):
self.rect.y += self.speedy
# Kill if it moves off the top of the screen
if self.rect.bottom < 0:
self.kill()
class BouncingBullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
try:
self.image = load_image("assets/images/bouncing_bullet.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((8, 8))
self.image.fill(GREEN) # Green color for bouncing bullets
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.speed = 10 # Base speed
# Play shoot sound
try:
if shoot_sound:
shoot_sound.play()
except:
pass
# Find the closest enemy to target
self.target_enemy()
# If we couldn't find an enemy, use a default upward movement
if not hasattr(self, 'speedy') or not hasattr(self, 'speedx'):
self.speedy = -self.speed
self.speedx = random.choice([-2, -1, 1, 2]) # Small random horizontal movement
self.bounces = 0
self.max_bounces = 3 # Maximum number of bounces before disappearing
self.damage = 8 # Slightly less damage than regular bullets (which do 10)
def target_enemy(self):
# Get a list of all enemies and bosses
all_targets = list(enemies) + list(bosses)
if not all_targets:
# No enemies found, will use default movement
return
# Find the closest enemy
closest_enemy = None
closest_distance = float('inf')
for enemy in all_targets:
# Calculate distance to this enemy
dx = enemy.rect.centerx - self.rect.centerx
dy = enemy.rect.centery - self.rect.centery
distance = math.sqrt(dx * dx + dy * dy)
if distance < closest_distance:
closest_distance = distance
closest_enemy = enemy
if closest_enemy:
# Calculate direction to the closest enemy
dx = closest_enemy.rect.centerx - self.rect.centerx
dy = closest_enemy.rect.centery - self.rect.centery
# Normalize the direction vector
length = max(1, math.sqrt(dx * dx + dy * dy)) # Prevent division by zero
dx /= length
dy /= length
# Set velocity components, keep overall speed consistent
self.speedx = dx * self.speed
self.speedy = dy * self.speed
def update(self):
self.rect.y += self.speedy
self.rect.x += self.speedx
# Bounce off the sides of the screen
if self.rect.right > WIDTH:
self.rect.right = WIDTH
self.speedx = -self.speedx
self.bounces += 1
self.retarget_after_bounce()
if self.rect.left < 0:
self.rect.left = 0
self.speedx = -self.speedx
self.bounces += 1
self.retarget_after_bounce()
# Bounce off the top of the screen
if self.rect.top < 0:
self.rect.top = 0
self.speedy = -self.speedy
self.bounces += 1
self.retarget_after_bounce()
# Kill if it moves off the bottom of the screen or exceeds max bounces
if self.rect.top > HEIGHT or self.bounces >= self.max_bounces:
self.kill()
def retarget_after_bounce(self):
# After bouncing, try to retarget toward closest enemy (50% chance)
if random.random() < 0.5:
self.target_enemy()
def bounce_off_enemy(self):
# Called when the bullet hits an enemy but doesn't kill it
self.speedy = -self.speedy
self.speedx = -self.speedx # Reverse direction
# Slightly randomize the direction for more interesting bounces
angle_variation = random.uniform(-30, 30) # Up to 30 degrees variation
angle = math.degrees(math.atan2(self.speedy, self.speedx)) + angle_variation
angle_radians = math.radians(angle)
speed = math.sqrt(self.speedx**2 + self.speedy**2)
self.speedx = math.cos(angle_radians) * speed
self.speedy = math.sin(angle_radians) * speed
self.bounces += 1
# Try to retarget after bouncing (50% chance)
if random.random() < 0.5:
self.target_enemy()
class HomingBullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
try:
self.image = load_image("assets/images/homing_bullet.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((8, 8))
self.image.fill((255, 128, 0)) # Orange color for homing bullets
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.speed = 7 # Slower than normal bullets but constantly homing
# Play shoot sound
try:
if shoot_sound:
shoot_sound.play()
except:
pass
self.damage = 12 # More damage than normal bullets
self.max_lifetime = 120 # Maximum frames before disappearing (2 seconds at 60 FPS)
self.lifetime = 0
# Initial velocity (will be adjusted during homing)
self.speedx = 0
self.speedy = -self.speed
# Target the closest enemy initially
self.find_target()
def find_target(self):
# Get all potential targets (enemies and bosses)
all_targets = list(enemies) + list(bosses)
# If no targets, maintain current direction
if not all_targets:
return None
# Find closest target
closest_target = None
closest_distance = float('inf')
for target in all_targets:
dx = target.rect.centerx - self.rect.centerx
dy = target.rect.centery - self.rect.centery
distance = math.sqrt(dx * dx + dy * dy)
if distance < closest_distance:
closest_distance = distance
closest_target = target
return closest_target
def update(self):
# Increment lifetime
self.lifetime += 1
if self.lifetime >= self.max_lifetime:
self.kill()
return
# Find target
target = self.find_target()
# If we have a target, adjust direction toward it
if target:
# Calculate direction to target
dx = target.rect.centerx - self.rect.centerx
dy = target.rect.centery - self.rect.centery
# Normalize the direction vector
distance = max(1, math.sqrt(dx * dx + dy * dy))
dx = dx / distance
dy = dy / distance
# Gradually adjust velocity (for smooth homing effect)
homing_strength = 0.3 # How strongly it homes in on targets
self.speedx = self.speedx * (1 - homing_strength) + dx * self.speed * homing_strength
self.speedy = self.speedy * (1 - homing_strength) + dy * self.speed * homing_strength
# Maintain consistent speed
current_speed = math.sqrt(self.speedx**2 + self.speedy**2)
if current_speed > 0:
self.speedx = self.speedx / current_speed * self.speed
self.speedy = self.speedy / current_speed * self.speed
# Update position
self.rect.x += self.speedx
self.rect.y += self.speedy
# Kill if it moves off the screen
if (self.rect.right < 0 or self.rect.left > WIDTH or
self.rect.bottom < 0 or self.rect.top > HEIGHT):
self.kill()
# Spread bullet class
class SpreadBullet(pygame.sprite.Sprite):
def __init__(self, x, y, angle):
pygame.sprite.Sprite.__init__(self)
try:
self.image = load_image("assets/images/spread_bullet.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((5, 15))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.bottom = y
self.angle = math.radians(angle)
self.speedy = -15 * math.cos(self.angle)
self.speedx = 15 * math.sin(self.angle)
# Play shoot sound
try:
if shoot_sound:
shoot_sound.play()
except:
pass
def update(self):
self.rect.y += self.speedy
self.rect.x += self.speedx
# Kill if it moves off the screen
if self.rect.bottom < 0 or self.rect.right < 0 or self.rect.left > WIDTH:
self.kill()
# Laser class
class Laser(pygame.sprite.Sprite):
def __init__(self, x, y, level, angle=0, color=RED):
pygame.sprite.Sprite.__init__(self)
self.level = level
width = 10 + (level * 5) # Wider with higher level
length = HEIGHT # Length of the laser
# Create a surface for the original laser pointing up
original = pygame.Surface((width, length), pygame.SRCALPHA)
original.fill(color)
# Rotate the laser to point at the target angle
self.image = pygame.transform.rotate(original, angle)
self.rect = self.image.get_rect()
self.rect.centerx = x
self.rect.centery = y
self.damage = 5 * level
self.duration = 800 # Increased from 500ms
self.created = pygame.time.get_ticks()
self.angle = angle
def update(self):
now = pygame.time.get_ticks()
if now - self.created > self.duration:
self.kill()
# Enemy classes
class Enemy(pygame.sprite.Sprite):
def __init__(self, enemy_type="basic"):
pygame.sprite.Sprite.__init__(self)
self.enemy_type = enemy_type
# Base speed calculation - scales with game sector and difficulty
difficulty_multiplier = {
"easy": 0.8,
"normal": 1.0,
"hard": 1.3
}[game_state.difficulty]
base_min_speed = (2 + (game_state.sector - 1) * 0.5) * difficulty_multiplier
base_max_speed = (5 + (game_state.sector - 1) * 0.5) * difficulty_multiplier
# Common variables for all enemy types
self.bullets = [] # Track this enemy's bullets
self.last_shot = pygame.time.get_ticks() - random.randint(0, 2000) # Random initial delay
# Common features based on enemy type
if enemy_type == "basic":
try:
self.image = load_image("assets/images/basic_enemy.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((40, 40), pygame.SRCALPHA)
pygame.draw.polygon(self.image, RED, [(0, 0), (40, 0), (20, 40)])
self.rect = self.image.get_rect()
# Adjust health based on difficulty
if game_state.difficulty == "easy":
self.health = 8
elif game_state.difficulty == "normal":
self.health = 10
else: # hard
self.health = 15
self.speed = random.uniform(base_min_speed, base_max_speed) # Speed scales with sector and difficulty
self.shoot_delay = 2000 # Base delay
self.score_value = 10
elif enemy_type == "elite":
try:
self.image = load_image("assets/images/elite_enemy.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((60, 60), pygame.SRCALPHA)
pygame.draw.polygon(self.image, PURPLE, [(0, 0), (60, 0), (30, 60)])
self.rect = self.image.get_rect()
# Adjust health based on difficulty
if game_state.difficulty == "easy":
self.health = 40
elif game_state.difficulty == "normal":
self.health = 50
else: # hard
self.health = 70
self.speed = random.uniform(base_min_speed, base_max_speed)
self.shoot_delay = 1000 # Base delay
self.score_value = 25 # Elite enemies are worth more points
# New enemy types
elif enemy_type == "cloaked_ambusher":
try:
self.image = load_image("assets/images/cloaked_ambusher.png")
self.original_image = self.image.copy()
except:
# Fallback if image loading fails
self.image = pygame.Surface((45, 45), pygame.SRCALPHA)
pygame.draw.polygon(self.image, (100, 100, 150), [(0, 0), (45, 0), (22, 45)]) # Light blue-purple
self.original_image = self.image.copy()
self.rect = self.image.get_rect()
# Cloaking variables
self.visible = True
self.cloak_timer = random.randint(1500, 3000) # Time until next cloak/uncloak
self.cloak_start = pygame.time.get_ticks()
self.cloak_duration = 1500 # How long it stays cloaked
self.alpha = 255 # Fully visible
if game_state.difficulty == "easy":
self.health = 15
elif game_state.difficulty == "normal":
self.health = 20
else: # hard
self.health = 30
self.speed = random.uniform(base_min_speed*0.8, base_max_speed*0.8) # Slightly slower
self.shoot_delay = 2500 # Longer delay between shots
self.burst_count = 3 # Number of shots in burst
self.burst_delay = 150 # Delay between shots in burst
self.burst_active = False
self.burst_shots = 0
self.score_value = 20
elif enemy_type == "splitter_drone":
try:
if not hasattr(self, 'is_split') or not self.is_split:
self.image = load_image("assets/images/splitter_drone.png")
else:
self.image = load_image("assets/images/mini_splitter_drone.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((50, 50), pygame.SRCALPHA)
pygame.draw.circle(self.image, (0, 180, 180), (25, 25), 25) # Teal color
self.rect = self.image.get_rect()
self.is_split = False # Whether this is a split version
if game_state.difficulty == "easy":
self.health = 20
elif game_state.difficulty == "normal":
self.health = 25
else: # hard
self.health = 35
self.speed = random.uniform(base_min_speed*0.9, base_max_speed*0.9)
self.shoot_delay = 2200
self.score_value = 15
elif enemy_type == "shield_bearer":
try:
self.image = load_image("assets/images/shield_bearer.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((55, 55), pygame.SRCALPHA)
pygame.draw.circle(self.image, (50, 150, 250), (27, 27), 27) # Light blue
self.rect = self.image.get_rect()
# Shield variables
self.shield_active = True
self.shield_health = 40
self.shield_max_health = 40
self.shield_regen_rate = 0.02
self.shield_radius = 80 # How far the shield extends
if game_state.difficulty == "easy":
self.health = 15
elif game_state.difficulty == "normal":
self.health = 20
else: # hard
self.health = 30
self.speed = random.uniform(base_min_speed*0.7, base_max_speed*0.7) # Slower
self.shoot_delay = 3000 # Shoots less often
self.score_value = 25
elif enemy_type == "energy_sapper":
try:
self.image = load_image("assets/images/energy_sapper.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((45, 55), pygame.SRCALPHA)
pygame.draw.ellipse(self.image, (200, 100, 200), (0, 0, 45, 55)) # Pink-purple
self.rect = self.image.get_rect()
# Sapper beam variables
self.beam_active = False
self.beam_start = 0
self.beam_duration = 2000
self.beam_cooldown = 4000
self.beam_target = None
if game_state.difficulty == "easy":
self.health = 25
elif game_state.difficulty == "normal":
self.health = 35
else: # hard
self.health = 50
self.speed = random.uniform(base_min_speed*0.6, base_max_speed*0.6) # Very slow
self.shoot_delay = 4000 # Rarely shoots regular bullets
self.score_value = 30
elif enemy_type == "blade_spinner":
try:
self.image = load_image("assets/images/blade_spinner.png")
except:
# Fallback if image loading fails
self.image = pygame.Surface((48, 48), pygame.SRCALPHA)
# Draw a spinning blade-like appearance
points = []
center = (24, 24)
for i in range(8): # 8-pointed star
angle = math.pi * i / 4
points.append((center[0] + 24 * math.cos(angle), center[1] + 24 * math.sin(angle)))
angle += math.pi / 8
points.append((center[0] + 12 * math.cos(angle), center[1] + 12 * math.sin(angle)))
pygame.draw.polygon(self.image, (255, 150, 0), points) # Orange color
self.rect = self.image.get_rect()
# Spinning variables
self.angle = 0
self.spin_speed = 5
self.original_image = self.image.copy()
self.orbit_center = None
self.orbit_radius = random.randint(80, 150)
self.orbit_speed = random.uniform(0.01, 0.03)
self.orbit_angle = random.uniform(0, math.pi*2)
self.reflect_bullets = game_state.difficulty == "hard" # Only reflect on hard
if game_state.difficulty == "easy":
self.health = 20
elif game_state.difficulty == "normal":
self.health = 30
else: # hard
self.health = 45
self.speed = random.uniform(base_min_speed*0.7, base_max_speed*0.7)
self.shoot_delay = 2500
self.score_value = 25
# Add random offset to shoot delay to prevent synchronized firing
self.shoot_delay += random.randint(-500, 500)
# Random initial delay so they don't all start firing at once
self.last_shot = pygame.time.get_ticks() - random.randint(0, self.shoot_delay)
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-150, -50)
def update(self):
# Store previous position to calculate momentum
prev_x = self.rect.x
prev_y = self.rect.y
now = pygame.time.get_ticks()
# Movement based on enemy type
if self.enemy_type == "basic":
# Basic enemies just move downward at a constant speed
self.rect.y += self.speed
elif self.enemy_type == "elite":
# Elite enemies move in a slight side-to-side pattern while moving down
self.rect.y += self.speed
# Add sine wave horizontal movement
self.rect.x += math.sin(now / 500) * 2
# Keep within screen boundaries
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > WIDTH:
self.rect.right = WIDTH
elif self.enemy_type == "cloaked_ambusher":
# Cloaked ambusher moves downward, occasionally cloaking
self.rect.y += self.speed
# Handle cloaking
if hasattr(self, 'visible'):
if self.visible and now - self.cloak_start > self.cloak_timer:
# Start cloaking
self.visible = False
self.cloak_start = now
# Make semi-transparent
self.image.set_alpha(30) # Almost invisible
elif not self.visible and now - self.cloak_start > self.cloak_duration:
# Uncloak
self.visible = True
self.cloak_start = now
self.cloak_timer = random.randint(2000, 4000) # Time until next cloak
self.image.set_alpha(255) # Fully visible
# Burst attack when uncloaking
if hasattr(self, 'burst_active'):
self.burst_active = True
self.burst_shots = 0
self.last_shot = now
# Handle burst fire
if hasattr(self, 'burst_active') and self.burst_active and now - self.last_shot > self.burst_delay:
self.shoot_cloaked_ambusher()
self.burst_shots += 1
self.last_shot = now
# End burst after enough shots
if self.burst_shots >= self.burst_count:
self.burst_active = False
elif self.enemy_type == "splitter_drone":
# Splitter drone moves downward, splitting happens in hit() method
self.rect.y += self.speed
elif self.enemy_type == "shield_bearer":
# Shield bearer moves downward with shield protection
self.rect.y += self.speed
# Regenerate shield if it's active
if hasattr(self, 'shield_active') and self.shield_active:
if hasattr(self, 'shield_health') and hasattr(self, 'shield_max_health') and hasattr(self, 'shield_regen_rate'):
self.shield_health = min(self.shield_max_health, self.shield_health + self.shield_regen_rate)
# Check if shield should be disabled/enabled
if hasattr(self, 'shield_active') and hasattr(self, 'shield_health'):
if self.shield_active and self.shield_health <= 0:
self.shield_active = False
elif not self.shield_active and hasattr(self, 'shield_max_health') and self.shield_health > self.shield_max_health * 0.3:
self.shield_active = True
elif self.enemy_type == "energy_sapper":
# Energy sapper moves slowly
self.rect.y += self.speed * 0.7
# Check if we should start/stop the beam