Skip to content
This repository has been archived by the owner on Nov 26, 2020. It is now read-only.

Commit

Permalink
Add scaled time calculation.
Browse files Browse the repository at this point in the history
Fixed #39.
  • Loading branch information
Christopher Peplin committed Oct 20, 2010
1 parent 0abcd62 commit ea3da63
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 12 deletions.
21 changes: 16 additions & 5 deletions app/models/game.rb
@@ -1,5 +1,9 @@
require 'simple'

class Game < ActiveRecord::Base
TIME_SCALE_FACTOR = 1 / 0.2
include SimpleExtensions

TIME_SCALE_FACTOR = [1 / 0.8, 1 / 0.2]

acts_as_limited
has_many :market_prices
Expand Down Expand Up @@ -56,15 +60,22 @@ def current_price market
market.current_price @game
end

def time_since time
TIME_SCALE_FACTOR * speed * (Time.now - time)
end

def in_progress?
not ended
end

def time_since_update
time_since updated_at
end

def to_s
"#{states.count} confirmed players, #{started ? "started #{started}" : "not started"}"
end

private

def time_since time
range_map(speed, 0, 100, TIME_SCALE_FACTOR[0],
TIME_SCALE_FACTOR[1]) * (Time.now - time)
end
end
2 changes: 1 addition & 1 deletion db/schema.rb
Expand Up @@ -47,7 +47,7 @@
t.integer "x", :null => false
t.integer "y", :null => false
t.integer "elevation", :default => 0, :null => false
t.string "type", :null => false
t.string "block_type", :null => false
t.float "wind_speed", :default => 0.0, :null => false
t.integer "water_flow", :default => 0, :null => false
t.integer "sunfall", :default => 5125, :null => false
Expand Down
6 changes: 6 additions & 0 deletions lib/simple.rb
@@ -0,0 +1,6 @@
module SimpleExtensions
def range_map(value, istart, istop, ostart, ostop)
ostart + (ostop - ostart) * (
Float((value - istart)) / Float((istop - istart)))
end
end
17 changes: 11 additions & 6 deletions spec/models/game_spec.rb
Expand Up @@ -73,21 +73,26 @@
(@game.current_price @market).should eq(@market.current_price @game)
end

context "should know how much game-relative time has passed" do
context "that has been updated" do
before do
@game.updated_at = Time.now - 60
@now = Time.now
Time.stubs(:now).returns(@now)
end

it "with a real-time speed" do
it "should scale time passed based on game speed" do
@game.speed = 0
assert_equal @game.time_since(@now), @now - @game.updated_at
real_time = @game.time_since_update
@game.speed = 1
fast_time = @game.time_since_update
real_time.should be > (@now - @game.updated_at)
fast_time.should be > (@now - @game.updated_at)
real_time.should be < fast_time
end

it "with maxiumum speed" do
it "should know how much time has passed with maxiumum speed" do
@game.speed = 1
assert_equal @game.time_since(@now),
Game::TIME_SCALE_FACTOR * (@now - @game.updated_at)
@game.time_since_update.should be > (@now - @game.updated_at)
end
end
end
Expand Down

0 comments on commit ea3da63

Please sign in to comment.