2011-10-10 48 views
0

我正在Ruby中进行一个简单的基于文本的地下城游戏,我遇到了一个障碍。基本上,我有一个房间有一个锁着的门。钥匙在另一个房间里找到,我希望一旦钥匙被找到,门就会被解锁。从Ruby中的另一种方法结束循环中的一个方法?

这里是我到目前为止有:

def chest_room 
    puts "You are in a small, round room." 
    puts "On the floor in front of you is a small wooden chest." 
    puts "It does not appear to be locked." 
    puts "What do you do?" 
    chest_open = false 

    while true 
    prompt; next_move = gets.chomp 
    if next_move == "open chest" 
    chest_open = true 
    puts "Inside the chest, you see a small, brass key." 
    puts "What do you do?" 
    prompt; next_move = gets.chomp 
    elsif next_move == "take key" and chest_open 
    key_present = true  
    puts "You take the key and slip it into a pocket." 
    puts "What do you do?" 
    prompt; next_move = gets.chomp 
    elsif next_move == "go back" 
    start() 
    else puts "I don't understand you." 
    puts "What do you do?" 
    prompt; next_move = gets.chomp 
    end 
    end 
end 

def start 
    puts "You find yourself in a dank room lit by torches." 
    puts "There are three doors leading out of here." 
puts "What do you do?" 
door_open = false 
key_present = false 
while true 
    prompt; next_move = gets.chomp 
    if next_move == "door 1" 
    chest_room() 
    elsif next_move == "door 2" 
    dais() 
    elsif next_move == "door 3" and not door_open 
    puts "This door is securely locked." 
    puts "You'll need to find some way of opening it before you can enter." 
    puts "What do you do?" 
    prompt; next_move = gets.chomp 
    elsif next_move == "door 3" and key_present 
    door_open = true 
    puts "The key you found fits easily into the lock." 
    puts "With a click, you unlock the door!" 
    orb_room() 
    else 
    puts "I don't understand you." 
    puts "What do you do?" 
    prompt; next_move = gets.chomp 
    end 
    end 
end 

任何输入或建议吗?本质上,我想在找到键时结束door_open = false循环,但我无法弄清楚如何在chest_room方法中设置door_open = true,然后从start方法调用它。谢谢!

回答

1

您遇到的问题的范围。通过在其前面放置一个@来使door_open或key_present实例变量。然后任何方法都可以访问它们。同样情况下,/当清洁比,如果ELSIF

while [email protected]_present # @key_present can be modified in another method 
    prompt; next_move = gets.chomp 
    case 
    when "door 1" == next_move then chest_room() # put constants first when comparing == 
    when "door 2" == next_move then dais() 
    # more conditions 
    end 
end 
+0

感谢您的回答!我比以前更喜欢你的解决方案,所以我会尝试一下。 – illbzo1

3

你真正需要的是备份并再次思考设计。你有一个房间,它有一个“开放”或“关闭”的属性。您有一个密钥,并且您需要密钥才能更改该打开/关闭属性的状态。

写出你想要做的事情,并考虑如何将它建模为房间和钥匙,并且你将会走上更好的轨道。

(不,我不想给你答案。想出来的是更重要的。)

+2

+1如果你不遵循这个建议,你的代码很可能将最终会被很复杂,绝对类似http://bit.ly/o37l86 – timoxley

+0

我需要记住该链接。 –

+0

@CharlieMartin感谢您的输入!我一直在跟着学习Ruby难以建立我的Ruby技巧,并且可能对这个问题太过近视。我会根据你的建议重新思考我在做什么,并再次尝试。 – illbzo1

相关问题