1

我正在制作一个简短的基于文本的游戏,作为基于我到目前为止所学的 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班级知道接下来要去哪个房间。我也试图在不实现类继承的情况下做到这一点。谢谢!

4

1 回答 1

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
于 2012-09-24T22:51:01.447 回答