1

I am making a short, text-based game as an extra credit exercise based on the Ruby I have learned so far and I'm having trouble getting classes to read and write variables between each other. I have read extensively and searched for clarification on how to do this but I haven't had much luck. I have tried using @ instance variables and attr_accessible but I can't figure it out. Here is my code so far:

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

I want to have the different Room classes change the @room_count variable so that Game class knows which room to go to next. I am also trying to do this without implementing class inheritance. Thanks!

1

1 Answer 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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, passing Game as itself through Room works. It all makes sense to me now.
Dont you need @game instead of game in the def of Room#close?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.