0

I'm not a skillful programmer by any means, but everyone's got to start somewhere. I've been trying to make a (very) basic maze-type in ruby, but I'm having difficulty with the while loop not exiting.

Room layout is an upside down t:

 5
 2
103
 4

Going north twice from the center should change @loc to 5, say "End", and exit the loop:

elsif @loc == 2
@loc = 5
puts "End"

But it returns to the beginning of the while loop, stranding the player.

EDIT: there's some confusion about the code, so I'm removing the block and pointing you to http://pastebin.com/EFWVBAhn

4
  • We need to see more of your code. What are your classes? Most likely in your cmd.go_north you're accessing the @loc field of cmd, not of whatever your maze class is. But we can't tell until we see the code. Commented Mar 4, 2013 at 23:35
  • How do you expect the while statement to exit while @loc's value isn't changing? Try checking the value of that variable at the beggining of the statement with a puts or something. Commented Mar 4, 2013 at 23:37
  • Please indent, especially when troubleshooting loops! And it never exits because @loc is never 5. But you haven't posted the code where @loc changes, so it's hard to say what the problem is. Commented Mar 4, 2013 at 23:38
  • I added debug code to my working copy and can confirm that @loc is getting changed. Commented Mar 4, 2013 at 23:59

1 Answer 1

1

The line

while @loc != 5

is accessing a variable which is not being changed. The changes are happening to cmd.loc, which is not the same variable. That line needs to be

while cmd.loc != 5

in order to access the variable.

Also you need to quote your strings (e.g. if command == west should be if command == "west"); otherwise you're telling Ruby to compare to a variable called west, which doesn't exist, rather than the string "west".

Sign up to request clarification or add additional context in comments.

3 Comments

I did make that mistake with the strings, but it was corrected. I just forgot to recopy it.
puts @loc returns 5 for the expected space, so that should not the issue.
Where is the line puts @loc?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.