【发布时间】:2015-09-27 03:53:52
【问题描述】:
我完全是 Ruby 的初学者。我目前正在学习艰难地学习 Ruby 的第 45 课,并且正在创建一个类似于 Zork 和 Adventure 的游戏。
我创建了一个结构,我在不同的文件中创建“场景”,并要求一个文件中的所有场景,其中我有一个引擎/地图,以确保当前场景不等于“完成”它运行“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()
scene_one.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
scene_two.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
scene_three.rb
class SceneThree
def enter
puts "This is scene three"
end
end
提前致谢!
【问题讨论】:
标签: ruby-on-rails ruby