class StudioGame::Player

Attributes

health[RW]
name[RW]

Public Class Methods

from_csv(string) click to toggle source
# File lib/studio_game/player.rb, line 32
def self.from_csv(string)
  name, health = string.split(',')
        Player.new(name,Integer(health))
end
new(name,health=100) click to toggle source
# File lib/studio_game/player.rb, line 9
def initialize(name,health=100)
        @name = name.capitalize
        @health = health
        @found_treasures = Hash.new(0)
end

Public Instance Methods

<=>(other) click to toggle source
# File lib/studio_game/player.rb, line 37
def <=>(other)
        other.score <=> score
end
each_found_treasure() { |treasure_recreated| ... } click to toggle source
# File lib/studio_game/player.rb, line 51
def each_found_treasure
        @found_treasures.each do |name, points|
                        treasure_recreated = Treasure.new(name, points)
                        yield treasure_recreated
        end
end
found_treasure(treasure) click to toggle source
# File lib/studio_game/player.rb, line 41
def found_treasure (treasure)
        @found_treasures[treasure.name] += treasure.points
        puts "#{@name} found a #{treasure.name} worth #{treasure.points} points."
        puts "#{@name}'s treasures #{@found_treasures}"
end
name=(new_name) click to toggle source

Ruby generated the default name= method for you when you used “attr_accessor :name”, but you can easily override it. For example, if we want to capitalize the name before it's assigned, all we need to do is explicitly define a “name=” method in the Player class:

# File lib/studio_game/player.rb, line 20
def name=(new_name)
        @name=new_name.capitalize
end
points() click to toggle source
# File lib/studio_game/player.rb, line 47
def points
        @found_treasures.values.reduce(0,:+)
end
score() click to toggle source
# File lib/studio_game/player.rb, line 24
def score
        @health + points
end
to_s() click to toggle source
# File lib/studio_game/player.rb, line 28
def to_s
        "I'm #{@name} with a health = #{@health}, points = #{points}, and a score = #{score}."
end