using OECS; namespace Game.Blackjack; /// /// Helper to calculate the blackjack value of a hand. /// Aces count as 11 unless that would bust, then they count as 1. /// 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(World world, T handTag) where T : struct { // Find the hand entity. Entity handEntity = Entity.Null; using (var iter = world.Select()) { while (iter.MoveNext()) { if (iter.CurrentEntity != World.SingletonEntity) { handEntity = iter.CurrentEntity; break; } } } if (handEntity == Entity.Null) return 0; var cards = world.GetSources(handEntity); int total = 0; int aceCount = 0; foreach (var cardEntity in cards) { var card = world.ReadComponent(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; } }