gpt4 book ai didi

ruby - Beginning Ruby 中的 noMethoderror by Peter Cooper 第 6 章地下城游戏

转载 作者:数据小太阳 更新时间:2023-10-29 08:54:22 27 4
gpt4 key购买 nike

我卡在了第 6 章的部分。这是一个地牢文字冒险游戏,有房间和一个四处移动的玩家。对于 find_room_in_dungeon 方法中使用的 .detect 方法,我不断收到 noMethod 错误。我假设我可能遗漏了一些东西,但我就是想不通是什么。如果有人能帮助我,我将不胜感激。谢谢。

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)

最佳答案

当您分配变量并在 add_room 中访问它时,您调用了变量 @room,但是当您尝试访问它时调用了 @rooms它在 find_room_in_dungeon 中。如果您将其重命名为在所有三种情况下都相同,它将起作用。

我建议将变量命名为 @rooms 而不是 @room 因为它是(可能)多个房间的数组,而不是单个房间。

关于ruby - Beginning Ruby 中的 noMethoderror by Peter Cooper 第 6 章地下城游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5131087/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com