我不知道如何修复它,所以它从health类变量中去掉了10个,因为它说这是一个错误。
/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.to_i -= 10但它只会带来另一个错误:
undefined method `to_i=' for nil:NilClass (NoMethodError)发布于 2017-05-04 17:27:32
错误消息告诉您attacked方法中的@health == nil。你需要在某个地方初始化这个值!通常,这将位于类的适当命名的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,除非已经定义了@ ||=。
发布于 2017-05-04 20:02:39
正如@omnikron所提到的,您的@health未初始化,因此-=在尝试从nil中减去时会抛出异常。如果我们使用initialize方法,我想象你的对象类如下:
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
endhttps://stackoverflow.com/questions/43778796
复制相似问题