-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrocket.py
More file actions
70 lines (55 loc) · 2.1 KB
/
Copy pathrocket.py
File metadata and controls
70 lines (55 loc) · 2.1 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
# PY5 IMPORTED MODE CODE
from dna import DNA
class Rocket:
def __init__(self, x: float, y: float, dna: DNA):
"""A rocket has three vectors: position, velocity, and acceleration."""
self.dna = dna # A rocket has DNA.
self.fitness = 0.0 # A rocket has fitness.
self.position = Py5Vector2D(x, y)
self.velocity = Py5Vector2D()
self.acceleration = Py5Vector2D()
self.r = 4 # Size.
self.gene_counter = 0 # A counter for the DNA genes list.
def calculate_fitness(self, target: Py5Vector2D) -> None:
"""How close did the rocket get?"""
distance = self.position.dist(target)
# Fitness is inversely proportional to distance.
self.fitness = 1 / distance # linear
# self.fitness = 1 / (distance * distance) # quadratic
def run(self) -> None:
"""# Apply a force from the genes list."""
self.apply_force(self.dna.genes[self.gene_counter])
self.gene_counter += 1 # Go to the next force in the genes list.
self.update() # Update the rocket's physics.
self.show()
def apply_force(self, force: Py5Vector2D) -> None:
"""Accumulate forces into acceleration (Newton's second law)."""
self.acceleration += force
def update(self) -> None:
"""A simple physics engine (Euler integration)."""
# Velocity changes according to acceleration.
self.velocity += self.acceleration
# Position changes according to velocity.
self.position += self.velocity
self.acceleration *= 0
def show(self) -> None:
angle = self.velocity.heading + PI / 2
r = self.r
stroke(0)
stroke_weight(1)
push()
translate(self.position.x, self.position.y)
rotate(angle)
# Thrusters.
rect_mode(CENTER)
fill(0)
rect(-r / 2, r * 2, r / 2, r)
rect(r / 2, r * 2, r / 2, r)
# Rocket body.
fill(175)
begin_shape(TRIANGLES)
vertex(0, -r * 2)
vertex(-r, r * 2)
vertex(r, r * 2)
end_shape(CLOSE)
pop()