Java 剪刀纸石头的算法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20271325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:45:18  来源:igfitidea点击:

Algorithm for scissor paper stone

c#javaalgorithm

提问by kar

I am using the following method which works but wondering if there is a better algorithm to perform the test. Is there a better way to do it? Doing this in C# but putting syntax aside, believe the algorithm is going to be the same across OOP languages. Thank you.

我正在使用以下有效的方法,但想知道是否有更好的算法来执行测试。有没有更好的方法来做到这一点?在 C# 中执行此操作但将语法放在一边,相信算法将在 OOP 语言中相同。谢谢你。

public String play(int userInput)
        {   //ComputerIn is a randomly generated number between 1-3
            ComputerIn = computerInput();

            if (ComputerIn == userInput)
                return "Draw";

            else if (ComputerIn == 1 && userInput == 2)
                return "Win";

            else if (ComputerIn == 2 && userInput == 3)
                return "Win";

            else if (ComputerIn == 3 && userInput == 1)
                return "Win";

            else if (ComputerIn == 1 && userInput == 3)
                return "Lose";

            else if (ComputerIn == 2 && userInput == 1)
                return "Lose";

            else
                return "Lose";
        }

采纳答案by Cruncher

if ((ComputerIn) % 3 + 1 == userInput)
    return "Win";
else if ((userInput) % 3 + 1 == ComputerIn)
    return "Lose"
else
    return "Draw"

If you wrap 3 around to 1 (using %) then the winner is always 1 greater than the loser.

如果您将 3 绕到 1(使用 %),那么赢家总是比输家大 1。

This approach is more natural when you use 0-2, in which case we would use (ComputerIn+1)%3. I came up with my answer by subbing ComputerInwith ComputerIn-1and UserInputwith UserInput-1and simplifying the expression.

当您使用 0-2 时,这种方法更自然,在这种情况下,我们将使用(ComputerIn+1)%3. 我通过底涂来到了我的回答ComputerInComputerIn-1,并UserInputUserInput-1和简化的表达。

Edit, looking at this question after a long time. As written, if the ComputerInis not used anywhere else, and is only used to determine win/lose/draw, then this method is actually equivalent to:

编辑,在很长一段时间后看这个问题。如所写,如果ComputerIn没有在其他任何地方使用,并且仅用于确定赢/输/平局,那么此方法实际上等效于:

if (ComputerIn == 1)
    return "Win";
else if (ComputerIn == 2)
    return "Lose"
else
    return "Draw"

This can even be further simplified to

这甚至可以进一步简化为

return new String[]{"Win", "Lose", "Draw"}[ComputerIn-1];

The results from this are entirely indistinguishable. Unless the randomly generated number is exposed to outside of this method. No matter what your input is, there's always 1/3 chance of all possibilities. That is, what you're asking for, is just a complicated way of returning "Win", "Lose", or "Draw" with equal probability.

由此产生的结果是完全无法区分的。除非随机生成的数字暴露在这个方法之外。无论您的输入是什么,所有可能性总是有 1/3 的机会。也就是说,您所要求的只是一种以等概率返回“赢”、“输”或“平”的复杂方式。

回答by kjhf

Here's one of many possible solutions. This will print Win.

这是许多可能的解决方案之一。这将打印 Win。

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      Input userInput = Input.Rock;
      Result result = Play(userInput);
      Console.WriteLine(Enum.GetName(result.GetType(), result));
      Console.ReadKey();
    }

    static Result Play(Input userInput)
    {
      Input computer = Input.Scissors;

      switch (userInput)
      {
        case Input.Paper:
          switch (computer)
          {
            case Input.Paper: return Result.Draw;
            case Input.Rock: return Result.Win;
            case Input.Scissors: return Result.Lose;
            default: throw new Exception("Logic fail.");
          }
        case Input.Rock:
          switch (computer)
          {
            case Input.Paper: return Result.Lose;
            case Input.Rock: return Result.Draw;
            case Input.Scissors: return Result.Win;
            default: throw new Exception("Logic fail.");
          }
        case Input.Scissors:
          switch (computer)
          {
            case Input.Paper: return Result.Win;
            case Input.Rock: return Result.Lose;
            case Input.Scissors: return Result.Draw;
            default: throw new Exception("Logic fail.");
          }
        default: throw new Exception("Logic fail.");
      }
    }
  }
  enum Input
  {
    Rock,
    Paper,
    Scissors
  }
  enum Result
  {
    Lose,
    Draw,
    Win
  }
}

回答by Ahmed KRAIEM

This is how I would do it:

这就是我将如何做到的:

public class Program
{

    public enum RPSPlay { Rock, Scissors, Paper }
    public enum RPSPlayResult { Win, Draw, Loose }

    public static readonly int SIZE = Enum.GetValues(typeof(RPSPlay)).Length;

    static RPSPlayResult Beats(RPSPlay play, RPSPlay otherPlay)
    {
        if (play == otherPlay) return RPSPlayResult.Draw;
        return ((int)play + 1) % SIZE == (int)otherPlay 
            ? RPSPlayResult.Win 
            : RPSPlayResult.Loose;
    }

    static void Main(string[] args)
    {
        Random rand = new Random();
        while (true)
        {
            Console.Write("Your play ({0}) (q to exit) : ", string.Join(",", Enum.GetNames(typeof(RPSPlay))));
            var line = Console.ReadLine();
            if (line.Equals("q", StringComparison.OrdinalIgnoreCase))
                return;
            RPSPlay play;
            if (!Enum.TryParse(line, true, out play))
            {
                Console.WriteLine("Invalid Input");
                continue;
            }
            RPSPlay computerPlay = (RPSPlay)rand.Next(SIZE);
            Console.WriteLine("Computer Played {0}", computerPlay);
            Console.WriteLine(Beats(play, computerPlay));
            Console.WriteLine();
        }
    }
}

回答by Philip Sheard

I would prefer to use a static 3x3 matrix to store the possible outcomes. But it is a question of taste, and I am a mathematician.

我更喜欢使用静态 3x3 矩阵来存储可能的结果。但这是一个品味问题,而我是一名数学家。

回答by Nine

Here is one-liner that we created at lunchtime.

这是我们在午餐时间创建的单线。

using System;

public class Rps {
  public enum PlayerChoice { Rock, Paper, Scissors };
  public enum Result { Draw, FirstWin, FirstLose};

  public static Result Match(PlayerChoice player1, PlayerChoice player2) {
    return (Result)((player1 - player2 + 3) % 3);
  }

  public static void Main() {
    Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Rock), Result.Draw);
    Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Paper), Result.Draw);
    Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Scissors), Result.Draw);

    Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Scissors), Result.FirstWin);
    Rps.Test(Match(PlayerChoice.Rock, PlayerChoice.Paper), Result.FirstLose);

    Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Rock), Result.FirstWin);
    Rps.Test(Match(PlayerChoice.Paper, PlayerChoice.Scissors), Result.FirstLose);

    Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Paper), Result.FirstWin);
    Rps.Test(Match(PlayerChoice.Scissors, PlayerChoice.Rock), Result.FirstLose);
  }

  public static void Test(Result sample, Result origin) {
    Console.WriteLine(sample == origin);
  }      
}

回答by Eric Mwenda

\From A java beginner Perspective. User plays with the computer to infinity.

\从Java初学者的角度来看。用户玩电脑到无限。

import java.util.Scanner;

public class AlgorithmDevelopmentRockPaperScissors{
    public static void main(String[] args){

        System.out.println("\n\nHello Eric today we are going to play a game.");
        System.out.println("Its called Rock Paper Scissors.");
        System.out.println("All you have to do is input the following");
        System.out.println("\n  1 For Rock");
        System.out.println("\n        2 For Paper");
        System.out.println("\n        3 For Scissors");

        int loop;
        loop = 0;

        while (loop == 0){
            System.out.println("\n\nWhat do you choose ?");


        int userInput;
        Scanner input = new Scanner(System.in);
        userInput = input.nextInt();

        while (userInput > 3 || userInput <= 0 ){ //ensure that the number input by the sure is within range 1-3. if else the loop trap.

            System.out.println("Your choice "+userInput+" is not among the choices that are given. Please enter again.");
            userInput = input.nextInt();
        }



        switch (userInput){
            case 1:
            System.out.println("You Chose Rock.");
            break;

            case 2:
            System.out.println("You Chose Paper.");
            break;

            case 3:
            System.out.println("You Chose Scissors");
            break;

            default:
            System.out.println("Please Choose either of the choices given");
            break;

        }



        int compInput;
        compInput = (int)(3*Math.random()+1);

        switch (compInput){
            case 1:
            System.out.println("\nComputer Chooses Rock.");
            break;

            case 2:
            System.out.println("\nComputer Chooses Paper.");
            break;

            case 3:
            System.out.println("\nComputer Chooses Scissors");
            break;

        }

        if (userInput == compInput){

            System.out.println(".........................................");
            System.out.println("\nYou Both chose the same thing, the game ends DRAW.");
            System.out.println(".........................................");
        }

        if (userInput == 1 && compInput == 2){

            System.out.println(".........................................");
            System.out.println("\nComputer wins because Paper wraps rock.");
            System.out.println(".........................................");
        }

        if (userInput == 1 && compInput == 3){

            System.out.println(".........................................");
            System.out.println("\nYou win because Rock breaks Scissors.");
            System.out.println(".........................................");
        }

        if (userInput == 2 && compInput == 1){

            System.out.println(".........................................");
            System.out.println("\nYou win Because Paper wraps Rock");
            System.out.println(".........................................");
        }

        if (userInput == 2 && compInput == 3){

            System.out.println(".........................................");
            System.out.println("\nComputer wins because Scissors cut the paper");
            System.out.println(".........................................");
        }

        if (userInput == 3 && compInput == 1){

            System.out.println(".........................................");
            System.out.println("\nComputer Wins because Rock Breaks Scissors.");
            System.out.println(".........................................");
        }

        if (userInput == 3 && compInput == 2){

            System.out.println(".........................................");
            System.out.println("\nYou win because scissors cut the paper");
            System.out.println(".........................................");
        }

        }


    }

}

回答by Obywatel 79

A simple JavaScript implementation using sine wave function to calculate result:

使用正弦波函数计算结果的简单 JavaScript 实现:

<script>
    var tab = ["Lose","Draw","Win"];
    var dict = ["Paper","Stone","Scissors"];
    var i,text = '';
    for (i = 0; i < dict.length; i++) {
        text += i + '-' + dict[i] + ' ';
    }
    var val1 = parseInt(prompt(text));
    var val2 = Math.floor(Math.random() * 3);
    alert('Computer chose: ' + dict[val2]);
    result = Math.sin((val1*180+1) - (val2*180+1));
    alert(tab[Math.round(result)+1]);
</script>

No if's required, just for fun...

没有如果是必需的,只是为了好玩......

Check it

核实