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

时间:2018-01-08 20:24:20

标签: ruby compare

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

我的问题是我不知道如何比较用户输入(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 + "\n\nYou 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 

1 个答案:

答案 0 :(得分:0)

您需要访问所有房间并找到具有该符号的房间。你不需要一个case语句,你应该能够验证它是一个有效的房间,然后发送它:

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

这是测试rooms[y]是否真实(不返回零或假值)。如果y不存在,则哈希(my_dungeon.rooms)将返回nil。这是一个虚假的价值。

相关问题