-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSpaceExplorer.py
More file actions
3293 lines (2762 loc) · 114 KB
/
Copy pathSpaceExplorer.py
File metadata and controls
3293 lines (2762 loc) · 114 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
#!/usr/bin/env python
#------------------------------------------------------------------------------
# SPACE EXPLORER
#
# Forked from Defender2's star-field parallax idea: four oversized scrolling
# layers (far background / background / middleground / foreground) with a tiny
# ship locked to
# the center of the screen. Ground terrain is omitted. The world drifts in
# sixteen directions so the star fields move at different speeds on both axes.
#------------------------------------------------------------------------------
import LEDarcade as LED
LED.Initialize()
import copy
import math
import random
import time
# --- Display ---
WIDTH = LED.HatWidth
HEIGHT = LED.HatHeight
# --- World maps (larger than the physical panel in both dimensions) ---
LAYER_WIDTH = 640
LAYER_HEIGHT = max(HEIGHT * 30, 960)
# Movement — staggered layer scroll rates like Defender2 (no per-frame sleep).
SCROLL_STEP = 1.6
FAR_RATE = 14 # far star field; scrolled smoothly every frame
BRATE = 8
MRATE = 6
FRATE = 4
# Ship inertia — Blasteroids-style: rotate at fixed rate, thrust when aligned, coast.
# Rates are tuned for 60fps and scaled by frame delta for smooth motion on the Pi.
PHYSICS_FPS = 60.0
SHIP_TURN_RATE = 0.10
SHIP_THRUST = 0.056
MAX_SHIP_SPEED = 3.75
SHIP_THRUST_ALIGN_RAD = 0.45
HUNT_LEAD_SEC = 0.55
SHIP_HUNT_TURN_RATE = 0.14
SHIP_HUNT_ALIGN_RAD = 0.72
SHIP_HUNT_CLOSE_DIST = 32
SHIP_HUNT_CLOSE_ALIGN_RAD = 1.05
HUNT_INTERCEPT_MIN_TIME = 0.05
HUNT_INTERCEPT_MAX_TIME = 4.0
HUNT_MIN_PURSUIT_SPEED = 0.85
HUNT_TARGET_REACQUIRE_RATIO = 0.55
HUNT_ORBIT_CLOSE_DIST = 70
TRACTOR_BEAM_RGB = (40, 255, 70)
TRACTOR_MAX_WORLD_DIST = 90
TRACTOR_MOMENTUM_DAMP = 0.035
TRACTOR_PULL_RATE = 0.016
TRACTOR_SHIP_MATCH_RATE = 0.07
TRACTOR_SHIP_CLOSE_RATE = 0.85
TRACTOR_COOLDOWN_SEC = 2.0
TRACTOR_MAX_SHIP_SPEED = 5.34375
SHIP_TURBO_THRUST = 0.144
SHIP_TURBO_MAX_SPEED = 6.5625
SHIP_TURBO_TURN_RATE = 0.20
SHIP_TURBO_ALIGN_RAD = 0.75
TURBO_CLOSE_DIST = 30
TURBO_ORBIT_STALL_FRAMES = 10
TURBO_ORBIT_CLOSE_MIN = 0.12
TURBO_DURATION_SEC = 5.0
TURBO_COOLDOWN_SEC = 2.0
ROCK_NEARBY_DIST = 58
CRUISE_MAX_SPEED = 1.05
CRUISE_THRUST = 0.024
CRUISE_TURN_RATE = 0.08
GAS_GIANT_COUNT = 4
GAS_GIANT_ARRIVAL_PAD = 30
BOUNCE_DAMPING = 0.88
SHIP_BOUNCE_DAMPING = 0.44
BOUNCE_COOLDOWN_FRAMES = 12
ENEMY_BOUNCE_COOLDOWN_FRAMES = 10
LOOKAHEAD = 18
THRUST_FLAME_COLORS = (
(255, 210, 70),
(255, 140, 30),
(220, 60, 0),
(160, 30, 0),
)
# Defender-style enemy ships (world coords on the scrolling map)
ENEMY_SHIP_COUNT = 12
LARGE_ENEMY_SHIP_COUNT = 2
ENEMY_TURN_RATE = 0.14
ENEMY_THRUST = 0.006
ENEMY_MAX_SPEED = 0.32
LARGE_ENEMY_TURN_RATE = 0.10
LARGE_ENEMY_THRUST = 0.004
LARGE_ENEMY_MAX_SPEED = 0.20
ENEMY_BRIGHTNESS = 1.85
ENEMY_RGB_FLOOR = 52
ENEMY_LARGE_BRIGHTNESS = 2.15
ENEMY_LARGE_RGB_FLOOR = 64
ENEMY_SHIP_TYPES = tuple(range(8)) # SmallUFOSprite … SmallUFOSprite7
# LargeUFOSprite5 (8×5) and LargeUFOSprite6 (8×4) in LED.ShipSprites
LARGE_ENEMY_SHIP_TYPES = (22, 23)
ENEMY_DIRECTION_8WAY = {
1: (0, -1), 2: (1, -1), 3: (1, 0), 4: (1, 1),
5: (0, 1), 6: (-1, 1), 7: (-1, 0), 8: (-1, -1),
}
CHAIN_PLAYER = object()
CHAIN_LINK_GAP = 2.0
PLAYER_CHAIN_RADIUS = 1.8
CHAIN_LIMP_POS_BLEND = 0.20
CHAIN_LIMP_VEL_MATCH = 0.94
CHAIN_LIMP_CORRECTION = 0.06
CHAIN_WEAVE_AMPLITUDE = 0.38
CHAIN_WEAVE_HZ = 0.55
CHAIN_UFO_GRAPPLE_EXTRA = 20
CHAIN_BAIT_PASS_DIST = 34
CHAIN_BAIT_PASS_SLIP = 0.48
ENEMY_CRYSTAL_BREAK_DIST = 52
# Tiny ship at screen center
SHIP_H = WIDTH // 2
SHIP_V = HEIGHT // 2
SHIP_CORE_RGB = (255, 255, 255)
SHIP_BODY_RGB = (90, 140, 220)
SHIP_NOSE_RGB = (180, 220, 255)
DIRECTION_COUNT = 16
# 16-wind compass (clockwise from north): 1=N, 2=NNE, 3=NE, ... 16=NNW
DIRECTION_DELTAS = {
1: (0, -1),
2: (1, -2),
3: (1, -1),
4: (2, -1),
5: (1, 0),
6: (2, 1),
7: (1, 1),
8: (1, 2),
9: (0, 1),
10: (-1, 2),
11: (-1, 1),
12: (-2, 1),
13: (-1, 0),
14: (-2, -1),
15: (-1, -1),
16: (-1, -2),
}
def _nose_for_delta(dh, dv):
"""Single-pixel nose direction from a movement vector."""
if dh == 0:
return (0, 1 if dv > 0 else -1)
if dv == 0:
return (1 if dh > 0 else -1, 0)
return (1 if dh > 0 else -1, 1 if dv > 0 else -1)
DIRECTION_NOSE = {d: _nose_for_delta(dh, dv) for d, (dh, dv) in DIRECTION_DELTAS.items()}
ScrollSleep = 0.02
TerminalTypeSpeed = 0.015
TerminalScrollSpeed = 0.015
CursorRGB = (0, 255, 0)
CursorDarkRGB = (0, 50, 0)
# Asteroid styling (from Blasteroids lump renderer)
ASTEROID_LIGHTING_CONTRAST = 1.0
ASTEROID_COLOR_OPTIONS = (
(138, 138, 145),
(125, 133, 252),
(252, 55, 252),
)
FOREGROUND_ASTEROID_COLORS = (
(210, 195, 175),
(255, 140, 90),
(200, 210, 255),
)
LAYER_ASTEROIDS = (
# layer, count, (min_size, max_size), dim_factor
# Stars live on FarBackground only — no rocks on Background (avoids star-like specks).
("middleground", 11, (4, 8), 0.6),
("foreground", 18, (2, 9), 0.75),
)
# Foreground rocks = free-floating breakable objects (not parallax layer pixels).
FOREGROUND_ASTEROID_COUNT = 44
FOREGROUND_ASTEROID_SIZE_RANGE = (2, 9)
FOREGROUND_ASTEROID_DIM = 1.15
FOREGROUND_ASTEROID_MIN_SPEED = 0.1
FOREGROUND_ASTEROID_MAX_SPEED = 0.25
# Extra large slow breakable rocks (same ForegroundAsteroid class as the 44 above).
LARGE_SLOW_ASTEROID_COUNT = 10
LARGE_SLOW_ASTEROID_SIZE_RANGE = (8, 12)
LARGE_SLOW_ASTEROID_MIN_SPEED = 0.04
LARGE_SLOW_ASTEROID_MAX_SPEED = 0.08
FOREGROUND_ASTEROID_SPLIT_ANGLE = 0.45
MIN_FOREGROUND_ASTEROID_SIZE = 3
ASTEROID_TIER_BIG_MIN = 7
ASTEROID_TIER_SMALL_MIN = 4
ASTEROID_HITS_HUGE_MIN = 10
ASTEROID_HITS_BIG_MIN = 7
ASTEROID_SMALL_SIZE_RANGE = (4, 6)
ASTEROID_TINY_SIZE_RANGE = (2, 3)
BIG_ROCK_SPLIT_COUNT = 4
SMALL_ROCK_SPLIT_COUNT = 3
SPLIT_FLY_APART_BIG = (0.14, 0.24)
SPLIT_FLY_APART_SMALL = (0.24, 0.42)
SPLIT_PARENT_MOMENTUM = 0.12
SPLIT_PERP_SPREAD_RAD = 0.85
SPLIT_SPAWN_OFFSET = 1.6
TINY_ROCK_SPARK_COUNT = 12
ASTEROID_COLLIDE_SCALE = 0.95
ASTEROID_MERGE_COOLDOWN_SEC = 2.0
SPARK_COUNT = 8
SPARK_TRAIL_LENGTH = 5
SPARK_COLOR = (255, 200, 100)
ENEMY_PARTICLE_GRAVITY = 0.01
ENEMY_PARTICLE_LIFESPAN = 48
CRYSTAL_MAX_PER_BREAK = 3
CRYSTAL_HUNT_DIST = 90
CRYSTAL_MIN_SPEED = 0.05
CRYSTAL_MAX_SPEED = 0.16
CRYSTAL_PIXELS = ((0, 0, (255, 255, 0)),)
SHIP_HITBOX = (
(0, 0), (0, -1), (0, 1), (-1, 0), (1, 0),
(-1, -1), (1, -1), (-1, 1), (1, 1),
)
def _generate_asteroid_lumps():
"""Blasteroids-style lumpy asteroid shape definition."""
lumps = []
for _ in range(random.randint(3, 6)):
angle = random.uniform(0, 2 * math.pi)
distance_frac = random.uniform(0, 0.5)
lump_radius_frac = random.uniform(0.2, 0.5)
lumps.append((
math.cos(angle) * distance_frac,
math.sin(angle) * distance_frac,
lump_radius_frac,
))
return lumps
def _pick_asteroid_color():
roll = random.random()
if roll < 0.9:
return ASTEROID_COLOR_OPTIONS[0]
if roll < 0.95:
return ASTEROID_COLOR_OPTIONS[1]
return ASTEROID_COLOR_OPTIONS[2]
def _shade_asteroid_color(color, brightness_factor):
r, g, b = color
return (
min(255, int(r * brightness_factor)),
min(255, int(g * brightness_factor)),
min(255, int(b * brightness_factor)),
)
def _asteroid_pixel_solid(i, j, size, lumps):
"""True when map offset (i, j) from asteroid center is inside the lump shape."""
bounding_size = int(size * 1.2)
if abs(i) > bounding_size or abs(j) > bounding_size:
return False
for frac_dx, frac_dy, frac_r in lumps:
effective_dx = frac_dx * size
effective_dy = frac_dy * size
effective_radius = frac_r * size
distance = math.sqrt((i - effective_dx) ** 2 + (j - effective_dy) ** 2)
if distance < effective_radius:
return True
return False
def _paint_asteroid_to_layer(layer, cx, cy, size, color, lumps, dim_factor=1.0, obstacle_map=None):
"""Stamp one lump-shaded asteroid into a layer map (Blasteroids draw logic)."""
bounding_size = int(size * 1.2)
lw = layer.width
lh = layer.height
for j in range(-bounding_size, bounding_size + 1):
for i in range(-bounding_size, bounding_size + 1):
max_depth = -1.0
selected_lump = None
for frac_dx, frac_dy, frac_r in lumps:
effective_dx = frac_dx * size
effective_dy = frac_dy * size
effective_radius = frac_r * size
distance = math.sqrt((i - effective_dx) ** 2 + (j - effective_dy) ** 2)
if distance < effective_radius:
depth = effective_radius - distance
if depth > max_depth:
max_depth = depth
selected_lump = (frac_dx, frac_dy, frac_r)
if not selected_lump:
continue
frac_dx, frac_dy, frac_r = selected_lump
effective_dx = frac_dx * size
effective_dy = frac_dy * size
effective_radius = frac_r * size
rel_i = i - effective_dx
rel_j = j - effective_dy
brightness = 1.0 - ASTEROID_LIGHTING_CONTRAST * (rel_i + rel_j) / (2 * max(effective_radius, 0.5))
brightness = max(0.64, min(1.35, brightness)) * dim_factor
rgb = _shade_asteroid_color(color, brightness)
x = (cx + i) % lw
y = (cy + j) % lh
layer.map[y][x] = rgb
if obstacle_map is not None:
obstacle_map[y][x] = True
def _pick_layer_asteroid_color(layer_name):
if layer_name == "foreground":
return random.choice(FOREGROUND_ASTEROID_COLORS)
return _pick_asteroid_color()
def _build_asteroid_sprite_pixels(size, color, lumps, dim_factor=1.0):
"""Precompute lump-shaded pixels once — avoids heavy per-frame math on the Pi."""
pixels = []
bounding_size = int(size * 1.2)
for j in range(-bounding_size, bounding_size + 1):
for i in range(-bounding_size, bounding_size + 1):
max_depth = -1.0
selected_lump = None
for frac_dx, frac_dy, frac_r in lumps:
effective_dx = frac_dx * size
effective_dy = frac_dy * size
effective_radius = frac_r * size
distance = math.sqrt((i - effective_dx) ** 2 + (j - effective_dy) ** 2)
if distance < effective_radius:
depth = effective_radius - distance
if depth > max_depth:
max_depth = depth
selected_lump = (frac_dx, frac_dy, frac_r)
if not selected_lump:
continue
frac_dx, frac_dy, frac_r = selected_lump
effective_dx = frac_dx * size
effective_dy = frac_dy * size
effective_radius = frac_r * size
rel_i = i - effective_dx
rel_j = j - effective_dy
brightness = 1.0 - ASTEROID_LIGHTING_CONTRAST * (rel_i + rel_j) / (2 * max(effective_radius, 0.5))
brightness = max(0.64, min(1.35, brightness)) * dim_factor
pixels.append((i, j, _shade_asteroid_color(color, brightness)))
return pixels
class ForegroundAsteroid:
"""Breakable drifting rock — world position, velocity, Blasteroids-style lumps."""
def __init__(
self, h, v, size=None, color=None, dx=None, dy=None, speed_range=None,
merge_cooldown_until=0.0,
):
self.h = float(h)
self.v = float(v)
self.size = size if size is not None else random.randint(*FOREGROUND_ASTEROID_SIZE_RANGE)
self.color = color if color is not None else random.choice(FOREGROUND_ASTEROID_COLORS)
self.lumps = _generate_asteroid_lumps()
dim = FOREGROUND_ASTEROID_DIM
self.sprite_pixels = _build_asteroid_sprite_pixels(
self.size, self.color, self.lumps, dim,
)
self.alive = True
self.hits_to_break = _asteroid_hits_to_break(self.size)
self.hits_taken = 0
self.merge_cooldown_until = merge_cooldown_until
if dx is None or dy is None:
angle = random.uniform(0, 2 * math.pi)
if speed_range is None:
speed_range = (FOREGROUND_ASTEROID_MIN_SPEED, FOREGROUND_ASTEROID_MAX_SPEED)
speed = random.uniform(*speed_range)
self.dx = math.cos(angle) * speed
self.dy = math.sin(angle) * speed
else:
self.dx = dx
self.dy = dy
def move(self):
self.h = (self.h + self.dx) % LAYER_WIDTH
self.v = (self.v + self.dy) % LAYER_HEIGHT
def touches_ship_pixels(self, fh, fy, ship_pixels):
"""Screen-space hit test — matches the same rounding used when drawing."""
sh, sv = world_to_screen(self.h, self.v, fh, fy)
center_h = int(round(sh))
center_v = int(round(sv))
for i, j, _ in self.sprite_pixels:
if (center_h + i, center_v + j) in ship_pixels:
return True
return False
def draw(self, canvas, fh, fy):
"""Blit cached sprite pixels to the canvas (like a ship sprite)."""
sh, sv = world_to_screen(self.h, self.v, fh, fy)
center_h = int(round(sh))
center_v = int(round(sv))
for i, j, rgb in self.sprite_pixels:
px = center_h + i
py = center_v + j
if 0 <= px < WIDTH and 0 <= py < HEIGHT:
canvas.SetPixel(px, py, *rgb)
class Crystal:
"""Bright yellow loot — drifts after rock breaks; ship and aliens race to collect."""
def __init__(self, h, v, dx=None, dy=None):
self.h = float(h)
self.v = float(v)
self.alive = True
if dx is None or dy is None:
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(CRYSTAL_MIN_SPEED, CRYSTAL_MAX_SPEED)
self.dx = math.cos(angle) * speed
self.dy = math.sin(angle) * speed
else:
self.dx = dx
self.dy = dy
def move(self):
self.h = (self.h + self.dx) % LAYER_WIDTH
self.v = (self.v + self.dy) % LAYER_HEIGHT
def screen_pixels(self, fh, fy):
sh, sv = world_to_screen(self.h, self.v, fh, fy)
center_h = int(round(sh))
center_v = int(round(sv))
return [
(center_h + dx, center_v + dy, rgb)
for dx, dy, rgb in CRYSTAL_PIXELS
]
def touches_ship_pixels(self, fh, fy, ship_pixels):
for px, py, _ in self.screen_pixels(fh, fy):
if (px, py) in ship_pixels:
return True
return False
def touches_enemy_sprite(self, fh, fy, ship):
sh, sv = world_to_screen(ship.h, ship.v, fh, fy)
sh = int(round(sh))
sv = int(round(sv))
frame = _enemy_animation_frame(ship)
grid = ship.grid[frame]
crystal_pixels = {(px, py) for px, py, _ in self.screen_pixels(fh, fy)}
for count in range(ship.width * ship.height):
y, x = divmod(count, ship.width)
r, g, b = LED.ColorList[grid[count]]
if r > 0 or g > 0 or b > 0:
if (sh + x, sv + y) in crystal_pixels:
return True
return False
def draw(self, canvas, fh, fy):
for px, py, rgb in self.screen_pixels(fh, fy):
if 0 <= px < WIDTH and 0 <= py < HEIGHT:
canvas.SetPixel(px, py, *rgb)
class Spark:
"""Short-lived explosion streak in world coordinates."""
def __init__(self, wh, wv, angle, speed, length):
self.wh = wh
self.wv = wv
self.angle = angle
self.speed = speed
self.length = max(1, min(length, 8))
self.lifespan = SPARK_TRAIL_LENGTH
def move(self, layer_width, layer_height):
self.wh = (self.wh + math.cos(self.angle) * self.speed) % layer_width
self.wv = (self.wv + math.sin(self.angle) * self.speed) % layer_height
def draw(self, canvas, fh, fy):
for i in range(self.length):
wh = (self.wh - math.cos(self.angle) * i) % LAYER_WIDTH
wv = (self.wv - math.sin(self.angle) * i) % LAYER_HEIGHT
sh, sv = world_to_screen(wh, wv, fh, fy)
if not (0 <= sh < WIDTH and 0 <= sv < HEIGHT):
continue
fade = max(32, SPARK_COLOR[0] - i * (SPARK_COLOR[0] // SPARK_TRAIL_LENGTH * 2))
canvas.SetPixel(sh, sv, fade, fade * 3 // 4, fade // 2)
class EnemyParticle:
"""Defender-style debris — one colored sprite pixel with drift and gravity."""
def __init__(self, wh, wv, r, g, b, vel_h, vel_v):
self.wh = float(wh)
self.wv = float(wv)
self.r, self.g, self.b = r, g, b
self.vel_h = vel_h
self.vel_v = vel_v
self.alive = True
self.lifespan = ENEMY_PARTICLE_LIFESPAN
def move(self, dt):
self.vel_v += _physics_scale(ENEMY_PARTICLE_GRAVITY, dt)
self.wh = (self.wh + self.vel_h) % LAYER_WIDTH
self.wv = (self.wv + self.vel_v) % LAYER_HEIGHT
self.lifespan -= 1
def draw(self, canvas, fh, fy):
sh, sv = world_to_screen(self.wh, self.wv, fh, fy)
sh = int(round(sh))
sv = int(round(sv))
if 0 <= sh < WIDTH and 0 <= sv < HEIGHT:
canvas.SetPixel(sh, sv, self.r, self.g, self.b)
def _random_asteroid_world_spawn(player_wh, player_wv):
"""Spawn a drifting rock somewhere on the map, away from the player."""
for _ in range(40):
wh = random.randint(0, LAYER_WIDTH - 1)
wv = random.randint(0, LAYER_HEIGHT - 1)
dh = min((wh - player_wh) % LAYER_WIDTH, (player_wh - wh) % LAYER_WIDTH)
dv = min((wv - player_wv) % LAYER_HEIGHT, (player_wv - wv) % LAYER_HEIGHT)
if dh + dv > 24:
return wh, wv
return random.randint(0, LAYER_WIDTH - 1), random.randint(0, LAYER_HEIGHT - 1)
def _random_large_asteroid_spawn(player_wh, player_wv):
"""Place a large breakable rock within hunt range on the wrapping map."""
for _ in range(40):
wh = random.randint(0, LAYER_WIDTH - 1)
wv = random.randint(0, LAYER_HEIGHT - 1)
dh = min((wh - player_wh) % LAYER_WIDTH, (player_wh - wh) % LAYER_WIDTH)
dv = min((wv - player_wv) % LAYER_HEIGHT, (player_wv - wv) % LAYER_HEIGHT)
dist = math.hypot(dh, dv)
if 28 <= dist <= 160:
return wh, wv
return _random_asteroid_world_spawn(player_wh, player_wv)
def create_foreground_asteroids(count, size_range, fh=0, fy=0):
"""Spawn breakable rocks with random drift trajectories in world space."""
smin, smax = size_range
player_wh, player_wv = player_world_position(fh, fy)
asteroids = []
for _ in range(count):
wh, wv = _random_asteroid_world_spawn(player_wh, player_wv)
asteroids.append(ForegroundAsteroid(wh, wv, size=random.randint(smin, smax)))
return asteroids
def create_large_slow_asteroids(count, fh=0, fy=0):
"""Spawn large slow breakable rocks — split on contact like the smaller ones."""
smin, smax = LARGE_SLOW_ASTEROID_SIZE_RANGE
player_wh, player_wv = player_world_position(fh, fy)
asteroids = []
for _ in range(count):
wh, wv = _random_large_asteroid_spawn(player_wh, player_wv)
asteroids.append(ForegroundAsteroid(
wh, wv,
size=random.randint(smin, smax),
speed_range=(LARGE_SLOW_ASTEROID_MIN_SPEED, LARGE_SLOW_ASTEROID_MAX_SPEED),
))
return asteroids
def create_all_foreground_asteroids(fh=0, fy=0):
"""22 standard breakable rocks plus 5 large slow breakable rocks."""
asteroids = create_foreground_asteroids(
FOREGROUND_ASTEROID_COUNT, FOREGROUND_ASTEROID_SIZE_RANGE, fh, fy,
)
asteroids.extend(create_large_slow_asteroids(LARGE_SLOW_ASTEROID_COUNT, fh, fy))
return asteroids
def count_alive_foreground_asteroids(foreground_asteroids):
return sum(1 for asteroid in foreground_asteroids if asteroid.alive)
def replenish_foreground_asteroids_if_empty(foreground_asteroids, fh, fy):
"""Drop in a fresh wave once the player has blown up every rock."""
if count_alive_foreground_asteroids(foreground_asteroids) > 0:
return False
foreground_asteroids.extend(create_all_foreground_asteroids(fh, fy))
return True
def _asteroid_mass(size):
"""Mass scales with sprite area (size²)."""
return size * size
def _asteroid_collision_radius(size):
return size * FOREGROUND_ASTEROID_DIM
def _asteroids_collide(a, b):
"""True when two breakable rocks overlap on the wrapping map."""
dh = _toroidal_delta(a.h, b.h, LAYER_WIDTH)
dv = _toroidal_delta(a.v, b.v, LAYER_HEIGHT)
dist = math.hypot(dh, dv)
touch_dist = (
_asteroid_collision_radius(a.size) + _asteroid_collision_radius(b.size)
) * ASTEROID_COLLIDE_SCALE
return dist < touch_dist
def asteroid_can_merge(asteroid, now):
"""Split fragments cannot recombine until their merge cooldown expires."""
return now >= asteroid.merge_cooldown_until
def _asteroids_can_merge(a, b, now):
return (
_asteroids_collide(a, b)
and asteroid_can_merge(a, now)
and asteroid_can_merge(b, now)
)
def merge_two_asteroids(a, b):
"""Combine two colliding rocks — summed area, momentum-conserving velocity."""
m1 = _asteroid_mass(a.size)
m2 = _asteroid_mass(b.size)
total_mass = m1 + m2
dh = _toroidal_delta(a.h, b.h, LAYER_WIDTH)
dv = _toroidal_delta(a.v, b.v, LAYER_HEIGHT)
h = _wrap_world_coord(a.h + dh * m2 / total_mass, LAYER_WIDTH)
v = _wrap_world_coord(a.v + dv * m2 / total_mass, LAYER_HEIGHT)
new_size = max(MIN_FOREGROUND_ASTEROID_SIZE, round(math.sqrt(m1 + m2)))
dx = (m1 * a.dx + m2 * b.dx) / total_mass
dy = (m1 * a.dy + m2 * b.dy) / total_mass
color = a.color if a.size >= b.size else b.color
return ForegroundAsteroid(h, v, size=new_size, color=color, dx=dx, dy=dy)
def resolve_asteroid_collisions(foreground_asteroids, now):
"""Merge breakable rocks that collide — one pair per pass until stable."""
merged_any = True
while merged_any:
merged_any = False
alive = [a for a in foreground_asteroids if a.alive]
for i in range(len(alive)):
for j in range(i + 1, len(alive)):
if _asteroids_can_merge(alive[i], alive[j], now):
merged = merge_two_asteroids(alive[i], alive[j])
alive[i].alive = False
alive[j].alive = False
foreground_asteroids.append(merged)
merged_any = True
break
if merged_any:
break
def update_foreground_asteroids(foreground_asteroids, now):
for asteroid in foreground_asteroids:
if asteroid.alive:
asteroid.move()
resolve_asteroid_collisions(foreground_asteroids, now)
def draw_foreground_asteroids(canvas, foreground_asteroids, fh, fy):
for asteroid in foreground_asteroids:
if asteroid.alive:
asteroid.draw(canvas, fh, fy)
return canvas
def ship_hits_foreground_asteroids(foreground_asteroids, fh, fy):
return bool(asteroids_touching_ship(foreground_asteroids, fh, fy))
_SHIP_PIXELS = frozenset((SHIP_H + dx, SHIP_V + dy) for dx, dy in SHIP_HITBOX)
def _expand_pixel_zone(pixels):
"""Include every pixel orthogonally and diagonally beside a zone."""
zone = set(pixels)
for px, py in pixels:
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
zone.add((px + dx, py + dy))
return frozenset(zone)
_SHIP_COLLECT_PIXELS = _expand_pixel_zone(_SHIP_PIXELS)
def asteroids_touching_ship(foreground_asteroids, fh, fy):
"""Return foreground asteroids whose drawn pixels overlap the ship hitbox."""
touching = []
for asteroid in foreground_asteroids:
if asteroid.alive and asteroid.touches_ship_pixels(fh, fy, _SHIP_PIXELS):
touching.append(asteroid)
return touching
def _asteroid_break_tier(size):
"""big (7+) → small (4–6) → tiny (2–3) → explode."""
if size >= ASTEROID_TIER_BIG_MIN:
return "big"
if size >= ASTEROID_TIER_SMALL_MIN:
return "small"
return "tiny"
def _asteroid_hits_to_break(size):
"""Ram hits required before the rock splits — 4 for huge, stepping down to 1."""
if size >= ASTEROID_HITS_HUGE_MIN:
return 4
if size >= ASTEROID_HITS_BIG_MIN:
return 3
if size >= ASTEROID_TIER_SMALL_MIN:
return 2
return 1
def apply_ship_hits_to_asteroids(hit_asteroids):
"""Count one player ram per rock; return those damaged enough to split."""
ready_to_split = []
for asteroid in hit_asteroids:
if not asteroid.alive:
continue
asteroid.hits_taken += 1
if asteroid.hits_taken >= asteroid.hits_to_break:
ready_to_split.append(asteroid)
return ready_to_split
def _split_child_sizes(parent_size, tier, count):
"""Pick child sizes one tier below the parent, with slight variation."""
smin, smax = ASTEROID_SMALL_SIZE_RANGE if tier == "big" else ASTEROID_TINY_SIZE_RANGE
base = max(smin, min(smax, parent_size // 2))
sizes = []
for _ in range(count):
size = base + random.randint(-1, 0)
sizes.append(max(smin, min(smax, size)))
return sizes
def _split_fragment_angles(ship_angle, count):
"""Random break headings anchored perpendicular to the ramming ship."""
angles = []
for _ in range(count):
side = random.choice((-1, 1))
angles.append(
ship_angle
+ side * (
math.pi / 2
+ random.uniform(-SPLIT_PERP_SPREAD_RAD, SPLIT_PERP_SPREAD_RAD)
)
)
return angles
def _split_fly_apart_burst(tier):
"""Outward shove applied along each fragment's break angle."""
if tier == "big":
return random.uniform(*SPLIT_FLY_APART_BIG)
return random.uniform(*SPLIT_FLY_APART_SMALL)
def _split_fragment_state(asteroid, angle, tier, child_size):
"""Spawn position and velocity for a fragment flying away from the break."""
burst = _split_fly_apart_burst(tier)
offset = SPLIT_SPAWN_OFFSET + child_size * 0.2
h = asteroid.h + math.cos(angle) * offset
v = asteroid.v + math.sin(angle) * offset
dx = asteroid.dx * SPLIT_PARENT_MOMENTUM + math.cos(angle) * burst
dy = asteroid.dy * SPLIT_PARENT_MOMENTUM + math.sin(angle) * burst
speed = math.hypot(dx, dy)
max_speed = FOREGROUND_ASTEROID_MAX_SPEED * 1.35
if speed > max_speed:
scale = max_speed / speed
dx *= scale
dy *= scale
return h, v, dx, dy
def spawn_crystals_from_break(wh, wv, ship_angle):
"""0–3 bright crystals ejected perpendicular to the ramming ship."""
crystals = []
for _ in range(random.randint(0, CRYSTAL_MAX_PER_BREAK)):
side = random.choice((-1, 1))
angle = (
ship_angle
+ side * (math.pi / 2 + random.uniform(-0.6, 0.6))
)
speed = random.uniform(0.10, 0.22)
offset = random.uniform(0.8, 2.2)
crystals.append(Crystal(
wh + math.cos(angle) * offset,
wv + math.sin(angle) * offset,
dx=math.cos(angle) * speed,
dy=math.sin(angle) * speed,
))
return crystals
def split_asteroids(foreground_asteroids, hit_asteroids, now, ship_angle):
"""
Tiered break on ship contact — big rocks split to several small pieces,
small rocks split to several tiny pieces, tiny rocks explode into sparks only.
"""
if not hit_asteroids:
return [], []
new_asteroids = []
sparks = []
crystals = []
merge_cooldown_until = now + ASTEROID_MERGE_COOLDOWN_SEC
for asteroid in hit_asteroids:
if not asteroid.alive:
continue
asteroid.alive = False
tier = _asteroid_break_tier(asteroid.size)
if tier != "tiny":
split_count = BIG_ROCK_SPLIT_COUNT if tier == "big" else SMALL_ROCK_SPLIT_COUNT
for angle, child_size in zip(
_split_fragment_angles(ship_angle, split_count),
_split_child_sizes(asteroid.size, tier, split_count),
):
frag_h, frag_v, frag_dx, frag_dy = _split_fragment_state(
asteroid, angle, tier, child_size,
)
new_asteroids.append(ForegroundAsteroid(
frag_h,
frag_v,
child_size,
asteroid.color,
dx=frag_dx,
dy=frag_dy,
merge_cooldown_until=merge_cooldown_until,
))
spark_count = TINY_ROCK_SPARK_COUNT if tier == "tiny" else SPARK_COUNT
for _ in range(spark_count):
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(0.15, 1.2)
sparks.append(Spark(asteroid.h, asteroid.v, angle, speed, int(asteroid.size * 1.5)))
crystals.extend(spawn_crystals_from_break(asteroid.h, asteroid.v, ship_angle))
foreground_asteroids[:] = [a for a in foreground_asteroids if a.alive]
foreground_asteroids.extend(new_asteroids)
return sparks, crystals
def find_nearest_crystal(crystals, fh, fy):
"""Return the closest alive crystal to the centered ship."""
nearest = None
nearest_dist = float("inf")
for crystal in crystals:
if not crystal.alive:
continue
dist = distance_to_world_point(fh, fy, crystal.h, crystal.v)
if dist < nearest_dist:
nearest_dist = dist
nearest = crystal
return nearest, nearest_dist
def crystal_on_screen(crystal, fh, fy):
if crystal is None or not crystal.alive:
return False
sh, sv = world_to_screen(crystal.h, crystal.v, fh, fy)
sh = int(round(sh))
sv = int(round(sv))
return _rect_visible_on_screen(sh, sv, 1, 1)
def update_crystals(crystals):
for crystal in crystals:
if crystal.alive:
crystal.move()
def collect_crystals_for_ship(crystals, fh, fy):
"""Remove crystals on or beside the player ship."""
collected = 0
for crystal in crystals:
if crystal.alive and crystal.touches_ship_pixels(fh, fy, _SHIP_COLLECT_PIXELS):
crystal.alive = False
collected += 1
return collected
def collect_crystals_for_enemies(crystals, enemy_ships, fh, fy):
"""Remove crystals alien ships scoop up."""
for ship in enemy_ships:
if not _enemy_alive(ship):
continue
for crystal in crystals:
if crystal.alive and crystal.touches_enemy_sprite(fh, fy, ship):
crystal.alive = False
def prune_dead_crystals(crystals):
crystals[:] = [crystal for crystal in crystals if crystal.alive]
def draw_crystals(canvas, crystals, fh, fy):
for crystal in crystals:
if crystal.alive:
crystal.draw(canvas, fh, fy)
return canvas
def update_sparks(sparks):
alive = []
for spark in sparks:
spark.move(LAYER_WIDTH, LAYER_HEIGHT)
spark.lifespan -= 1
if spark.lifespan > 0:
alive.append(spark)
sparks[:] = alive
def draw_sparks(canvas, sparks, fh, fy):
for spark in sparks:
spark.draw(canvas, fh, fy)
def update_enemy_particles(particles, dt):
alive = []
for particle in particles:
if not particle.alive:
continue
particle.move(dt)
if particle.lifespan > 0:
alive.append(particle)
particles[:] = alive
def draw_enemy_particles(canvas, particles, fh, fy):
for particle in particles:
particle.draw(canvas, fh, fy)
def _add_asteroids_to_layer(layer, count, size_range, dim_factor=1.0, obstacle_map=None, layer_name=None):
"""Scatter Blasteroids-style rocks across a parallax layer."""
smin, smax = size_range
for _ in range(count):
cx = random.randint(0, layer.width - 1)
cy = random.randint(0, layer.height - 1)
size = random.randint(smin, smax)
color = _pick_layer_asteroid_color(layer_name) if layer_name else _pick_asteroid_color()
_paint_asteroid_to_layer(
layer, cx, cy, size, color, _generate_asteroid_lumps(),
dim_factor, obstacle_map=obstacle_map,
)
STAR_DIM_FACTOR = 0.7
def _star_rgb(brightness, purple=False):
"""Blue-tinted star, dimmed 30%; optional slight purple for distant stars."""
brightness = max(1, int(brightness * STAR_DIM_FACTOR))
if purple:
return (
max(0, min(255, brightness * 45 // 100)),
max(0, min(255, brightness * 22 // 100)),
max(0, min(255, brightness * 88 // 100)),
)
return (
max(0, brightness // 5),
max(0, brightness // 3),
brightness,
)
def _add_far_stars(layer, starchance=184):
"""Sparse blue stars on FarBackground only — varying brightness."""
lw = layer.width
lh = layer.height
star_positions = []
for y in range(lh):
for x in range(lw):
if random.randint(0, starchance) != 1:
layer.map[y][x] = (0, 0, 0)
continue