在RPS游戏中为玩家添加积分

时间:2015-10-11 18:54:19

标签: ruby

我正在创建一个Rock Paper Scissors游戏。没有任何错误,但它没有按照我的意愿工作。

不是将分数添加到玩家,而是当玩家按下" R"或者" E"

我不明白在这里发生了什么,有人可以向我解释为什么它没有进行添加?

def welcome
  puts "Welcome to Rock, Paper, Scissors. To begin press 'S'. 
  To learn how to play press 'I'. To quit the game press 'Q'"
    input = gets.chomp
    if input =~ /s/i
      start_game
    elsif input =~ /i/i
      instructions
    else
    exit
  end
end

def start_game
  start_points_P1 = 0
  start_points_P2 = 0
  choice = ['Rock', 'Paper', 'Scissors']
  choicep2 = ['Rock', 'Paper', 'Scissors']
  puts "Press 'R' to roll for Player 1"
  input = gets.chomp!
  puts "Press 'E' to roll for Player 2"
  input = gets.chomp!

  if choice.sample == choicep2.sample
    puts "Draw!"
      start_game
    elsif choice.sample == 'Paper' && choicep2.sample == 'Scissors'
      puts "Player 2 has won! You have gained 10 points! Score: Player 1: #{start_points_p1} Player 2: #{start_points_p2 += 10}"
    elsif choice.sample == 'Scissors' && choicep2.sample == 'Rock'
      puts "Player 2 has won! You have gained 10 points! Score: Player 1: #{start_points_p1} Player 2: #{start_points_p2 += 10}"
    elsif choice.sample == 'Rock' && choicep2.sample == 'Paper'
      puts "Player 2 has won! You have gained 10 points! Score: Player 1: #{start_points_p1} Player 2: #{start_points_p2 += 10}"
    elsif choicep2.sample == 'Paper' && choice.sample == 'Scissors'
      puts "Player 1 has won! You have gained 10 points! Score: Player 1: #{start_points_p1 += 10} Player 2: #{start_points_p2}"
    elsif choicep2.sample == 'Scissors' && choice.sample == 'Rock'
      puts "Player 1 has won! You have gained 10 points! Score: Player 1: #{start_points_p1 += 10} Player 2: #{start_points_p2}"
    elsif choicep2.sample == 'Rock' && choice.sample == 'Paper'
      puts "Player 1 has won! You have gained 10 points! Score: Player 1: #{start_points_p1 += 10} Player 2: #{start_points_p2}"
  end
end

2 个答案:

答案 0 :(得分:1)

每次在samplechoicep2上拨打choice时,都会从您调用它的阵列中选择一个随机值。您应该执行类似player_choice = choice.samplecomputer_choice = choicep2.sample(或computer_choice = choice.sample也能正常工作)的内容,然后在player_choicecomputer_choice之间进行比较。

答案 1 :(得分:0)

代码中您遇到的最大问题可能是重复使用choice.samplechoicep2.sample。每次调用时,它都会从每个数组中返回一个新的随机选择。

这意味着每次测试都是这样的:

elsif choice.sample == 'Paper' && choicep2.sample == 'Scissors'

有一个独立的九分之一的机会它是真的,你看到了结果。这意味着可能会失败所有测试,因为对于每个条件,"玩家"再来一次,你只检查一个可能的确切结果。这根本不像这个游戏的真实版本,玩家每个人都做出一个选择,然后你进行测试。

要以与此游戏通常播放方式相匹配的方式解决此问题,您应该将每个玩家的选择存储在新变量中,并比较这些值。例如。在第一次测试之前,做一些像

这样的事情
p1_plays = choice.sample
p2_plays = choice.sample

(注意你可以重新使用选择列表,因为它没有改变,至少在这个变种中)

您的条件可以引用这样的变量:

elsif p1_plays == 'Paper' && p2_plays == 'Scissors'

顺便说一句,它可能是你的代码的一个很好的补充,以显示每个玩家玩什么。如果您这样做是第一件事,那么它将帮助您验证其余代码中的正确逻辑。