Class: Worlds::Updater

Inherits:
Object
  • Object
show all
Defined in:
lib/worlds/terminal/updater.rb

Overview

A container for ::tick, which processes input and updates the world state.

Constant Summary collapse

UPDATES_PER_SECOND =
1

Class Method Summary collapse

Class Method Details

.started?Boolean

Whether the world has been started.

Returns:

  • (Boolean)


11
12
13
# File 'lib/worlds/terminal/updater.rb', line 11

def self.started?
  !!@time_start
end

.tick(input = nil) ⇒ Array<Hash>?

Processes input if any, or performs an update if enough time has passed.

Parameters:

  • input (Hash) (defaults to: nil)

    a line of input from the player.

Returns:

  • (Array<Hash>, nil)

    an array of output hashes, if input was processed or an update was performed.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/worlds/terminal/updater.rb', line 19

def self.tick(input = nil)
  unless started?
    # On why not Time.now, see
    # https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way
    @time_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)

    return World.setup
  end

  return process_input(input) if input

  time_now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  time_elapsed = time_now - @time_start

  if time_elapsed >= (1.0 / UPDATES_PER_SECOND)
    @time_start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    return update
  end
end