我完全是红宝石初学者我正在努力学习ruby的第45课,目前正在创建一个类似于zork和冒险的游戏。
我创建了一个结构,在其中我在不同的文件中创建“场景”,并要求所有场景都在一个文件中,其中我有一个引擎/映射,确保当前场景不等于“完成”,它运行“x”场景的“enter”方法。
但是我有两个问题:
1)我一直收到一个错误,说“警告类变量从顶层访问”
2)即使脚本正在运行,我仍然得到
ex45.rb:30:in `play': undefined method `enter' for nil:NilClass (NoMethodError) from ex45.rb:59:in
下面是我每个文件中的所有代码。我很抱歉,如果这是一个长期阅读,但我想知道为什么我得到这两个错误,我可以做些什么来纠正它们。
Ex45.rb号:
require "./scene_one.rb"
require "./scene_two.rb"
require "./scene_three.rb"
@@action = SceneOne.new
@@action_two = SceneTwo.new
@@action_three = SceneThree.new
class Engine
def initialize(scene_map)
@scene_map = scene_map
end
def play()
current_scene = @scene_map.opening_scene()
last_scene = @scene_map.next_scene('finished')
while current_scene != last_scene
next_scene_name = current_scene.enter()
current_scene = @scene_map.next_scene(next_scene_name)
end
current_scene.enter()
end
end
class Map
@@scenes = {
'scene_one' => @@action,
'scene_two' => @@action_two,
'scene_three' => @@action_three
}
def initialize(start_scene)
@start_scene = start_scene
end
def next_scene(scene_name)
val = @@scenes[scene_name]
return val
end
def opening_scene()
return next_scene(@start_scene)
end
end
a_map = Map.new('scene_one')
a_game = Engine.new(a_map)
a_game.play()
场景1.rb:
类SceneOne
def enter
puts "What is 1 + 2?"
print "> "
answer = $stdin.gets.chomp
if answer == "3"
puts "Good job"
return 'scene_two'
else
puts "try again"
test
end
end
end
场景2.rb
class SceneTwo
def enter
puts "1 + 3?"
print "> "
action = $stdin.gets.chomp
if action == "4"
return 'scene_three'
else
puts "CANNOT COMPUTE"
end
end
end
场景3.rb
class SceneThree
def enter
puts "This is scene three"
end
end
提前谢谢!
最佳答案
回答你的第一个问题:
您需要在Map
类中移动类变量定义以消除这些警告:
Ex45.rb:5: warning: class variable access from toplevel
Ex45.rb:6: warning: class variable access from toplevel
Ex45.rb:7: warning: class variable access from toplevel
因此,您的
Map
类将如下所示:class Map
@@action = SceneOne.new
@@action_two = SceneTwo.new
@@action_three = SceneThree.new
@@scenes = {
'scene_one' => @@action,
'scene_two' => @@action_two,
'scene_three' => @@action_three
}
def initialize(start_scene)
@start_scene = start_scene
end
def next_scene(scene_name)
val = @@scenes[scene_name]
return val
end
def opening_scene()
return next_scene(@start_scene)
end
end
回答你的第二个问题:
你得到
undefined method 'enter' for nil:NilClass (NoMethodError)
是因为你的current_scene
在某个时刻变成nil
,然后你尝试调用:current_scene.enter()
即nil.enter
并失败,并显示错误消息。要解决这个问题,你必须确保你的
current_scene
中总是有一些值,即确保它不是nil
。我认为,您可以从
current_scene.enter()
类中的play
方法的末尾移除Engine
行因此,您的Engine
类将如下所示:class Engine
def initialize(scene_map)
@scene_map = scene_map
end
def play()
current_scene = @scene_map.opening_scene()
last_scene = @scene_map.next_scene('finished')
while current_scene != last_scene
next_scene_name = current_scene.enter()
current_scene = @scene_map.next_scene(next_scene_name)
end
# current_scene.enter()
end
end
而且,你不会再犯那个错误了。
关于ruby-on-rails - 从顶层访问类变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32804409/