我正在制作一个基于文本的简短游戏,作为基于我目前所学 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
类知道下一个去哪个房间。我也试图在不实现类继承的情况下做到这一点。谢谢!
最佳答案
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
关于Ruby:在类之间使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12573843/