自学 ruby 用的 ruby 从入门到精通这本书籍,按照书上代码敲了一下,结果 error 了。。。
报错信息如下:
Traceback (most recent call last):
2: from ./game.rb:76:in <main>'
1: from ./game.rb:34:in
go'
./game.rb:29:in `find_room_in_direction': wrong number of arguments (given 1, expected 0) (ArgumentError)
代码如下:
#实验:地下城文本冒险游戏
class Dungeon
attr_accessor :player
def initialize(player_name)
@player = Player.new(player_name)
@rooms = []
end
def add_room(reference, name, description, connections)
@rooms << 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\nYou are in " + @description
end
end
#Player = Struct.new(:name, :location) #可以用Struct创建用于保存数据的特殊类
#Room = Struct.new(:reference, :name, :description, :connections)
end
#Create the main dungeon object
my_dungeon = Dungeon.new("Fred Bloggs")
#Add rooms to the dungeon
my_dungeon.add_room(:largecave, "Large Cave", "a large cavernous cave", { :west => :smallcave })
my_dungeon.add_room(:smallcave, "Small Cave", "a small claustrophobic cave", { :east => :largecave })
#Start the dungeon by placing the player in the large cave
my_dungeon.start(:largecave)
#go to another room
my_dungeon.go(:west)
my_dungeon.go(:east)
阅读报错信息显示应该是 find_room_in_direction 方法里参数个数错误,可是这个方法确实只要一个参数啊,为什么会报错呢? 希望大家能帮我解决这个问题,谢谢!