61 lines
1.4 KiB
C#
61 lines
1.4 KiB
C#
using OECS;
|
|
|
|
namespace Game.Blackjack;
|
|
|
|
/// <summary>
|
|
/// Helper to calculate the blackjack value of a hand.
|
|
/// Aces count as 11 unless that would bust, then they count as 1.
|
|
/// </summary>
|
|
public static class HandUtil
|
|
{
|
|
public static int CalculateHand(World world, DealerHand hand)
|
|
{
|
|
return CalculateHandImpl(world, hand);
|
|
}
|
|
|
|
public static int CalculateHand(World world, PlayerHand hand)
|
|
{
|
|
return CalculateHandImpl(world, hand);
|
|
}
|
|
|
|
private static int CalculateHandImpl<T>(World world, T handTag)
|
|
where T : struct
|
|
{
|
|
// Find the hand entity.
|
|
var handEntity = world.FindEntity<T>();
|
|
|
|
if (handEntity == Entity.Null)
|
|
return 0;
|
|
|
|
var cards = world.GetSources<Holds>(handEntity);
|
|
int total = 0;
|
|
int aceCount = 0;
|
|
|
|
foreach (var cardEntity in cards)
|
|
{
|
|
var card = world.ReadComponent<Card>(cardEntity);
|
|
int value = card.Rank switch
|
|
{
|
|
Rank.Ace => 11,
|
|
Rank.Jack => 10,
|
|
Rank.Queen => 10,
|
|
Rank.King => 10,
|
|
_ => (int)card.Rank
|
|
};
|
|
|
|
if (card.Rank == Rank.Ace)
|
|
aceCount++;
|
|
|
|
total += value;
|
|
}
|
|
|
|
// Downgrade aces from 11 to 1 as needed.
|
|
while (total > 21 && aceCount > 0)
|
|
{
|
|
total -= 10;
|
|
aceCount--;
|
|
}
|
|
|
|
return total;
|
|
}
|
|
} |