Search code examples
c#arrayslinqsortingpoker

Poker Hand Analysing


I have run into a bit of trouble on coding a hand analyser for my poker game. As of now i can analyse each players hand and get the desired result (TwoPair,OnePair,HighCard)

But what i want to do now is get the player with the highest ranking cards to win the game

For Example: Player 1 = Two Pair, 
         Player 2 = HighCard,
         Player 3 = One Pair
         Player 4 = Two Pair

Take the players with the highest match (player 1 and player 4)

Player Class

 public class Player :  IPlayer
{

    public Player(string name)
    {
        Name = name;
    }


    public string Name { get;  private set; }
    // Hold max 2 cards
    public Card[] Hand { get; set; }
    public HandResult HandResult { get ; set ; }
}

Hand Result Class

  public class HandResult
{
    public HandResult(IEnumerable<Card> cards, HandRules handRules)
    {
        result = handRules;
        Cards = cards;
    }

    public PokerGame.Domain.Rules.HandRules result { get; set; }

    public IEnumerable<Card> Cards { get; set; }// The cards the provide the result (sortof backlog)
}

Hand Rule Enum

    public enum HandRules 
{ 
    RoyalFlush, StraightFlush, FourOfAKind, FullHouse, Flush, Straight, ThreeOfAKind, TwoPair, OnePair, HighCard 
}

Solution

  • By using linq (using System.Linq;), and assuming you keep the players in a List<Player> collection with the variable name playerList;

    Player[] winners = playerList
        .Where(x => (int)x.HandResult.result == (int)playerList
            .Min(y => y.HandResult.result)
        ).ToArray();
    

    Or, for clarity:

    int bestScore = playerList.Min(x => (int)x.HandResult.result);
    
    Player[] winners = playerList
        .Where(x => (int)x.HandResult.result == bestScore).ToArray();
    

    This will give you the player(s) whose hand score is equal to the maximum score achieved by any of them.

    We are using .Min() here (instead of .Max()) because your enumeration (HandRules) is in reverse order. (enum value at index 0 represents the best hand)

    Please don't forget the kicker though. I don't see support for the kicker card in your implementation.