Here’s a little rewrite, note two things:
- The use of the initialize method
- The complete lack of variables that simply hold copies of the
values held in an object
It’s a start
class Creature
attr_reader :name, :attack, :hp
def initialize(name, attack, hp)
@name = name
@attack = attack
@hp = hp
end
def damage(attack)
@hp -= attack
end
def alive?
@hp > 0
end
end
hero = Creature.new(“Levi”, 10, 100)
frog = Creature.new(“Frog”, 1, 10)
rat = Creature.new(“Rat”, 3, 20)
rabbit = Creature.new(“Rabbit”, 4, 25)
snake = Creature.new(“Snake”, 8, 25)
while hero.alive?
puts “What would you like to do?”
action = gets.chomp
case action
when ‘attack’
puts “Which enemy would you like to get?”
enemy = gets.chomp
my_enemy = nil
case enemy
when "frog"
my_enemy = frog
when "rat"
my_enemy = rat
when "rabbit"
my_enemy = rabbit
when "snake"
my_enemy = snake
end
if my_enemy
if my_enemy.alive?
my_enemy.damage(hero.attack)
if my_enemy.alive?
puts "You deal the #{my_enemy.name} #{hero.attack} points of
damage, it retaliates"
hero.damage(my_enemy.attack)
puts “The #{my_enemy.name} deals you #{my_enemy.attack}
points of damage”
else
puts “Splat, the #{my_enemy.name} is dead”
end
else
puts “He’s dead Jim”
end
else
puts “You viciously attack a #{enemy}, which ignores you because
you can’t spell”
end
when “walk”
puts “You are walking man”
else
puts “please enter a valid action”
end
end
puts “You died”