Ruby:在类之间使用变量

时间:2012-09-24 22:31:07

标签: ruby

我正在制作一个简短的基于文本的游戏作为基于我迄今为止学到的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类知道下一个要转到哪个房间。我也试图在不实现类继承的情况下这样做。谢谢!

1 个答案:

答案 0 :(得分:3)

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