Comparing integers in contracts

62 Views Asked by At

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?

2

There are 2 best solutions below

0
Xiaoy312 On

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;
}
2
Andreas On

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
}