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