我在这个摇滚,纸张,剪刀游戏的得分更新程序中遇到问题,我必须为我的红宝石课程创建。此分配的目的是让用户输入一个选项,计算机也可以使用" rand"进行随机选择,赢得该轮次的任何人都会在每轮结束时显示更新的分数。 。我遇到的问题是计数器只使用第一个if语句进行更新。该程序可以随意选择计算机选项并保存用户响应。因此,所有代码都可以使用得分更新程序。任何帮助将受到高度赞赏。
human_score = 0.0
comp_score = 0.0
while true
print "Lets play rock,paper,scissors", "\n"
print "Do you choose rock, paper, or scissors?", "\n"
choice = STDIN.gets.chomp
comp = rand(3)
if comp == 1
comp_choice = "rock"
elsif comp == 2
comp_choice = "paper"
else
comp_choice = "scissors"
end
print "Computer picked: ", comp_choice, "\n"
print "You picked: ", choice, "\n"
if human_choice = "rock" && comp_choice = "rock"
comp_score += 0.5
human_score += 0.5
print "The result is a tie", "\n"
elsif human_choice = "rock" && comp_choice = "paper"
comp_score += 1
print "Computer wins", "\n"
elsif human_choice = "rock" && comp_choice = "scissors"
human_score += 1
print "You win", "\n"
elsif human_choice = "paper" && comp_choice = "rock"
human_score += 1
print "You win", "\n"
elsif human_choice = "paper" && comp_choice = "paper"
comp_score += 0.5
human_score += 0.5
print "Its a tie", "\n"
elsif human_choice = "paper" && comp_choice = "scissors"
comp_score += 1
print "Computer wins", "\n"
elsif human_choice = "scissors" && comp_choice = "rock"
comp_score += 1
print "Computer wins"
elsif human_choice = "scissors" && comp_choice = "paper"
human_score += 1
print "You win"
else human_choice = "scissors" && comp_choice = "scissors"
human_score += 0.5
comp_score += 0.5
print "Its a tie"
end
print "The computers score is: ", comp_score, "\n"
print "Your score is: ", human_score, "\n"
end
答案 0 :(得分:3)
您正在重新分配变量的值,而不是检查是否相等。
您的版本:
if human_choice = "rock" && comp_choice = "rock"
这会将human_choice
的值设置为“rock”,并与comp_choice
相同。它永远都是真的。
正确版本:
if human_choice == "rock" && comp_choice == "rock"
答案 1 :(得分:1)
此外,您将从键盘读取的值分配给choice
choice = STDIN.gets.chomp
并且您正在使用human_choice
来验证案例。
答案 2 :(得分:0)
默想:
human_score = 0.0
comp_score = 0.0
while true
puts "Lets play rock, paper, scissors"
puts "Do you choose rock, paper, or scissors?"
human_choice = STDIN.gets.chomp
comp_choice = %w[scissors rock paper][rand(3)]
puts "Computer picked: #{ comp_choice }"
puts "You picked: #{ human_choice }"
msg = case [human_choice, comp_choice]
when ['rock', 'rock'], ['paper', 'paper'], ['scissors', 'scissors']
comp_score += 0.5
human_score += 0.5
'The result is a tie'
when ['rock', 'scissors'], ['paper', 'rock'], ['scissors', 'paper']
human_score += 1
'You win'
when ['paper', 'scissors'], ['scissors', 'rock'], ['rock', 'paper']
comp_score += 1
'Computer wins'
end
puts msg
puts "The computer's score is: #{ comp_score }"
puts "Your score is: #{ human_score }"
end
它是用惯用的Ruby编写的。