开发者

noMethod error in Beginning Ruby by Peter Cooper chapter 6 dungeon game

I am stuck on the part in chapter 6. It is a dungeon text-adventure game with rooms and a player that moves around. I keep getting a noMethod error for the .detect method used in the find_room_in_dungeon method. I assume that I am probably missing something but I just can't figure out what. I would really appreciate if someone could help me out. thanks.

class Dungeon
  attr_accessor :player

  def initialize(player_name)
    @player=Player.new(player_name)
    @room  = []
  end

  def add_room(reference, name, description, connections)
    @room << Room.new(reference, name, description, connections)
  end

  def start(location)
    @player.location=location
    show_current_description
  end

  def show_current_description
    puts find_room_in_dungeon(@player.location).full_description
  end

  ###
  def find_room_in_dungeon(reference)
    @rooms.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 "you go " + direction.to_s
    @player.location= find_room_in_direction(direction)
    show_current_description
  end

  class Player
    attr_accessor :name, :location

    def 开发者_开发知识库initialize(name)
      @name = name
    end

  end

  class Room
    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 you are in" + @description
    end

  end
end
my_dungeon= Dungeon.new("adventurer")
my_dungeon.add_room(:largecave, "large cave", "a very large cave", {:west => :smallcave})
my_dungeon.add_room(:smallcave, "smallcave", "a small cave", {:east => :largecave})
my_dungeon.start(:largecave)


You called the variable @room when you assigned it and when you access it in add_room, but @rooms when you try to access it in find_room_in_dungeon. If you rename it to be the same in all three cases, it will work.

I would suggest naming the variable @rooms everywhere rather than @room as it is an array of (possibly) multiple rooms, not a single room.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜