我正在制作一个简短的基于文本的游戏,作为基于我到目前为止所学的 Ruby 的额外学分练习,我无法让类在彼此之间读取和写入变量。我已经广泛阅读并寻找有关如何执行此操作的说明,但我没有太多运气。我尝试过使用@
实例变量,attr_accessible
但我无法弄清楚。到目前为止,这是我的代码:
class Game
attr_accessor :room_count
def initialize
@room_count = 0
end
def play
while true
puts "\n--------------------------------------------------"
if @room_count == 0
go_to = Entrance.new()
go_to.start
elsif @room_count == 1
go_to = FirstRoom.new()
go_to.start
elsif @room_count == 2
go_to = SecondRoom.new()
go_to.start
elsif @room_count == 3
go_to = ThirdRoom.new()
go_to.start
end
end
end
end
class Entrance
def start
puts "You are at the entrance."
@room_count += 1
end
end
class FirstRoom
def start
puts "You are at the first room."
@room_count += 1
end
end
class SecondRoom
def start
puts "You are at the second room."
@room_count += 1
end
end
class ThirdRoom
def start
puts "You are at the third room. You have reached the end of the game."
Process.exit()
end
end
game = Game.new()
game.play
我想让不同的Room
班级更改@room_count
变量,以便Game
班级知道接下来要去哪个房间。我也试图在不实现类继承的情况下做到这一点。谢谢!