-
Notifications
You must be signed in to change notification settings - Fork 1
/
ship.py
662 lines (561 loc) · 20.5 KB
/
ship.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
"""Spaceships, shooting through space."""
from __future__ import annotations
import math
import random
from enum import Enum
from re import S
from typing import TYPE_CHECKING
import pygame
from pygame import Color
from pygame.math import Vector2 as Vec2
from physics import Disk
from projectiles import Bullet, Rocket, Missile
from constants import (
BULLET_SPEED,
DAMAGE_INDICATOR_TIME,
ENEMY_BULLET_COOLDOWN,
GUNBARREL_LENGTH,
GUNBARREL_WIDTH,
ENEMY_SHOOT_RANGE,
ENEMY_THRUST_MULTIPLIER,
ENEMY_ACTION_TIMER,
ENEMY_HEALTH,
ENEMY_ACTION_WEIGHTS,
ENEMY_ROCKET_COOLDOWN,
GUN_COOLDOWN,
ENEMY_VISUAL_RANGE,
WORLD_SIZE,
SMOL,
ENEMY_MISSILE_COOLDOWN,
)
if TYPE_CHECKING:
from camera import Camera
class Ship(Disk):
"""A basic spaceship."""
def __init__(
self,
pos: Vec2,
vel: Vec2,
density: float,
size: float,
color: Color,
bullet_color: Color,
) -> None:
"""Create a new spaceship.
Args:
----
pos (Vec2): Initial position
vel (Vec2): Initial velocity
density (float): Density (of disk-body)
size (float): Radius of disk-body
color (Color): Material color
bullet_color (Color): Bullet_color
"""
super().__init__(pos, vel, density, size, color)
self.size: float = size
self.angle: float = 0
self.health: float = 100.0
self.projectiles: list[Bullet] = []
self.gun_cooldown: float = 0
# This just just determines cooldown once at the very start.
self.has_trophy: bool = False
self.bullet_color = Color(bullet_color)
self.ammo: int = 3700
self.thrust: float = 250 * self.mass
self.rotation_thrust: float = 230
self.thruster_rot_left: bool = False
self.thruster_rot_right: bool = False
self.thruster_backward: bool = False
self.thruster_forward: bool = False
self.max_fuel: float = 100.0
self.fuel: float = self.max_fuel
self.fuel_consumption_rate: float = 0.5
self.fuel_rot_consumption_rate: float = 0.5
self.damage_indicator_timer: float = 0
def get_faced_direction(self) -> Vec2:
"""Get `self`'s faced direction from its `angle`.
Returns
-------
Vec2: Faced direction, normalized
"""
# For unknown reasons, `Vec2.from_polar((self.angle, 1))` won't work.
direction = Vec2()
direction.from_polar((1, self.angle))
return direction
def shoot(self) -> None:
"""Try to shoot a bullet."""
if self.gun_cooldown <= 0 and self.ammo > 0:
forward = self.get_faced_direction()
bullet_pos = self.pos + forward * self.radius * GUNBARREL_LENGTH
bullet_vel = self.vel + forward * BULLET_SPEED
self.projectiles.append(Bullet(bullet_pos, bullet_vel, self.bullet_color))
self.gun_cooldown = GUN_COOLDOWN
self.ammo -= 1
def suffer_damage(self, damage: float) -> None:
"""Deal damage to the ship and activate its damage-indicator.
Does nothing if damage is <= 0.
Args:
----
damage (float): Amount of damage to deal.
"""
if damage > 0:
self.health -= damage
self.damage_indicator_timer = DAMAGE_INDICATOR_TIME
def step(self, dt: float) -> None:
"""Physics, control, and bullet-stepping for `self`.
Args:
----
dt (float): Passed time
"""
if self.fuel > 0:
if self.thruster_rot_left:
self.fuel = max(0, self.fuel - dt * self.fuel_rot_consumption_rate)
self.angle += self.rotation_thrust * dt
if self.thruster_rot_right:
self.fuel = max(0, self.fuel - dt * self.fuel_rot_consumption_rate)
self.angle -= self.rotation_thrust * dt
forward = self.get_faced_direction()
if self.thruster_forward:
self.fuel = max(0, self.fuel - dt * self.fuel_consumption_rate)
self.apply_force(forward * self.thrust, dt)
if self.thruster_backward:
self.fuel = max(0, self.fuel - dt * self.fuel_consumption_rate)
self.apply_force(-forward * self.thrust, dt)
self.damage_indicator_timer = max(0, self.damage_indicator_timer - dt)
super().step(dt)
for projectile in self.projectiles:
projectile.step(dt)
self.gun_cooldown = max(0, self.gun_cooldown - dt)
def draw(self, camera: Camera) -> None:
"""Draw `self` on `camera.
Args:
----
camera (Camera): Camera to draw on
"""
forward = self.get_faced_direction()
right = Vec2(-forward.y, forward.x)
left = -right
backward = -forward
base_color: Color = self.color.lerp(Color("red"), self.damage_indicator_timer)
darker_color: Color = base_color.lerp(Color("black"), 0.5)
# Helper function for drawing polygons relative to the ship-position
def drawy(color: Color, points: list[Vec2]) -> None:
camera.draw_polygon(color, [self.pos + self.radius * p for p in points])
# thruster_backward (active)
if self.thruster_backward:
drawy(Color("orange"), [forward * 2, left * 1.25, right * 1.25])
# "For his neutral special, he wields a gun"
camera.draw_line(
darker_color,
self.pos,
self.pos + forward * self.radius * GUNBARREL_LENGTH,
GUNBARREL_WIDTH * self.radius,
)
# thruster_rot_left (material)
drawy(
darker_color,
[
0.7 * left + 0.7 * forward,
0.5 * left + 0.5 * backward,
2.0 * left + 1.0 * backward,
],
)
# thruster_rot_left (active)
if self.thruster_rot_left:
drawy(
Color("orange"),
[
1.5 * left + 1.25 * backward,
0.5 * left + 0.5 * backward,
2.0 * left + 1.0 * backward,
],
)
# thruster_rot_right (material)
drawy(
darker_color,
[
0.7 * right + 0.7 * forward,
0.5 * right + 0.5 * backward,
2.0 * right + 1.0 * backward,
],
)
# thruster_rot_right (active)
if self.thruster_rot_right:
drawy(
Color("orange"),
[
1.5 * right + 1.25 * backward,
0.5 * right + 0.5 * backward,
2.0 * right + 1.0 * backward,
],
)
# thruster_forward (flame)
if self.thruster_forward:
drawy(
Color("orange"),
[
0.7 * left + 0.7 * backward,
0.5 * left + 1.5 * backward,
1.25 * backward,
0.5 * right + 1.5 * backward,
0.7 * right + 0.7 * backward,
],
)
# thruster_forward (material)
drawy(
darker_color,
[
0.7 * left + 0.7 * backward,
0.5 * left + 1.25 * backward,
1.0 * backward,
0.5 * right + 1.25 * backward,
0.7 * right + 0.7 * backward,
],
)
# Ugly hack
backup_self_color = Color(self.color)
self.color = base_color
super().draw(camera) # Draw circular body ("hitbox")
self.color = backup_self_color
for projectile in self.projectiles:
projectile.draw(camera)
class ShipInput:
"""Specification for which keys trigger what spaceship-action."""
type PygameKey = int
def __init__(
self,
thruster_rot_left: PygameKey,
thruster_rot_right: PygameKey,
thruster_forward: PygameKey,
thruster_backward: PygameKey,
shoot: PygameKey,
) -> None:
"""Create a new map from keys to spaceship-actions.
Args:
----
thruster_rot_left (pygame_key): Left rotation thruster's key
thruster_rot_right (pygame_key): Right rotation thruster's key
thruster_forward (pygame_key): Forward thruster's key
thruster_backward (pygame_key): Backward thruster's key
shoot (pygame_key): Pew pew key
"""
self.thruster_rot_left = thruster_rot_left
self.thruster_rot_right = thruster_rot_right
self.thruster_forward = thruster_forward
self.thruster_backward = thruster_backward
self.shoot = shoot
class PlayerShip(Ship):
"""A player-controlled spaceship."""
def __init__(
self,
pos: Vec2,
vel: Vec2,
density: float,
size: float,
color: Color,
bullet_color: Color,
spaceship_input: ShipInput,
image_path: str,
) -> None:
"""Create a new player-spaceship.
Args:
----
pos (Vec2): Initial position
vel (Vec2): Initial velocity
density (float): Density (of disk-body)
size (float): Radius of disk-body
color (Color): Material color
bullet_color (Color): Bullet_color
spaceship_input (SpaceshipInput): Map from keys to actions
image_path (str): Path to image
"""
super().__init__(pos, vel, density, size, color, bullet_color)
self.spaceship_input = spaceship_input
self.image = pygame.image.load(image_path)
def handle_input(self, keys: pygame.key.ScancodeWrapper) -> None:
"""Handle input for `self` using ScancodeWrapper `keys`.
`keys` is typically retreived using `pygame.key.get_pressed()`
Args:
----
keys (pygame.key.ScancodeWrapper): Pressed keys
"""
self.thruster_rot_left = keys[self.spaceship_input.thruster_rot_left]
self.thruster_rot_right = keys[self.spaceship_input.thruster_rot_right]
self.thruster_forward = keys[self.spaceship_input.thruster_forward]
self.thruster_backward = keys[self.spaceship_input.thruster_backward]
if keys[self.spaceship_input.shoot]:
self.shoot()
def draw(self, camera: Camera) -> None:
"""Draw `self` on `camera.
Args:
----
camera (Camera): Camera to draw on
"""
forward = self.get_faced_direction()
right = Vec2(-forward.y, forward.x)
left = -right
backward = -forward
base_color: Color = self.color.lerp(Color("red"), self.damage_indicator_timer)
darker_color: Color = base_color.lerp(Color("black"), 0.5)
# Helper function for drawing polygons relative to the ship-position
def drawy(color: Color, points: list[Vec2]) -> None:
camera.draw_polygon(color, [self.pos + self.radius * p for p in points])
# thruster_backward (active)
if self.thruster_backward:
drawy(Color("orange"), [forward * 2, left * 1.25, right * 1.25])
# "For his neutral special, he wields a gun"
camera.draw_line(
darker_color,
self.pos,
self.pos + forward * self.radius * GUNBARREL_LENGTH,
GUNBARREL_WIDTH * self.radius,
)
# thruster_rot_left (material)
drawy(
darker_color,
[
0.7 * left + 0.7 * forward,
0.5 * left + 0.5 * backward,
2.0 * left + 1.0 * backward,
],
)
# thruster_rot_left (active)
if self.thruster_rot_left:
drawy(
Color("orange"),
[
1.5 * left + 1.25 * backward,
0.5 * left + 0.5 * backward,
2.0 * left + 1.0 * backward,
],
)
# thruster_rot_right (material)
drawy(
darker_color,
[
0.7 * right + 0.7 * forward,
0.5 * right + 0.5 * backward,
2.0 * right + 1.0 * backward,
],
)
# thruster_rot_right (active)
if self.thruster_rot_right:
drawy(
Color("orange"),
[
1.5 * right + 1.25 * backward,
0.5 * right + 0.5 * backward,
2.0 * right + 1.0 * backward,
],
)
# thruster_forward (flame)
if self.thruster_forward:
drawy(
Color("orange"),
[
0.7 * left + 0.7 * backward,
0.5 * left + 1.5 * backward,
1.25 * backward,
0.5 * right + 1.5 * backward,
0.7 * right + 0.7 * backward,
],
)
# thruster_forward (material)
drawy(
darker_color,
[
0.7 * left + 0.7 * backward,
0.5 * left + 1.25 * backward,
1.0 * backward,
0.5 * right + 1.25 * backward,
0.7 * right + 0.7 * backward,
],
)
rotated_image = pygame.transform.rotate(self.image, -self.angle - 90)
# Get the width and height of the rotated image
image_rect = rotated_image.get_rect()
center_offset = Vec2(image_rect.width / 2, image_rect.height / 2)
# Adjust the position to center the image
adjusted_pos = self.pos - center_offset
# Ugly hack
backup_self_color = Color(self.color)
self.color = base_color
super().draw(camera) # Draw circular body ("hitbox")
self.color = backup_self_color
for projectile in self.projectiles:
projectile.draw(camera)
camera.draw_image(rotated_image, adjusted_pos)
class BulletEnemy(Ship):
"""An enemy ship, targeting a specific other ship."""
Action = Enum(
"Action",
[
"accelerate_to_player",
"accelerate_randomly",
"decelerate",
],
)
def __init__(
self,
pos: Vec2,
vel: Vec2,
target_ship: Ship,
color: Color = Color("lime"),
bullet_color: Color = Color("hotpink"),
) -> None:
"""Create a new enemy ship.
Args:
----
pos (Vec2): Initial position
vel (Vec2): Initial velocity
target_ship (Ship): Ship to target
color (Color, optional): Material color. Defaults to Color("purple").
bullet_color (Color): Color of shot projectiles
"""
super().__init__(pos, vel, 1, 8, color, bullet_color)
self.thrust *= ENEMY_THRUST_MULTIPLIER
self.action_timer = 0
self.health = ENEMY_HEALTH
self.current_action: BulletEnemy.Action = (
BulletEnemy.Action.accelerate_randomly
)
self.target_ship = target_ship
self.projectiles: list[Bullet] = []
self.random_point = Vec2(0, 0)
def step(self, dt: float) -> None:
"""Apply physics and "AI" to `self`.
Args:
----
dt (float): Passed time
"""
self.action_timer -= dt
delta_target_ship = self.target_ship.pos - self.pos
if self.action_timer <= 0:
self.random_point = Vec2(
random.uniform(0, WORLD_SIZE.x), random.uniform(0, WORLD_SIZE.y)
)
# print(self.current_action)
# print(self.random_point)
if delta_target_ship == Vec2(0, 0):
delta_target_ship = Vec2(SMOL, SMOL)
if delta_target_ship.magnitude_squared() < ENEMY_VISUAL_RANGE**2:
self.current_action = BulletEnemy.Action.accelerate_to_player
else:
[self.current_action] = random.choices(
population=[
BulletEnemy.Action.accelerate_randomly,
BulletEnemy.Action.decelerate,
],
weights=ENEMY_ACTION_WEIGHTS,
)
self.action_timer = ENEMY_ACTION_TIMER
match self.current_action:
case BulletEnemy.Action.accelerate_to_player:
desired_velocity = (
delta_target_ship * self.thrust / delta_target_ship.magnitude()
)
perfect_multiplier = max(
self.target_ship.vel.magnitude() * 1.5, desired_velocity.magnitude()
)
perfect_velocity = desired_velocity.normalize() * perfect_multiplier
required_acceleration = perfect_velocity - self.vel
force_direction = required_acceleration
case BulletEnemy.Action.decelerate:
force_direction = -self.vel
case BulletEnemy.Action.accelerate_randomly:
delta_random_point = self.random_point - self.pos
force_direction = delta_random_point
if force_direction.magnitude() != 0:
force = force_direction * self.thrust / force_direction.magnitude()
self.apply_force(force, dt)
super().step(dt)
# Shooting logic
if (
delta_target_ship.magnitude_squared() < ENEMY_SHOOT_RANGE**2
):
self.shoot()
def shoot(self) -> None:
"""Shoot a bullet."""
if (
self.gun_cooldown <= 0
and self.ammo > 0
and self.current_action == BulletEnemy.Action.accelerate_to_player
):
forward = self.get_faced_direction()
bullet_pos = self.pos + forward * self.radius * GUNBARREL_LENGTH
bullet_vel = self.vel + forward * BULLET_SPEED
self.projectiles.append(Bullet(bullet_pos, bullet_vel, self.bullet_color))
self.gun_cooldown = ENEMY_BULLET_COOLDOWN
self.ammo -= 1
class RocketEnemy(BulletEnemy):
"""An enemy ship shooting rockets, targeting a specific other ship."""
def __init__(
self,
pos: Vec2,
vel: Vec2,
target_ship: Ship,
color: Color = Color("plum"),
) -> None:
"""Create a new Rocket-Ship.
Args:
----
pos (Vec2): Initial position
vel (Vec2): Initial velocity
target_ship (Ship): Ship to target
color (Color, optional): Material color. Defaults to Color("red").
"""
super().__init__(pos, vel, target_ship, color)
def shoot(self) -> None:
"""Shoot a Rocket."""
if (
self.gun_cooldown <= 0
and self.ammo > 0
and self.current_action == BulletEnemy.Action.accelerate_to_player
):
forward = self.get_faced_direction()
bullet_pos = self.pos + forward * self.radius * GUNBARREL_LENGTH
bullet_vel = self.vel
self.projectiles.append(
Rocket(bullet_pos, bullet_vel, self.color, self.target_ship),
)
self.gun_cooldown = ENEMY_ROCKET_COOLDOWN
self.ammo -= 1
class MissileEnemy(BulletEnemy):
"""An enemy ship shooting powerful, smart, homing missiles, targeting a specific other ship."""
def __init__(
self,
pos: Vec2,
vel: Vec2,
target_ship: Ship,
color: Color = Color("blue"),
) -> None:
"""Create a new Missile-Ship.
Args:
----
pos (Vec2): Initial position
vel (Vec2): Initial velocity
target_ship (Ship): Ship to target
color (Color, optional): Material color. Defaults to Color("red").
"""
super().__init__(pos, vel, target_ship, color)
def shoot(self) -> None:
"""Shoot a smart Missile."""
if (
self.gun_cooldown <= 0
and self.ammo > 0
and self.current_action == BulletEnemy.Action.accelerate_to_player
):
forward = self.get_faced_direction()
bullet_pos = self.pos + forward * self.radius * GUNBARREL_LENGTH
bullet_vel = self.vel
self.projectiles.append(
Missile(
bullet_pos,
bullet_vel,
self.color,
self.target_ship,
"assets/missile.png",
),
)
self.gun_cooldown = ENEMY_MISSILE_COOLDOWN
self.ammo -= 1