So, I am currently working on an Interactive Fiction like game in Ruby,
and have stumbled across a bit of a problem. The 'move' function makes a
call to the room's 'exits' variable (exits[:north], for instance) but I
want it to catch if the variable :north doesn't exist to display
something like "You can't go taht way!". I can't figure out how to do
this with my meager skills.
if dir
聽聽if exits[dir]
聽聽聽聽puts "moving to #{exits[dir]}"
聽聽else
聽聽聽聽puts "you can't go that way!"
聽聽end
else
聽聽puts "no such direction. please enter one of [n]orth, [s]outh, [e]ast
or [w]est"
end
So, I am currently working on an Interactive Fiction like game in Ruby,
and have stumbled across a bit of a problem. The 'move' function makes a
call to the room's 'exits' variable (exits[:north], for instance) but I
want it to catch if the variable :north doesn't exist to display
something like "You can't go taht way!". I can't figure out how to do
this with my meager skills.
Didn't know a nice if like that would just take care of it! Also, did
you test that code? Or the concept? I'm pretty sure you can't do
exits[avar[. I did some testing with that earlier...
Yep, I tested it before pasting it in. What I'm doing is this:
1. defining exits as a hash
2. writing a case statement to convert move from "N" or "n" or "north"
or "NORTH" to :north
3. using the converted move as a key to look up the exits hash
In the context of a larger game, you'd have a $rooms hash, with unique
identifiers like "front of building" as location keys. So you'd say
if dir
聽聽if exits[dir]
聽聽聽聽player.move_to(exits[dir])
聽聽end
end
where player.move_to(location) would be defined something like
def move_to(location)
聽聽loc = $rooms[location]
聽聽if loc
聽聽聽聽self.current_location = loc
聽聽end
end
Didn't know a nice if like that would just take care of it! Also, did
you test that code? Or the concept? I'm pretty sure you can't do
exits[avar[. I did some testing with that earlier...