Reputation: 19
I've been messing around in Ruby, thinking of making simple little RPG games. It's been going decently (already have character creation mostly done). But, I was having trouble finding out how to make an attack method (or other kinds of targeted methods, like healing). For example, the method would take a "user" parameter and "target" parameter. It would use the user's stats to influence the target's HP. I've looked for info on this, but I haven't been able to "get" what the threads were about. I'm a beginner, so I'm not even sure if they were speaking of what I'm trying to find out.
Here's basically what I want. Of course, this doesn't work:
class Enemy
attr_accessor :hp, :power
def initialize (hp, power)
@hp = hp
@power = power
end
end
class Hero
attr_accessor :hp, :power
def initialize (hp, power)
@hp = hp
@power = power
end
end
monster = Enemy.new(7,3)
dude = Hero.new(10,5)
def attack(user,target)
user.hp - target.power
end
puts "Dude's HP is #{dude.hp}, and power is #{dude.power}"
puts "Monster's HP is #{monster.hp}, and power is #{monster.power}"
puts " "
puts "Dude attacks!"
attack(dude, monster)
puts "Dude's HP is #{dude.hp}, and power is #{dude.power}"
puts "Monster's HP is #{monster.hp}, and power is #{monster.power}"
puts " "
puts "Monster attacks!"
attack(monster, dude)
puts "Dude's HP is #{dude.hp}, and power is #{dude.power}"
puts "Monster's HP is #{monster.hp}, and power is #{monster.power}"
x = gets
I apologize if this is an extremely noobie question, but I'm just not finding it. If another post has the answer (in a way I can understand), please point me to it.
Perhaps I should also give my code for character creation and stats, so you know what I'm working with?
Thank you for reading my question, and hopefully answering.
Upvotes: 1
Views: 500
Reputation: 845
Try this one:
def attack(user,target)
user.hp -= target.power
end
But I really think you should write it with OOP style like:
class Common
attr_accessor :hp, :power
def initialize(hp, power)
self.hp = hp
self.power = power
end
def hit(target)
p "#{self.class} hits #{target.class}"
target.hp = [target.hp - power, 0].max # you don't want hp less then 0 possible
end
end
class Hero < Commom; end
class Enemy < Common; end
Then use it like
monster = Enemy.new(7,3)
dude = Hero.new(10,5)
moster.hit(dude)
dude.hit(monster)
Upvotes: 2