我正在使用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方法调用它。谢谢!
答案 0 :(得分:3)
你真正需要的是备份并再次思考设计。您有一个房间,它有一个“开放”或“关闭”的属性。你有一把钥匙,你需要钥匙来改变那个开/关房产的状态。
写出你想做的事情,并考虑如何将它建模为房间和钥匙,你将会走得更好。
(不,我不想给你答案。弄清楚它更重要。)
答案 1 :(得分:1)
你有范围问题。通过在它们前面加上@来制作door_open或key_present实例变量。然后任何方法都可以访问它们。案例/何时比elsif更清洁
while !@key_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