Ruby - 如何制作完美的计数器方法

时间:2016-09-08 07:58:37

标签: ruby

我这里有一个ruby程序,它计算赢得的计算机数量和用户赢得的数量。这里的想法是谁获得5胜第一将是胜利者并将输出一个特殊信息"你赢了5次你真的是胜利者!" :

VALID_CHOICES = { 
 'l' => 'light',
 'p' => 'prost', 
 'k' => 'kronge',
}

def display(message)
  Kernel.puts("=>#{message}")
end

def test_win?(first, second)
  (first == 'l' && second == 'p') ||
    (first == 'p' && second == 'k') ||
    (first == 'k' && second == 'p') ||
end

player_count = 0
computer_count = 0
end

请反击。

当我计算双方的胜利时,我怎样才能确保我在这方面得到正确的逻辑?

2 个答案:

答案 0 :(得分:1)

你试过这个吗?

def output_results(player, computer)

      if win?(player, computer)
        player_count+= 1
        if player_count == 5
         display("You won!")
        end
      elsif win?(computer, player)
        computer_count+= 1
        if computer_count == 5
          display("Computer won! You loose!")
        end
      else
        display("It's a tie! No one wins!")
      end

    end

答案 1 :(得分:0)

好吧,我真的不明白问题是什么,但根据您发布的代码,这是一个有效的例子 - 绝不是“完美”,它只是一个起点。

VALID_CHOICES = {
 'l' => 'light',
 'p' => 'prost',
 'k' => 'kronge',
}

@player_count = 0
@computer_count = 0
@end_game = false

def display(message)
  Kernel.puts("=>#{message}")
end

def test_win?(first, second)
  (first == 'l' && second == 'p') ||
    (first == 'p' && second == 'k') ||
    (first == 'k' && second == 'p')
end

def output_results(player, computer)
  if test_win?(player, computer)
    @player_count += 1
    if @player_count == 5
      @end_game = true
      display("You won the game!")
    else
      display("You won this round!")
    end
  elsif test_win?(computer, player)
    @computer_count += 1
    if @computer_count == 5
      @end_game = true
      display("Computer won! You loose!")
    else
      display("Computer won this round!")
    end
  else
    display("It's a tie! No one wins!")
  end

  display("Player: #{@player_count}")
  display("Computer: #{@computer_count}")
end

until @end_game
  computer_choice = VALID_CHOICES.keys.sample
  display("==================================================================")
  display("Choose your weapon (type l for Light, p for Prost, k for Kronge): ")
  choice = Kernel.gets().chomp()
  display("==================================================================")


  display("You chose: #{VALID_CHOICES[choice]}, computer choose: #{VALID_CHOICES[computer_choice]}")
  output_results(choice, computer_choice)
end

假设您将此文件另存为“my_game.rb”,您可以在命令提示符下使用ruby my_game.rb运行它(您必须位于正确的文件夹中)。

编辑:如果这对您没有帮助或者您有更多问题,我们可以打开聊天。