Sha256: b514f2c47396cd8962c75d5a71c891689d14280f3e91910a3151b7ec5481952c

Contents?: true

Size: 1.73 KB

Versions: 6

Compression:

Stored size: 1.73 KB

Contents

# Behavior is any type of behavior an actor can exibit.
class Behavior
  construct_with :actor, :behavior_factory

  attr_accessor :opts

  # Specifies messages that your behavior is interested in and
  # that you have defined methods for in your helpers block.
  #
  #  reacts_with :remove
  #
  #  helpers do
  #    def remove
  #      input_manager.unsubscribe_all self
  #    end
  #  end
  def reacts_with(*messages_with_methods)
    @message_handlers ||= Set.new
    @message_handlers.merge(messages_with_methods)
  end

  # Dispatches reactions to helper methods based on name.
  # See BehaviorDefinition to see how to override this.
  # 
  # @see BehaviorDefinition
  # @see Actor#react_to
  def react_to(message_type, *opts, &blk)
    if @message_handlers && @message_handlers.include?(message_type)
      send message_type, *opts, &blk
    end
  end

  # Builds and adds a behavior based on the name and options passed in.
  #
  #  actor.input.when :shields_up do
  #    add_behavior :invincible, duration: actor.shield_charge
  #  end
  #
  def add_behavior(behavior_name, opts = {})
    behavior_factory.add_behavior actor, behavior_name, opts
  end

  # Removes the behavior by name. Any added attributes will remain on the actor.
  #
  #  actor.input.when :shields_down do
  #    remove_behavior :invincible
  #  end
  #
  def remove_behavior(behavior_name)
    actor.remove_behavior(behavior_name)
  end

  class << self

    def define(behavior_type, &blk)
      @definitions ||= {}
      definition = BehaviorDefinition.new
      definition.source = caller.detect{|c|!c.match /core/}
      definition.instance_eval &blk if block_given?
      @definitions[behavior_type] = definition
    end

    def definitions
      @definitions ||= {}
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
gamebox-0.5.5 lib/gamebox/core/behavior.rb
gamebox-0.5.4 lib/gamebox/core/behavior.rb
gamebox-0.5.2 lib/gamebox/core/behavior.rb
gamebox-0.5.1 lib/gamebox/core/behavior.rb
gamebox-0.5.0 lib/gamebox/core/behavior.rb
gamebox-0.4.1 lib/gamebox/core/behavior.rb