Ruby-如何在2人骰子游戏中使用while循环和条件语句?

Ruby-如何在2人骰子游戏中使用while循环和条件语句?,ruby,Ruby,编程新手,尝试在Ruby中使用带条件中断的while循环创建一个非常基本的两人掷骰子游戏 我需要它为每场比赛打几轮-第一个赢得两轮的玩家赢得比赛(每个人有两个骰子) 到目前为止,我提出了: player_1 = 2 + rand(6) + rand(6) #generates number between 1-12 (simulating two dice being thrown) player_2 = 2 + rand(6) + rand(6) puts player_1 puts pla

编程新手,尝试在Ruby中使用带条件中断的while循环创建一个非常基本的两人掷骰子游戏

我需要它为每场比赛打几轮-第一个赢得两轮的玩家赢得比赛(每个人有两个骰子)

到目前为止,我提出了:

player_1 = 2 + rand(6) + rand(6) #generates number between 1-12 (simulating two dice being thrown)
player_2 = 2 + rand(6) + rand(6)

puts player_1
puts player_2

player_1_score = 0
player_2_score = 0

while true do
  if player_1 > player_2
    return player_1_score = player_1_score + 1
  elsif player_2 > player_1
    return player_2_score = player_2_score + 1
  end
  if player_1_score == 2
    puts "Player 1 wins!"
    break
  elsif player_2_score == 2
    puts "Player 2 wins!"
    break
  end
end
目前它只生成两个随机数,没有错误消息。我需要它来产生一些回合,当其中一个赢了两轮时,“玩家1赢!”或“玩家2赢!”

我是走对了路还是完全错过了什么

在while循环中可以有多个if语句吗

如果您能帮助理解while循环,我们将不胜感激!
谢谢

如评论中所述,您需要在循环中掷骰子

player_1_score = 0
player_2_score = 0

while true do
  player_1, player_2 = throw_dices # here is the decomposition
  puts "player_1: #{player_1} - player_2: #{player_2}" # print the throw result or whatever
  player_1_score += 1 if player_1 > player_2
  player_2_score += 1 if player_2 > player_1
  break if player_1_score == 2 || player_2_score == 2
end

p player_1_score
p player_2_score
# do whatever you want with the final score.
例如,定义一个返回带有两个结果的数组的方法

def throw_dices
  return rand(1..6), rand(1..6)
end
可以使用以下命令将结果分配给变量:

一旦你有了这个方法,你就可以在循环中使用它了

player_1_score = 0
player_2_score = 0

while true do
  player_1, player_2 = throw_dices # here is the decomposition
  puts "player_1: #{player_1} - player_2: #{player_2}" # print the throw result or whatever
  player_1_score += 1 if player_1 > player_2
  player_2_score += 1 if player_2 > player_1
  break if player_1_score == 2 || player_2_score == 2
end

p player_1_score
p player_2_score
# do whatever you want with the final score.

另请注意:
player\u 1\u score+=1

您不需要将骰子掷入循环中吗?仅供参考
rand(1..6)
返回一个随机数1≤ N≤ 6马上,这样你就不必事后调整了。每轮骰子游戏的规则是什么?我们要从代码中找出答案吗?请编辑以解释游戏的工作原理。例如,在每一轮中,两名玩家都掷两个骰子,而获胜者是两个骰子上的点数总和最大的那个?如果是的话,领带呢?