【问题标题】:Rescue player from going wrong direction in dungeon game在地牢游戏中从错误的方向拯救玩家
【发布时间】:2015-03-27 05:54:14
【问题描述】:

如果玩家输入的方向在游戏中不可用,我会尝试使用救援来拯救我的地牢游戏,以免出现错误,而是会再次向他们重复他们的位置并询问去哪里。以下是相关代码:

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:in show_current_description': undefined methodfull_description' for nil:NilClass (NoMethodError) 来自地牢.rb:52:in rescue in show_current_description' from dungeon.rb:48:inshow_current_description' 来自地牢.rb:20:in start' from dungeon.rb:89:in'

这里是所有代码:My full Dungeon Code

【问题讨论】:

  • 您好,欢迎来到 Stack Overflow。请确保您在问题本身中有尽可能多的相关代码。本题中,相关代码为go方法;我们不应该为了它去异地。
  • 谢谢@Amadan。如果我一开始就知道它是相关代码,我会包含它。显示我知道多少!还是新手!

标签: ruby rescue


【解决方案1】:

你的救援抓错了。您执行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

【讨论】:

  • 嗨@Amadan 感谢您的回复。我已经尝试根据您的建议修复我的救援,但我只是收到更多错误消息。老实说,这是我第一次使用救援,所以我仍在试图弄清楚它是如何工作的。你能再描述一下和/或告诉我什么是拯救 go 方法的有效方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多