2012-09-24 32 views
1

我正在基於迄今爲止學過的Ruby製作一個簡短的基於文本的遊戲,作爲額外的學分練習,並且我無法讓類彼此讀取和寫入變量。我已經廣泛閱讀,並尋求澄清如何做到這一點,但我沒有多少運氣。我曾嘗試使用@實例變量和attr_accessible,但我無法弄清楚。這是我到目前爲止的代碼:Ruby:在類之間使用變量

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類就知道要到下一哪個房間。我也試圖在不實現類繼承的情況下做到這一點。謝謝!

+0

http://codereview.stackexchange.com/ – tokland

回答

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 
+0

謝謝,通過房間的作品傳遞遊戲本身。現在對我來說這一切都很有意義。 –

+0

你不需要@遊戲而不是遊戲的房間#關閉? – sawa