Algorithm for scissor paper stone

前端 未结 8 614
日久生厌
日久生厌 2021-02-06 20:03

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

8条回答
  •  无人共我
    2021-02-06 20:44

    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();
            }
        }
    }
    

提交回复
热议问题