I've created this game thing in order to learn OOP and I'm having trouble with part of it. Here's what's causing me problems:
I have two classes. On line 3 of class Player, I have some code which is probably way wrong, but basically, what I'm trying to do is use armor to modify how much damage a player receives. I'm getting an error, though: "undefined method 'protection' for nil:NilClass (NoMethodError)
I have Armor as another class. I think the problem might relate to the fact that I am calling @armor.protection when protection is mentioned in Armor and @armor is mentioned in Player, but I am unsure how to fix this. I have added all the code I believe is relevant to my question below. Like I said, I'm really new at this, so please use terminology a noob could understand.
class Player
def equip(armor)
@armor = armor
end
def hit(damage)
#damage = damage - @armor.protection
@health -= damage
end
end
class Armor
def initialize(name, protection)
@protection = protection
end
end
EDIT: added additional code to show all of what I've got going on for clarification. I don't expect anyone to read all of what I've got, though. :S It's probabably scary and snarled up. :P
class Player
def initialize(name, health)
@name = name
@health = health
end
def equip(armor)
@armor = armor
end
def health
@health
end
def health=(value)
@health = value
end
def hit(damage)
damage = damage - @armor.protection
@health -= damage
end
def dead?
if @health <= 0
return true
elsif @health > 0
return false
end
end
def name
@name
end
def attack(target)
damage = rand(30)
puts "#{@name} attacks #{target.name}"
target.hit(damage)
puts "#{@name} hits #{target.name} for #{damage} damage."
end
end
class Armor
def initialize(name, protection)
@protection = protection
end
end
player1 = Player.new("Melanie", 100)
player2 = Player.new("a Monster", 200)
shirt = Armor.new('shirt', 4)
player1.equip(shirt)
while player1.dead? == false && player2.dead? == false
player1.attack(player2)
if player2.health > 0
puts "#{player2.name}'s health is at #{player2.health}."
elsif player2.health <= 0
puts "#{player2.name} has no health."
end
player2.attack(player1)
if player1.health > 0
puts "#{player1.name}'s health is at #{player1.health}."
elsif player1.health <= 0
puts "#{player1.name} has no health."
end
end
if player1.health > player2.health
puts "#{player2.name} is dead."
puts "#{player1.name} wins."
elsif player2.health > player1.health
puts "#{player1.name} is dead."
puts "#{player2.name} wins."
elsif player2.health == player1.health
puts "#{player1.name} and #{player2.name} killed each other."
end