ruby小例子-‘洞穴’文字游戏

直接上代码:

#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
大洞穴
 
在 大的,空荡荡的洞穴

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值