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

时间:2018-08-14 10:41:19

标签: ruby

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

我需要它为每局游戏打几局-第一个赢得两局的玩家才能赢得比赛(每局有两个骰子)

到目前为止,我已经提出了:

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

目前,它仅产生两个随机数,没有错误消息。我需要它来产生许多回合,并且“ Player 1获胜!”或“玩家2获胜!”当其中一个赢得了两轮比赛时。

我在正确的轨道上还是完全错过了什么?

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

在理解while循环方面的任何帮助将不胜感激! 谢谢

1 个答案:

答案 0 :(得分:0)

如评论中所述,您需要在循环内扔骰子。

例如,定义一个返回带有两个结果的数组的方法。

def throw_dices
  return rand(1..6), rand(1..6)
end

您可以使用array decomposition将结果分配给变量:

player_1, player_2 = throw_dices

一旦有了该方法,便可以在循环内使用它。

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.

还请注意abbreviated assignments的使用:player_1_score += 1