Skip to content

Commit

Permalink
Don't use a deque for trail history
Browse files Browse the repository at this point in the history
  • Loading branch information
lordmauve committed Apr 16, 2019
1 parent 258946c commit ae14529
Showing 1 changed file with 42 additions and 15 deletions.
57 changes: 42 additions & 15 deletions examples/basic/stars.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import math
import random
from collections import deque

WIDTH = 1000
HEIGHT = 1000 * 9 // 16
Expand All @@ -20,31 +19,39 @@
class Star:
__slots__ = (
'pos', 'vel', 'brightness',
'speed', 'prev_pos'
'speed', 'position_history'
)

def __init__(self, pos, vel):
self.pos = pos
self.vel = vel
self.brightness = 10
self.speed = math.hypot(*vel)
self.prev_pos = deque(maxlen=TRAIL_LENGTH)
self.prev_pos.append(self.pos)

def set_pos(self, pos):
self.pos = pos
self.prev_pos.append(pos)
@property
def end_pos(self):
"""Get the point where the star trail ends."""
x, y = self.pos
vx, vy = self.vel

return (
x - vx * warp_factor / 30,
y - vy * warp_factor / 30,
)


def draw():
screen.clear()

# Draw all our stars
for star in stars:
b = star.brightness
color = (b, b, b) # a grey
screen.draw.line(star.prev_pos[0], star.pos, color)
screen.draw.line(star.end_pos, star.pos, color)

# Head-up-display
screen.draw.text(
"Warp {:0.1f}".format(warp_factor),
"||| Warp {:0.1f} |||".format(warp_factor),
fontsize=40,
midbottom=(WIDTH // 2, HEIGHT - 40),
color=(180, 160, 0),
Expand All @@ -59,35 +66,55 @@ def draw():

def update(dt):
global stars, warp_factor

# Calculate the new warp factor
if keyboard.space:
# If space is held, accelerate
warp_factor += ACCEL * dt

# Apply drag to slow us, regardless of whether space is held
warp_factor = (
MIN_WARP_FACTOR +
(warp_factor - MIN_WARP_FACTOR) * DRAG ** dt
)

# Spawn new stars until we have 300
while len(stars) < 300:
# Pick a direction and speed
angle = random.uniform(-math.pi, math.pi)
dx = math.cos(angle)
dy = math.sin(angle)
speed = 255 * random.uniform(0.3, 1.0) ** 2

# Turn the direction into position and velocity vectors
dx = math.cos(angle)
dy = math.sin(angle)
d = random.uniform(25, 100)
pos = centerx + dx * d, centery + dy * d
vel = speed * dx, speed * dy

v = speed * dx, speed * dy
stars.append(Star(pos, v))
stars.append(Star(pos, vel))

# Update the positions of stars
for s in stars:
x, y = s.pos
vx, vy = s.vel

# Move according to speed and warp factor
x += vx * warp_factor * dt
y += vy * warp_factor * dt
s.set_pos((x, y))
s.pos = x, y

# Grow brighter
s.brightness = min(s.brightness + warp_factor * 200 * dt, s.speed)

# Get faster
s.vel = vx * 2 ** dt, vy * 2 ** dt
stars = [star for star in stars if BOUNDS.collidepoint(star.prev_pos[0])]

# Drop any stars that are completely off-screen
stars = [
star
for star in stars
if BOUNDS.collidepoint(star.end_pos)
]


# Jump-start the star field
Expand Down

0 comments on commit ae14529

Please sign in to comment.