目标是让计算机正确猜出玩家的4种颜色序列。玩家通过循环的每个实例猜测一种颜色。如果计算机猜测正确,那么最终输出应该从播放器输出4个正确颜色的序列。允许重复。我正在考虑设置一个数组并将其与第一个元素一起存储。然后推动添加下一个正确的颜色。或者另一种方法是使用| item,index |来执行each.index ?
colors = %w(red green orange yellow blue purple)
guess_counter = 0
while guess_counter < 4 do
comp_guess = colors.sample
puts "Enter your guess: "
guess = gets.chomp
puts "Computer guessed: " + comp_guess
if(guess == comp_guess)
puts "You got it right."
puts
else
puts "You got it wrong. Guess again."
puts
end
end
运行以下程序是一个示例。
Enter your guess:
red
Computer guessed: red
You got it right.
Enter your guess:
blue
Computer guessed: blue
You got it right.
Enter your guess:
yellow
Computer guessed: orange
You got it wrong. Guess again.
Enter your guess:
green
Computer guessed: green
You got it right.
Enter your guess:
orange
Computer guessed: yellow
You got it wrong. Guess again.
Enter your guess:
red
Computer guessed: red
You got it right.
所以输出应该是&#34;正确的顺序是红色,蓝色,绿色,红色&#34;
答案 0 :(得分:1)
似乎你也忘记增加guess_counter
(看起来它应该只在猜测正确时增加),如果我们存储正确的猜测,实际上并不需要。否则,每次正确猜测时,只需附加一系列猜测,然后使用join
方法打印它:
colors = %w(red green orange yellow blue purple)
correct_guesses = []
while correct_guesses.size < 4 do
comp_guess = colors.sample
puts "Enter your guess: "
guess = gets.chomp
puts "Computer guessed: " + comp_guess
if(guess == comp_guess)
puts "You got it right."
puts
correct_guesses << guess
else
puts "You got it wrong. Guess again."
puts
end
end
puts "The correct sequence is #{correct_guesses.join(', ')}"