我正在尝试用 Ruby 编写 Mastermind 游戏。这是来自 https://www.theodinproject.com/lessons/ruby-mastermind.
的练习我构建了一个方法 #make-guess 循环 4 次从用户那里获取输入并验证它,即确保输入包含在 #BALL 数组中。
为此,我声明了一个条件,如果输入包含在#BALL 数组中,将其附加到数组#guess,否则,再次调用该函数(递归)。
问题是当不包括输入时,#make-guess 函数循环超过 4 次。 这是我正在处理的代码:
class MasterMind
BALLS = ['r', 'g', 'o', 'y', 'v', 'm']
comp_selection = BALLS.sample(4)
def make_guess
guess = []
until guess.length == 4
puts "Guess the computer's combination from: 'r', 'g', 'o', 'y', 'v', 'm'"
value = gets.chomp
if BALLS.include?(value)
guess.append(value)
else
puts 'Selection not in the combination, try again'
make_guess
end
end
guess
end
end
master = MasterMind.new
puts master.make_guess
这里不需要递归。 (至少在你使用它的地方)
class MasterMind
BALLS = ['r', 'g', 'o', 'y', 'v', 'm']
comp_selection = BALLS.sample(4)
def make_guess
guess = []
until guess.length == 4
puts "Guess the computer's combination from: 'r', 'g', 'o', 'y', 'v', 'm'"
value = gets.chomp
if BALLS.include?(value)
guess.append(value)
else
puts 'Selection not in the combination, try again'
# Remove this line to fix your problem.
# make_guess
end
end
guess
end
end
master = MasterMind.new
puts master.make_guess