我让自己和我的一些朋友成为龙与地下城的战斗助手,因为大部分的保持轨道非常重复所以我认为我可以将某些东西搞砸了。它进展顺利,但现在我遇到了障碍。
这是我的代码
def party8
party7
puts "Last one! What's your eighth player's name?"
player8name = gets.chomp
puts "What's their AC?"
player8ac = gets.chomp.to_i
puts "Got it. What's their max HP?"
player8maxhp = gets.chomp.to_i
end
def partysetup
puts "hi"
if 8 == playercount
party8
else
party1
end
end
#intro----------------------------------------------------------------------
puts "-Hello. I am l1fecount, the DM's combat assistant."
puts "-Before we begin, would you like to see in-depth information about me?"
infoq = gets.chomp
infoq.downcase!
if infoq == "yes"
puts "-Very well, I'm glad to explain. I am l1fecount, a program designed to keep track of up to 5 types of mobs, with up to 10
of each. I can also keep track of up to 8 players. I keep track of turn order, current HP vs max HP, CR, and armor
class. I am still very young, so please be patient with me. ^^; "
else
puts "-Right then."
end
puts "-So, let's begin."
#intro end----------------------------------------------------------------
#party---------------------------------------------------------------------
loop do
puts "How many players today?"
playercount = gets.chomp.to_i
if 0 >= playercount
puts "You can't have no players in a party. That's not D&D, that's you having no friends."
redo
elsif 8 < playercount
puts "Hey now, that's a huge party. I can only handle eight players at once."
redo
elsif 8 >= playercount
break
else
puts "A number between 1 and 8, please."
redo
end
end
partysetup
`
(party1-7存在,但与第8方相同,所以为了简洁起见我没有包含它。)
它运行得很好,直到我尝试运行partysetup。我添加了一个puts语句,所以我可以看到该方法是否被调用,它是,但我一直得到这个:
-Hello. I am l1fecount, the DM's combat assistant.
-Before we begin, would you like to see in-depth information about me?
no
-Right then.
-So, let's begin.
How many players today?
8
hi
Error: undefined method `playercount' for main:Object
我试过寻找简单的拼写错误,将playercount转换为字符串或符号,但没有解决这个问题。请帮忙吗?
答案 0 :(得分:2)
playercount
在循环中定义。由于它没有前缀,因此它是一个局部变量。在这种情况下,它只在循环内部可见。它在您在文件顶部定义的方法不可见。
几乎可以肯定,您不希望使用几乎相同的代码定义8个(或更多!)方法。一种解决方案是将聚会计数作为方法参数:
def party(n)
然后,您可以定义partysetup
来致电party
:
def partysetup(playercount)
# Setup stuff
party(playercount)
end
有几种方法可以为party
玩家写n
。它可能不是最好的解决方案,但我立即想到了一个递归算法:
$players = []
def party(n)
return if n == 0
party(n-1)
player = {}
puts "What's player #{n}'s name?"
player[:name] = gets.chomp
puts "What's their AC?"
player[:ac] = gets.chomp.to_i
puts "Got it. What's their max HP?"
player[:maxhp] = gets.chomp.to_i
$players[n] = player
end
注意我在$
数组中使用了美元符号($players
)作为前缀。这意味着它是一个全局变量,可供程序的所有部分使用。通常,您希望避免使用全局变量,但在代码中的任何位置访问播放器数据等内容都非常方便。
但Ruby提供全局和本地范围之间的选项。更好的解决方案是创建一个类来管理游戏并将玩家数据存储在实例变量(@players
)中。这为您提供了更大的灵活性(可能同时运行多个游戏?)并让您养成管理范围的习惯。