-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSpaceExplorer.py
More file actions
5023 lines (4346 loc) · 178 KB
/
Copy pathSpaceExplorer.py
File metadata and controls
5023 lines (4346 loc) · 178 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 = 100
# Stronger beam: faster rock damp/pull, firmer ship close + velocity match
TRACTOR_MOMENTUM_DAMP = 0.06
TRACTOR_PULL_RATE = 0.028
TRACTOR_SHIP_MATCH_RATE = 0.12
TRACTOR_SHIP_CLOSE_RATE = 1.25
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 rebound after ramming a rock (was 0.44; cut 50% so bounces are softer)
SHIP_BOUNCE_DAMPING = 0.22
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)),)
# Large mother UFOs — metallic spheres; hunted with crystal missiles after 5 loot
MOTHER_RADIUS = 6 # ~13×13 sprite
MOTHER_HIT_POINTS = 10
MOTHER_CRYSTAL_HUNT_MIN = 5 # banked crystals to start the hunt
MOTHER_COUNT = 3 # blue / green / yellow nav-light mothers
MOTHER_FLOAT_SPEED = 0.11
MOTHER_TURN_WANDER = 0.035
MOTHER_RESPAWN_SEC = 45.0
# SUPER mother — arrives when the whole fleet is wiped; only its death restores the three
SUPER_MOTHER_RADIUS = 12 # ~25×25 sprite
SUPER_MOTHER_HIT_POINTS = 25
SUPER_MOTHER_FLOAT_SPEED = 0.055 # slower than the regular three
SUPER_MOTHER_ATTACK_SPEED = 0.14 # still slow when aggro
# When any mother is hit / targeted, the whole fleet charges the player
MOTHER_ATTACK_SPEED = 0.32
MOTHER_ATTACK_TURN = 0.09
CRYSTAL_MISSILE_SPEED = 2.4
CRYSTAL_MISSILE_TURN = 0.22
CRYSTAL_MISSILE_HIT_R = 7.5
CRYSTAL_MISSILE_FIRE_INTERVAL = 0.32
CRYSTAL_MISSILE_TRAIL = 6 # head + fading white tail length
# Big, long death bloom
MOTHER_EXPLOSION_SPARKS = 140
MOTHER_EXPLOSION_PARTICLES = 260
MOTHER_EXPLOSION_RING_PARTICLES = 80
MOTHER_EXPLOSION_LIFE_SCALE = 3.2 # particle lifespan multiplier
MOTHER_EXPLOSION_SPARK_LIFE = 28 # spark frames (default trail sparks are ~5)
MOTHER_EXPLOSION_KEEP_PIXEL_CHANCE = 0.92 # keep more hull shards
# SUPER death: fill the entire panel with fire + sparks
SUPER_MOTHER_SCREEN_FIRE = 900
SUPER_MOTHER_SCREEN_SPARKS = 320
SUPER_MOTHER_CORE_PARTICLES = 400
SUPER_MOTHER_EXPLOSION_LIFE = 4.5
MOTHER_LIGHT_BLINK_HZ = 2.4
# Primary + alternate blink colors for each of the three mother ships
MOTHER_NAV_PALETTES = (
("blue", (40, 140, 255), (20, 60, 140)), # bright blue / deep blue
("green", (30, 255, 50), (15, 120, 30)), # bright green / deep green
("yellow", (255, 230, 40), (160, 120, 15)), # bright yellow / amber
)
# SUPER mothership multi-color nav lights (includes purple)
SUPER_MOTHER_LIGHT_COLORS = (
(40, 140, 255), # blue
(30, 255, 50), # green
(255, 230, 40), # yellow
(200, 60, 255), # purple
(255, 40, 200), # magenta
(255, 80, 30), # orange
(255, 255, 255), # white
(80, 255, 255), # cyan
(255, 40, 40), # red
(160, 80, 255), # violet
(255, 180, 40), # gold
(120, 255, 120), # mint
)
# Approach speeds — slow down near a mother so she stays on the 64×32 panel
MOTHER_APPROACH_MAX_SPEED = 2.0 # far intercept (well below turbo)
MOTHER_HOLD_MAX_SPEED = 0.72 # close hold — gentle scroll, mother stays framed
MOTHER_SLOW_DIST = 42 # start braking within this world distance
MOTHER_HOLD_DIST = 20 # full slow at/inside this distance
MOTHER_APPROACH_THRUST = 0.038
MOTHER_HOLD_THRUST = 0.016
MOTHER_APPROACH_TURN_RATE = 0.16
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)
#------------------------------------------------------------------------------
# Mother UFO — large metallic sphere with blinking nav lights
#------------------------------------------------------------------------------
def _build_mother_sphere_frame(
light_phase,
light_primary=(30, 255, 50),
light_alt=(15, 120, 30),
radius=None,
multi_lights=None,
):
"""
Procedural shaded metal sphere (center = 0,0).
light_phase 0/1 animates nav lights. multi_lights: many colors (SUPER).
"""
pixels = []
R = int(radius if radius is not None else MOTHER_RADIUS)
R2 = R * R
# Nav light seats on the equator (left/right/top-ish)
if multi_lights:
# Dense ring of lights for SUPER mother
light_seats = []
n = max(12, len(multi_lights) * 2)
for i in range(n):
ang = (2 * math.pi * i) / float(n)
lx = int(round((R - 1) * math.cos(ang)))
ly = int(round((R - 1) * math.sin(ang)))
light_seats.append((lx, ly))
# Inner ring
for i in range(n // 2):
ang = (2 * math.pi * i) / float(n // 2) + 0.3
lx = int(round((R * 0.55) * math.cos(ang)))
ly = int(round((R * 0.55) * math.sin(ang)))
light_seats.append((lx, ly))
else:
light_seats = (
(-R + 1, 0),
(R - 1, 0),
(0, -R + 2),
(0, R - 2),
(-R + 2, -R + 3),
(R - 2, R - 3),
)
for dy in range(-R, R + 1):
for dx in range(-R, R + 1):
d2 = dx * dx + dy * dy
if d2 > R2:
continue
# Sphere normal
nz = math.sqrt(max(0.0, R2 - d2)) / float(R)
nx = dx / float(R)
ny = dy / float(R)
# Key light from upper-left
ndotl = max(0.0, nx * (-0.45) + ny * (-0.55) + nz * 0.78)
# Cool metallic base
metal = 38 + int(165 * ndotl)
rim = (1.0 - nz) * 0.55
r = min(255, int(metal * 0.92 + rim * 50))
g = min(255, int(metal * 0.95 + rim * 55))
b = min(255, int(metal * 1.08 + rim * 70))
# Specular glint
if ndotl > 0.88 and nz > 0.55:
glint = int((ndotl - 0.88) * 900)
r = min(255, r + glint)
g = min(255, g + glint)
b = min(255, b + glint)
# Equator belt slightly darker (panel seam)
if abs(dy) <= 1 and d2 < (R - 1) * (R - 1):
r = max(20, int(r * 0.78))
g = max(20, int(g * 0.80))
b = max(30, int(b * 0.88))
pixels.append((dx, dy, (r, g, b)))
# Nav lights
for i, (lx, ly) in enumerate(light_seats):
if multi_lights:
# Cycle many colors; phase shifts which seats are bright
rgb = multi_lights[(i + light_phase * 3) % len(multi_lights)]
# Dim alternate seats for blink
if ((i + light_phase) % 2) == 1:
rgb = tuple(max(20, int(c * 0.35)) for c in rgb)
else:
if ((i + light_phase) % 2) == 0:
rgb = light_primary
else:
rgb = light_alt
for hx, hy, scale in (
(0, 0, 1.0),
(1, 0, 0.45), (-1, 0, 0.45),
(0, 1, 0.45), (0, -1, 0.45),
):
px, py = lx + hx, ly + hy
if px * px + py * py > R2 + 4:
continue
pixels.append((
px, py,
(
min(255, int(rgb[0] * scale)),
min(255, int(rgb[1] * scale)),
min(255, int(rgb[2] * scale)),
),
))
return pixels
# Cache frames: key -> (phase0, phase1)
_MOTHER_FRAMES_BY_COLOR = {}
def _mother_frames(
light_name,
light_primary=(30, 255, 50),
light_alt=(15, 120, 30),
radius=None,
multi_lights=None,
):
key = (light_name, int(radius or MOTHER_RADIUS), bool(multi_lights))
if key not in _MOTHER_FRAMES_BY_COLOR:
_MOTHER_FRAMES_BY_COLOR[key] = (
_build_mother_sphere_frame(
0, light_primary, light_alt, radius=radius, multi_lights=multi_lights,
),
_build_mother_sphere_frame(
1, light_primary, light_alt, radius=radius, multi_lights=multi_lights,
),
)
return _MOTHER_FRAMES_BY_COLOR[key]
class MotherShip(object):
"""Large floating metallic sphere UFO — minds its own business until hunted."""
def __init__(
self,
h=None,
v=None,
light_name="green",
light_primary=(30, 255, 50),
light_alt=(15, 120, 30),
radius=None,
max_hits=None,
float_speed=None,
attack_speed=None,
multi_lights=None,
is_super=False,
):
if h is None or v is None:
h = random.uniform(0, LAYER_WIDTH)
v = random.uniform(0, LAYER_HEIGHT)
self.h = float(h)
self.v = float(v)
self.is_super = bool(is_super)
self.radius = float(
radius if radius is not None
else (SUPER_MOTHER_RADIUS if self.is_super else MOTHER_RADIUS)
)
self.max_hits = int(
max_hits if max_hits is not None
else (SUPER_MOTHER_HIT_POINTS if self.is_super else MOTHER_HIT_POINTS)
)
self.float_speed = float(
float_speed if float_speed is not None
else (SUPER_MOTHER_FLOAT_SPEED if self.is_super else MOTHER_FLOAT_SPEED)
)
self.attack_speed = float(
attack_speed if attack_speed is not None
else (SUPER_MOTHER_ATTACK_SPEED if self.is_super else MOTHER_ATTACK_SPEED)
)
angle = random.uniform(0, 2 * math.pi)
self.vel_h = math.cos(angle) * self.float_speed
self.vel_v = math.sin(angle) * self.float_speed
self.heading = angle
self.alive = True
self.hits = 0
self.respawn_at = 0.0
self.light_name = light_name
self.light_primary = light_primary
self.light_alt = light_alt
self.multi_lights = multi_lights
# Aliases for hunt intercept math (same fields as asteroids)
self.dx = self.vel_h
self.dy = self.vel_v
def update(self, dt, fh=None, fy=None, pursue_player=False):
if not self.alive:
return
if pursue_player and fh is not None and fy is not None:
# Under attack — turn and drive toward the player
player_wh, player_wv = player_world_position(fh, fy)
dh = _toroidal_delta(self.h, player_wh, LAYER_WIDTH)
dv = _toroidal_delta(self.v, player_wv, LAYER_HEIGHT)
desired = math.atan2(dv, dh)
err = (desired - self.heading + math.pi) % (2 * math.pi) - math.pi
max_turn = MOTHER_ATTACK_TURN * dt * PHYSICS_FPS
if err > max_turn:
err = max_turn
elif err < -max_turn:
err = -max_turn
self.heading += err
speed = self.attack_speed
blend = min(1.0, 0.12 * dt * PHYSICS_FPS)
else:
# Gentle wander — slow heading drift, constant float speed
self.heading += random.uniform(-MOTHER_TURN_WANDER, MOTHER_TURN_WANDER) * (
dt * PHYSICS_FPS
)
speed = self.float_speed
blend = min(1.0, 0.04 * dt * PHYSICS_FPS)
target_vh = math.cos(self.heading) * speed
target_vv = math.sin(self.heading) * speed
self.vel_h += (target_vh - self.vel_h) * blend
self.vel_v += (target_vv - self.vel_v) * blend
self.dx = self.vel_h
self.dy = self.vel_v
self.h = (self.h + self.vel_h * dt * PHYSICS_FPS) % LAYER_WIDTH
self.v = (self.v + self.vel_v * dt * PHYSICS_FPS) % LAYER_HEIGHT
def frame_pixels(self, now):
phase = int(now * MOTHER_LIGHT_BLINK_HZ) % 2
return _mother_frames(
self.light_name,
self.light_primary,
self.light_alt,
radius=int(self.radius),
multi_lights=self.multi_lights,
)[phase]
def draw(self, canvas, fh, fy, now):
if not self.alive:
return
sh, sv = world_to_screen(self.h, self.v, fh, fy)
cx = int(round(sh))
cy = int(round(sv))
# Off-screen cull with margin
if (
cx + self.radius < -2
or cy + self.radius < -2
or cx - self.radius > WIDTH + 2
or cy - self.radius > HEIGHT + 2
):
return
for dx, dy, rgb in self.frame_pixels(now):
px, py = cx + dx, cy + dy
if 0 <= px < WIDTH and 0 <= py < HEIGHT:
canvas.SetPixel(px, py, *rgb)
def contains_world_point(self, wh, wv):
dh = _toroidal_delta(self.h, wh, LAYER_WIDTH)
dv = _toroidal_delta(self.v, wv, LAYER_HEIGHT)
return math.hypot(dh, dv) <= self.radius + 0.8
def take_hit(self):
if not self.alive:
return False
self.hits += 1
return self.hits >= self.max_hits
def revive_at(self, h, v):
"""Respawn this mother (same light color) at a new position."""
self.h = float(h)
self.v = float(v)
angle = random.uniform(0, 2 * math.pi)
self.vel_h = math.cos(angle) * self.float_speed
self.vel_v = math.sin(angle) * self.float_speed
self.heading = angle
self.dx = self.vel_h
self.dy = self.vel_v
self.alive = True
self.hits = 0
self.respawn_at = 0.0
class CrystalMissile(object):
"""Homed crystal fired from the ship when hunting a mother UFO."""
def __init__(self, h, v, angle, target=None):
self.h = float(h)
self.v = float(v)
self.angle = float(angle)
self.speed = CRYSTAL_MISSILE_SPEED
self.alive = True
self.age = 0.0
self.target = target
def update(self, dt, target=None):
if not self.alive:
return
if target is not None:
self.target = target
self.age += dt
if self.age > 8.0:
self.alive = False
return
tgt = self.target
if tgt is not None and not getattr(tgt, "alive", False):
tgt = None
self.target = None
if tgt is not None:
dh = _toroidal_delta(self.h, tgt.h, LAYER_WIDTH)
dv = _toroidal_delta(self.v, tgt.v, LAYER_HEIGHT)
desired = math.atan2(dv, dh)
# Shortest turn toward target
err = (desired - self.angle + math.pi) % (2 * math.pi) - math.pi
max_turn = CRYSTAL_MISSILE_TURN * dt * PHYSICS_FPS
if err > max_turn:
err = max_turn
elif err < -max_turn:
err = -max_turn
self.angle += err
step = self.speed * dt * PHYSICS_FPS
self.h = (self.h + math.cos(self.angle) * step) % LAYER_WIDTH
self.v = (self.v + math.sin(self.angle) * step) % LAYER_HEIGHT
if tgt is not None and tgt.alive:
if tgt.contains_world_point(self.h, self.v):
self.alive = False
return ("hit", tgt)
return None
def draw(self, canvas, fh, fy):
"""Bright white projectile with a fading white tail."""
if not self.alive:
return
trail = CRYSTAL_MISSILE_TRAIL
for i in range(trail):
# Step back along velocity for the tail
wh = (self.h - math.cos(self.angle) * i * 0.85) % LAYER_WIDTH
wv = (self.v - math.sin(self.angle) * i * 0.85) % LAYER_HEIGHT
sh, sv = world_to_screen(wh, wv, fh, fy)
px, py = int(round(sh)), int(round(sv))
if not (0 <= px < WIDTH and 0 <= py < HEIGHT):
continue
# Head = full white; tail fades smoothly to dim white/grey
if i == 0:
canvas.SetPixel(px, py, 255, 255, 255)
# 1px halo for a brighter head on coarse panels
for hx, hy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = px + hx, py + hy
if 0 <= nx < WIDTH and 0 <= ny < HEIGHT:
canvas.SetPixel(nx, ny, 220, 220, 220)
else:
# Linear fade: step 1 ≈ 0.75 white → last step nearly black
fade = max(0.08, 1.0 - (i / float(max(1, trail - 1))) * 0.92)
c = min(255, int(255 * fade))
canvas.SetPixel(px, py, c, c, c)
def _spawn_mother_position(fh=0, fy=0, avoid=None, min_dist=120, min_peer=80):
"""Pick a world position away from the player and optional peer mothers."""
player_wh, player_wv = player_world_position(fh, fy)
avoid = avoid or []
for _ in range(50):
h = random.uniform(0, LAYER_WIDTH)
v = random.uniform(0, LAYER_HEIGHT)
dh = min((h - player_wh) % LAYER_WIDTH, (player_wh - h) % LAYER_WIDTH)
dv = min((v - player_wv) % LAYER_HEIGHT, (player_wv - v) % LAYER_HEIGHT)
if math.hypot(dh, dv) < min_dist:
continue
ok = True
for peer in avoid:
ph = peer.h if hasattr(peer, "h") else peer[0]
pv = peer.v if hasattr(peer, "v") else peer[1]
pdh = min((h - ph) % LAYER_WIDTH, (ph - h) % LAYER_WIDTH)
pdv = min((v - pv) % LAYER_HEIGHT, (pv - v) % LAYER_HEIGHT)
if math.hypot(pdh, pdv) < min_peer:
ok = False
break
if ok:
return h, v
return random.uniform(0, LAYER_WIDTH), random.uniform(0, LAYER_HEIGHT)
def create_mother_ship(fh=0, fy=0, light_name="green",
light_primary=(30, 255, 50), light_alt=(15, 120, 30),
avoid=None):
"""Spawn one mother UFO well away from the player (and peers if given)."""
h, v = _spawn_mother_position(fh, fy, avoid=avoid)
return MotherShip(
h, v,
light_name=light_name,
light_primary=light_primary,
light_alt=light_alt,
)
def create_mother_fleet(fh=0, fy=0):
"""Spawn three mother UFOs: blue, green, and yellow nav lights."""
fleet = []
for light_name, primary, alt in MOTHER_NAV_PALETTES:
m = create_mother_ship(
fh, fy,
light_name=light_name,
light_primary=primary,
light_alt=alt,
avoid=fleet,
)
fleet.append(m)
print(
"[SpaceExplorer] Mother fleet deployed: {}".format(
", ".join(m.light_name for m in fleet)
)
)
return fleet
def create_super_mother(fh=0, fy=0):
"""Spawn the SUPER mother after the regular fleet is wiped out."""
h, v = _spawn_mother_position(fh, fy, min_dist=100, min_peer=0)
mother = MotherShip(
h, v,
light_name="super",
light_primary=(200, 60, 255),
light_alt=(120, 40, 180),
radius=SUPER_MOTHER_RADIUS,
max_hits=SUPER_MOTHER_HIT_POINTS,
float_speed=SUPER_MOTHER_FLOAT_SPEED,
attack_speed=SUPER_MOTHER_ATTACK_SPEED,
multi_lights=SUPER_MOTHER_LIGHT_COLORS,
is_super=True,
)
print(
"[SpaceExplorer] SUPER mother arrived "
"(r={}, hp={})".format(SUPER_MOTHER_RADIUS, SUPER_MOTHER_HIT_POINTS)
)
return mother
def any_mother_alive(mothers):
return any(m is not None and m.alive for m in (mothers or ()))
def active_mother_targets(mother_ships, super_mother):
"""
Combat / AI targets: SUPER alone while she lives; otherwise the three-ship fleet.
"""
if super_mother is not None and super_mother.alive:
return [super_mother]
return [m for m in (mother_ships or ()) if m is not None and m.alive]
def nearest_alive_mother(mothers, fh, fy):
"""Closest living mother to the player, or None."""
best = None
best_d = float("inf")
for m in mothers or ():
if m is None or not m.alive:
continue
d = distance_to_world_point(fh, fy, m.h, m.v)
if d < best_d:
best_d = d
best = m
return best
def mother_on_screen(mother, fh, fy):
if mother is None or not mother.alive:
return False
msh, msv = world_to_screen(mother.h, mother.v, fh, fy)
margin = mother.radius + 1
return (