Ruby 我不知道为什么这个石头、布、剪刀的游戏不起作用
我不知道这个游戏有什么问题:Ruby 我不知道为什么这个石头、布、剪刀的游戏不起作用,ruby,Ruby,我不知道这个游戏有什么问题: print "Welcome to Rock, Paper, Scissors!" print " All outcomes are randomly generated and independent from your answer." puts " Rock, paper, scissors:" answer = gets.chomp! answer.capitalize! cpu = 3 if cpu == 1 cpu = "Rock" end
print "Welcome to Rock, Paper, Scissors!"
print "
All outcomes are randomly generated and independent from your answer."
puts "
Rock, paper, scissors:"
answer = gets.chomp!
answer.capitalize!
cpu = 3
if cpu == 1
cpu = "Rock"
end
if cpu == 2
cpu = "Paper"
end
if cpu == 3
cpu = "Scissors"
end
print "
Your answer: #{answer}
CPU answer: #{cpu}"
if cpu == answer
print "
Winner: It's a tie"
end
if answer = "Rock" && cpu = "Paper"
print "
Winner: CPU"
end
if answer = "Rock" && cpu = "Scissors"
print "
Winner: Human"
end
它在最后输出所有可能的答案,例如:
Your answer: Rock
CPU answer: Scissors
Winner: CPU
Winner: Human
在代码末尾,有几个地方您意外地使用了赋值运算符=,而不是等式检查运算符=。Alexander 代码末尾有两个错误 在if条件中,replace=to==
if answer == "Rock" && cpu = "Paper"
print "
Winner: CPU"
end
if answer == "Rock" && cpu = "Scissors"
print "
Winner: Human"
end
这里有一个更像Ruby的方法来解决您的问题
WINS = { "rock"=>"scissors", "paper"=>"rock", "scissors"=>"paper" }
def outcome(first, second)
return :WIN if WINS[first] == second
return :LOSE if WINS[second] == first
:TIE
end
outcome("rock", "scissors") #=> :WIN
outcome("rock", "paper") #=> :LOSE
outcome("rock", "rock") #=> :TIE
在最后两个if中,您使用=,而不是将它们与==进行比较。我发现很难识别这些多行print和put语句。我对Ruby相当陌生,我不知道这个游戏有什么问题-现在是学习一些调试技巧的最佳时机。会让你更加自主,而不是像鱼一样离开水。我用了很多技巧。谢谢大家的帮助。看起来很好用