Catching (or saving) errors.

T

Tim Mcd

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. :(

Any help would be greatly appreciated!
 
M

Martin DeMello

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. :(

Any help would be greatly appreciated!

This should illustrate the basic approach:

exits = {:north => 'front of building', :east => 'fork in road'}
print "what now? > "
move = gets.chomp.downcase
dir = case move
when "n", "north"
:north
when "s", "south"
:south
when "e", "east"
:east
when "w", "west"
:west
else
nil
end

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, outh, [e]ast
or [w]est"
end

martin
 
T

Tim Mcd

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...
 
M

Martin DeMello

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

martin
 
T

Tim Mcd

Thanks a ton! You've helped out a lot! Oh, and btw, I still think the
whole obj_sword.strike:)martin) bit is hilarious :p
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,661
Latest member
FloridaHan

Latest Threads

Top