直接上代码:
#encoding:utf-8
class 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)
end
class Player
#创建Get Set方法
#保存名字和当前位置
attr_accessor :name,:location
def initialize(player_name)
@name = player_name
end
end
class 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}"
end
end
#Main
my_dungeon = Dungeon.new("larry")
#Add rooms
my_dungeon.add_room(:largecave, "大洞穴", "大的,空荡荡的洞穴", {:west => :smallcave})
my_dungeon.add_room(:smallcave, "小洞穴", "小的,密闭的洞穴", {:east => :largecave})
#Start
my_dungeon.start(:largecave)
my_dungeon.go(:west)
my_dungeon.go(:east)
运行结果:
大洞穴
在 大的,空荡荡的洞穴
去 west
小洞穴
在 小的,密闭的洞穴
去 east
大洞穴
在 大的,空荡荡的洞穴