将用户输入与 Ruby 中类中的属性进行比较



我是Ruby初学者,我有一个问题。我正在编写此代码 - 地牢冒险,我想使用用户输入(转换为符号(并检查天气地牢符号引用 (:west( 是否存在。如果存在,则应基于用户输入(例如 east(。

我的问题是我不知道如何将用户输入 (y( 与现有引用(:west, :east, :south:, :north(进行比较

提前谢谢你。

class Dungeon
    attr_accessor :player
    def initialize(player)
        @player = player
        @rooms = {}
    end
    def add_room(reference, name, description, connections)
        @rooms[reference] = 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[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
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 + "nnYou are in " + @description
    end
end
 puts "What is your name?"
x = gets.chomp
player = Player.new(x)
puts "Hi #{x}. Welcome to adventure!"
my_dungeon = Dungeon.new(player)
# Add rooms to the dungeon
my_dungeon.add_room(:largecave, "Large Cave", "a large cavernous cave", { :west => :smallcave, :south => :coldcave, :north => :hotcave})
my_dungeon.add_room(:smallcave, "Small Cave", "a small, claustrophobic cave", { :east => :largecave, :south => :coldcave, :north => :hotcave })
my_dungeon.add_room(:coldcave, "Cold Cave", "a cold, icy cave", { :north => :hotcave })
my_dungeon.add_room(:hotcave, "Hot Cave", "a hot, very hot cave", { :south => :coldcave })
# Start the dungeon by placing the player in the large cave
my_dungeon.start(:largecave)
puts "Where would you like to go? west, north or south?"
y = gets.chomp.to_sym
#Here is the problem that I am not able to solve:
case y
    when y == Room::reference then my_dungeon.go(y)
    else  puts "There is no cave there" 
end 

您需要访问所有房间并找到哪个房间具有该符号。 您不需要案例陈述,您应该能够验证它是有效的房间之一,然后发送:

if(my_dungeon.rooms[y])
  my_dungeon.go(y)
else
  puts "There is no cave there"
end

这是测试rooms[y]是否为真(不返回 nil 或 false 值(。 当y不存在时,哈希(my_dungeon.rooms(将返回nil。 这是一个错误的值。

相关内容

  • 没有找到相关文章

最新更新