0

I am creating a small application based on code contracts, is there a way to write a specification, which would kinda work in rock, paper, scissors way? I'd like to make a specification, which would follow something like this:

0- rock
1- paper
2- scissors 

so if you get 0 and 1- 1 wins, if you get 1 and 2- 2 wins and if you get 0 2, 0 wins. I would like to write a specification for a method which would specify this case, is it possible to do so?

  • Show us what you have tried. – Jeroen Heier Oct 10 '18 at 15:40
  • What do you mean "Code Contracts"? Code contracts aren't exactly specifications. They have to be validated by an analyzer or the compiler, otherwise they are nothing more than runtime guard clauses. You could write a complex `Ensures` that specified which value would be returned for which input, but the analyzer wouldn't be able to validate it. – Panagiotis Kanavos Oct 10 '18 at 15:44

2 Answers2

1

I'd do something similar to object.CompareTo() and do some modulo. The next in the circle is always winning, so add 1 to the hand and check the Rest of the division by 3 to project it back to our 3 options.

Compare it with the second hand. If it is equal: First hand loses, otherwhise second hand loses.

public int CompareHands(int hand1, int hand2)
{
   if (hand1 == hand2) return 0; //tie
   return ((hand1 + 1) % 3) == hand2 ? -1 : 1; //we have a winner
}
Andreas
  • 828
  • 4
  • 15
0

Instead of doing the arithmetic (comparing the value), it is probably better to use the domain logic (game rules):

public enum Hand
{
    Rock,
    Paper,
    Scissors,
}

public static Hand? Check(Hand h1, Hand h2)
{
    // same hand draw
    if (h1 == h2) return default;

    var winningHands = new Dictionary<Hand, Hand>
    {
        [Hand.Rock] = Hand.Paper,
        [Hand.Paper] = Hand.Scissors,
        [Hand.Scissors] = Hand.Rock,
    };
    return h2 == winningHands[h1] ? h2 : h1;
}
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44