救援球员在地下城游戏中走错了方向

时间:2015-03-27 05:54:15

标签: ruby rescue

我正在尝试使用救援来保存我的地下城游戏,如果玩家按照游戏中不可用的方向键入,而是再次重复他们的位置并询问去哪里。这是相关的代码:

def go(direction)
    puts "You go " + direction.to_s
    @player.location = find_room_in_direction(direction)
    show_current_description
end

def show_current_description
    puts find_room_in_dungeon(@player.location).full_description
    puts "Where will you go?"
    answer = gets.chomp.downcase
        if answer == "exit"
            puts "You somehow teleported out of the cave. Good work."
            exit
        else
            answer = answer.to_sym
            begin
                go(answer)
            rescue
                puts "You can't go that way!"
                show_current_description
            end 
        end
end

这是我通过输入一个不可接受的答案得到的结果:

  

你发现自己在一个巨大的洞穴里。向西是一个小孔径

     你会去哪里?

     

     

你往东走走

     

你不能这样!   你不能这样!   你不能这样!

     

dungeon.rb:40:在show_current_description': undefined method full_description'中为nil:NilClass(NoMethodError)       来自dungeon.rb:52:in rescue in show_current_description' from dungeon.rb:48:in show_current_description'       来自dungeon.rb:20:start' from dungeon.rb:89:in'

以下是所有代码:My full Dungeon Code

1 个答案:

答案 0 :(得分:3)

你的救援正在抓错了。您执行go操作,它指定下一个房间;但它是nil。然后失败的是查找nil上的描述。如果房间不存在,您需要阻止分配,而不是捕获失败的房间描述查找的错误。

编辑:这样的事情可能还可以。

def show_current_description
  loop do
    puts find_room_in_dungeon(@player.location).full_description

    puts "Where will you go?"
    answer = gets.chomp.downcase

    if answer == "exit"
      puts "You somehow teleported out of the cave. Good work."
      exit
    end

    next_location = find_room_in_direction(direction)
    if next_location
      puts "You go " + direction
      @player.location = next_location
      break
    else
      puts "You can't go that way!"
    end
  end
end