2

我不知道如何修复它,所以它从健康类变量中取出十个,因为它说这是一个错误。

/home/will/Code/Rubygame/objects.rb:61:in `attacked': undefined method `-' for nil:NilClass (NoMethodError)
    from ./main.rb:140:in `update'
    from /var/lib/gems/2.3.0/gems/gosu-0.10.8/lib/gosu/patches.rb:140:in `tick'
    from /var/lib/gems/2.3.0/gems/gosu-0.10.8/lib/gosu/patches.rb:140:in `tick'
    from ./main.rb:197:in `<main>'

这是main中的代码:

def update
    @player.left if Gosu::button_down? Gosu::KbA
    @player.right if Gosu::button_down? Gosu::KbD
    @player.up if Gosu::button_down? Gosu::KbW
    @player.down if Gosu::button_down? Gosu::KbS
    if Gosu::button_down? Gosu::KbK 
        @player.shot if @player_type == "Archer" or @player_type == "Mage"
        if @object.collision(@xshot, @yshot) == true
            x, y, health = YAML.load_file("Storage/info.yml")
            @object.attacked #LINE 140
        end
    end

end

这是@object.attacked 导致的地方:

 def attacked
    puts "attacked"
    @health -= 10 #LINE 61
    @xy.insert(@health)
    File.open("Storage/info.yml", "w") {|f| f.write(@xy.to_yaml) }
    @xy.delete_at(2)
    if @health == 0
        @dead = true
    end
end 

如果需要,还有 yaml 文件:

   ---
   - 219.0
   - 45.0
   - 100.0

我试图将 .to_i 放在@health 之后,如下所示:

   @health.to_i -= 10

但它只是带来了另一个错误说:

   undefined method `to_i=' for nil:NilClass (NoMethodError)
4

2 回答 2

2

正如@omnikron 所提到的,您@health的未初始化,因此-=在尝试从 中减去时会引发异常nil。如果我们改用初始化方法,我想你的对象类看起来像:

Class Object
  attr_accessor :health

  def initialize
    @health = 100
  end
end

def attacked
  puts "attacked"
  @object.health -= 10 #LINE 61
  @xy.insert(@object.health)
  File.open("Storage/info.yml", "w") {|f| f.write(@xy.to_yaml) }
  @xy.delete_at(2)
  if @health == 0
    @dead = true
  end
end
于 2017-05-04T12:02:38.600 回答
2

错误消息@health == nil在您的attacked方法中告诉您。您需要在某处初始化此值!通常这将在initialize您的类的恰当命名的方法中。或者继续您到目前为止提供的代码,如果当某人第一次受到攻击时,您想将@health实例变量设置为默认值,您可以将其更改为:

def attacked
  @health ||= 100 # or whatever
  puts "attacked"
  @health -= 10 #LINE 61
  @xy.insert(@health)
  File.open("Storage/info.yml", "w") {|f| f.write(@xy.to_yaml) }
  @xy.delete_at(2)
  if @health == 0
    @dead = true
  end
end 

注意:||=语法是 ruby​​ 的条件赋值运算符——意思是 '设置@health为 100,除非 @health 已经定义。

于 2017-05-04T09:27:31.580 回答