Ruby:在类之间使用变量
我正在做一个简短的基于文本的游戏,作为一个额外的学分练习,它基于我迄今为止所学的Ruby,我在让类读取和写入彼此之间的变量方面遇到了困难。我已经阅读了大量的书籍,并寻求关于如何做到这一点的澄清,但我运气不太好。我尝试过使用Ruby:在类之间使用变量,ruby,Ruby,我正在做一个简短的基于文本的游戏,作为一个额外的学分练习,它基于我迄今为止所学的Ruby,我在让类读取和写入彼此之间的变量方面遇到了困难。我已经阅读了大量的书籍,并寻求关于如何做到这一点的澄清,但我运气不太好。我尝试过使用@实例变量和attr\u accessible,但我想不出来。以下是我目前的代码: class Game attr_accessor :room_count def initialize @room_count = 0 end def play
@
实例变量和attr\u 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\u count
变量,以便游戏
类知道下一个去哪个房间。我还试图在不实现类继承的情况下实现这一点。谢谢 谢谢,通过房间传递游戏本身是有效的。这一切对我来说都很有意义。你不需要@game而不是房间里的game#close吗?
class Room
def initialize(game)
@game = game
@game.room_count += 1
end
def close
@game.room_count -= 1
end
end
class Game
attr_accessor :room_count
def initialize
@room_count = 0
end
def new_room
Room.new self
end
end
game = Game.new
game.room_count # => 0
room = game.new_room
game.room_count # => 1
room.close
game.room_count # => 0