ruby小例子-‘洞穴’文字遊戲

來源:互聯網
上載者:User

直接上代碼:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.