Skip to content

Commit

Permalink
Predictable random numbers.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed May 16, 2024
1 parent 2bf00dd commit 8157699
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions examples/flappy-bird/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def render(builder)
end

class Pipe
def initialize(x, y, offset = 100, width: 44, height: 700)
def initialize(x, y, offset = 100, random: 0, width: 44, height: 700)
@x = x
@y = y
@offset = offset
Expand All @@ -94,6 +94,8 @@ def initialize(x, y, offset = 100, width: 44, height: 700)
@height = height
@difficulty = 0.0
@scored = false

@random = random
end

attr_accessor :x, :y, :offset
Expand All @@ -102,11 +104,11 @@ def initialize(x, y, offset = 100, width: 44, height: 700)
attr_accessor :scored

def scaled_random
rand(-1.0..1.0) * [@difficulty, 1.0].min
@random.rand(-1.0..1.0) * [@difficulty, 1.0].min
end

def reset!
@x = WIDTH + (rand * 10)
@x = WIDTH + (@random.rand * 10)
@y = HEIGHT/2 + (HEIGHT/2 * scaled_random)

if @offset > 50
Expand Down Expand Up @@ -169,6 +171,8 @@ def initialize(...)
# Defaults:
@score = 0
@prompt = "Press Space to Start"

@random = nil
end

def close
Expand Down Expand Up @@ -198,10 +202,12 @@ def forward_keypress
end

def reset!
@random = Random.new(1)

@bird = Bird.new
@pipes = [
Pipe.new(WIDTH * 1/2, HEIGHT/2),
Pipe.new(WIDTH * 2/2, HEIGHT/2)
Pipe.new(WIDTH * 1/2, HEIGHT/2, random: @random),
Pipe.new(WIDTH * 2/2, HEIGHT/2, random: @random)
]
@bonus = nil
@score = 0
Expand Down Expand Up @@ -306,11 +312,20 @@ def step(dt)

def run!(dt = 1.0/20.0)
Async do
start_time = Async::Clock.now

while true
self.step(dt)

self.update!
sleep(dt)

duration = Async::Clock.now - start_time
if duration < dt
sleep(dt - duration)
else
Console.info(self, "Running behind by #{duration - dt} seconds")
end
start_time = Async::Clock.now
end
end
end
Expand Down

0 comments on commit 8157699

Please sign in to comment.