class MonkeyMusic::Monkey

Attributes

capacity[RW]
carrying[R]
character[RW]
facing[R]
name[RW]
score[RW]

Public Class Methods

from_players(players) click to toggle source
# File lib/monkey_music/units/monkey.rb, line 10
def self.from_players(players)
  @player_index &&
    players[@player_index] &&
    players[@player_index].monkey
end
new() click to toggle source
# File lib/monkey_music/units/monkey.rb, line 16
def initialize
  @score = 0
  @capacity = 1
  @carrying = []
  @delivered = []
  @facing = [:west, :east].sample
end
player(number) click to toggle source
# File lib/monkey_music/units/monkey.rb, line 6
def self.player(number)
  Class.new Monkey do @player_index = number - 1 end
end

Public Instance Methods

deliver!() click to toggle source
# File lib/monkey_music/units/monkey.rb, line 55
def deliver!
  @delivered += @carrying
  @score += tally(@carrying)
  @carrying = []
end
interact_with!(unit) click to toggle source
# File lib/monkey_music/units/monkey.rb, line 41
def interact_with!(unit)
  case unit
  when Track then pick_up!(unit)
  when User then deliver!
  end
end
move!(direction) click to toggle source
# File lib/monkey_music/units/monkey.rb, line 24
def move!(direction)
  target = translate(@x, @y, direction)
  if target_unit = @level.at(*target)
    # Interact with unit
    interact_with!(target_unit)
  else
    # Face the right direction
    @facing = case direction
      when :west then :west
      when :east then :east
      else @facing
    end
    # Perform move
    @x, @y = *target if @level.accessible?(*target)
  end
end
pick_up!(unit) click to toggle source
# File lib/monkey_music/units/monkey.rb, line 48
def pick_up!(unit)
  if @carrying.count < @capacity
    @level.remove(unit)
    @carrying << unit
  end
end
remaining_capacity() click to toggle source
# File lib/monkey_music/units/monkey.rb, line 69
def remaining_capacity
  (@capacity - carrying.count) || 0
end
serialize() click to toggle source
# File lib/monkey_music/units/monkey.rb, line 73
def serialize
  "M#{@id}"
end
tally(tracks) click to toggle source
# File lib/monkey_music/units/monkey.rb, line 61
def tally(tracks)
  score = 0
  tracks.each do |track|
    score += track.value
  end
  score
end
to_json(options = {}) click to toggle source
# File lib/monkey_music/units/monkey.rb, line 81
def to_json(options = {})
  { :id => @id,
    :x => @x,
    :y => @y,
    :facing => @facing,
    :type => self.class.name.split('::').last,
    :name => @name,
    :score => @score,
  }.to_json
end