直接上代碼:
#encoding:utf-8class Dungeon #建立Get Set方法 #儲存玩家和room列表 attr_accessor :player def initialize(player_name) @player = Player.new(player_name) @room = [] end #設定玩家location屬性 def start(location) @player.location = location show_current_description end #根據玩家location找到所在房間 def show_current_description puts find_room_in_dungeon(@player.location).full_description end # def find_room_in_dungeon(reference) @room.detect{|room|room.reference == reference} end # def find_room_in_direction(direction) find_room_in_dungeon(@player.location).connections[direction] end # def go(direction) puts "去 #{direction.to_s}" @player.location = find_room_in_direction(direction) show_current_description end #添加房間 def add_room(reference, name, description, connections) @room << Room.new(reference, name, description, connections) end #Player = Struct.new(:name, :location) #Room = Struct.new(:reference, :name, :description, :connections)endclass Player #建立Get Set方法 #儲存名字和當前位置 attr_accessor :name,:location def initialize(player_name) @name = player_name endendclass Room #建立Get Set方法 #儲存名字,說明,與其它房間的串連方式,供其它房間串連的引用 attr_accessor :reference,:name,:description,:connections def initialize(reference, name, description, connections) @reference = reference @name = name @description = description @connections = connections end def full_description "#{@name}\n \n在 #{@description}" endend#Mainmy_dungeon = Dungeon.new("larry")#Add roomsmy_dungeon.add_room(:largecave, "大洞穴", "大的,空蕩蕩的洞穴", {:west => :smallcave})my_dungeon.add_room(:smallcave, "小洞穴", "小的,密閉的洞穴", {:east => :largecave})#Startmy_dungeon.start(:largecave) my_dungeon.go(:west)my_dungeon.go(:east)
運行結果:
大洞穴
在 大的,空蕩蕩的洞穴
去 west
小洞穴
在 小的,密閉的洞穴
去 east
大洞穴
在 大的,空蕩蕩的洞穴