Skip to content

Instantly share code, notes, and snippets.

@dsturnbull
Created June 15, 2009 11:07
Show Gist options
  • Select an option

  • Save dsturnbull/130048 to your computer and use it in GitHub Desktop.

Select an option

Save dsturnbull/130048 to your computer and use it in GitHub Desktop.
THREADS = []
class Fixnum ## add seconds/minutes/hours/days to integers
def seconds
self
end
alias_method :second, :seconds
def minutes
self * 60
end
alias_method :minute, :minutes
def hours
self * 60 * 60
end
alias_method :hour, :hours
def days
self * 60 * 60 * 24
end
alias_method :day, :days
end
class Event ## base event class. holds listeners
class << self
@@listeners = {}
def add_listener(object, event, &block)
@@listeners[event] ||= []
@@listeners[event] << [object, block]
end
def fire(event)
listeners = @@listeners[event.class]
if listeners
listeners.each do |object, block|
block.call(event)
end
end
end
end
def fire
Event.fire(self)
end
class MissingEvent < Event
def initialize(*args)
#puts "MissingEvent (#{self.class}) called with args: #{args}"
end
end
class NewUnit < Event
attr_reader :name
def initialize(name)
@name = name
end
end
end
class Events
class << self
def [](event)
klass = event.to_s.split('_').map(&:capitalize).join('')
mod = Kernel.const_get('Event')
if mod.constants.include?(klass)
mod.const_get(klass)
else
implementation = Class.new(Event::MissingEvent) {}
mod.const_set(klass, implementation)
end
end
end
end
class Timer ## simple timer. sleep for t seconds then yield
def initialize(t)
THREADS << Thread.new do
sleep t
yield
end
end
end
module Listener ## listens to events
def listen(event, &block)
event = Events[event]
Event.add_listener(self, event, &block)
end
end
class Unit ## base unit
include Listener
end
class CPU
def initialize
end
def process
end
end
class Game ## main game
include Listener
def start
end
def stop
THREADS.map(&:join)
end
def self.method_missing(method, *args, &block)
@@game ||= Game.new
@@game.send(method, *args, &block)
end
end
Game.listen(:new_unit) do |event|
p event
end
Game.start
u = Unit.new
u.listen(:new) { |event| }
Events[:new_unit].new('dave').fire
Events[:new].new('dave').fire
Game.stop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment