Ben G. wrote:
Stuck again. My random monster-fight generator works, but it’s so BASIC.
How can I do this without the if-statements? Is it a bad thing to stick
class objects into an array?
Also, I know Moblist[0].fight works, but why not Moblist[0…2].fight ?
##############################################
class Mob
def fight
“THIS IS A FIGHT METHOD”
end
end
GOBO = Mob.new
DRAGON = Mob.new
SLIME= Mob.new
Moblist = [GOBO, DRAGON, SLIME]
def rand_fight
a = rand(Moblist.length)#<-----------Has to be a better way|
if a ==0 then GOBO.fight
elsif a==1 then DRAGON.fight
elsif a==2 then SLIME.fight
end#------------------------------------------------------|
end
p rand_fight
##############################################
As the great Julian R. once said, one level of indirection solves
everything.
Also, I know Moblist[0].fight works, but why
not Moblist[0…2].fight ?
Because [0…2] is a Range object, which does not respond to the fight
method. You could monkey patch (ducks) Range to make it work, but a
better idea would be to take a step back and create a class responsible
for representing multiple monsters. GroupOfMonsters or MonsterParty,
perhaps?
As with your rand(Moblist.length) bit, that should also be put into its
own class (or several classes). Think about what you’re really trying to
say, then figure out the players (objects) and who is responsible for
doing what.
If you’re trying to write anything remotely resembling a game, you’ve a
lot of work ahead of you.
Have you looked at _why’s creature code?
http://poignantguide.net/ruby/chapter-6.html