Monday, October 10, 2011

Scope issues with Ruby

I'm still working through Learn Ruby the Hard Way. The exercise I'm working on now has me building a text-adventure dungeon (similar to the one I made when I was going through Beginning Ruby) but this time around I've got a better idea of how to map the project out.

Basically I'm starting with a simple 4 room dungeon. Players will need to go to one room to get a key to unlock a door in the starting room. I understand how to build rooms and allow a player to navigate between them, but managing an inventory and allowing players to access different rooms once they have completed a specific action (such as finding a key to unlock the door) was confusing me.

After asking for some input on Stack Overflow, I think I've got a better handle on the problem now. I'd originally set door_open = false in the start_room method, then once a player had found the key in the chest_room method, I set door_open to true. However, I couldn't call this from the start_room, because it was a local variable. As far as start_room was concerned, door_open was still = false. Am I thinking about this the right way?

I'll simply make key into an instance variable, so it can be accessed by all methods, and edit the logic so while !@key_present, players can open the door. Easy enough! Just wish I could get to coding NOW instead of tonight.

Also, I've been using if/elsif statements, but the same user suggested case/when is cleaner and simpler. I haven't used case/when before, but from the snippet of code he posted, I think I agree. Your thoughts?

No comments:

Post a Comment