我正在基於迄今爲止學過的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
類就知道要到下一哪個房間。我也試圖在不實現類繼承的情況下做到這一點。謝謝!
http://codereview.stackexchange.com/ – tokland