Im struggling with figuring out how to calculate the Ace value sometimes its 1 sometimes its 11. Once the deal button is clicked the player is dealt 2 cards (card1Value card2Value) these 2 cards are added together and becomes the playersHand. Now if one of these 2 cards is an Ace Im confused with how to give the option for it to be 1 or 11?
1 is the value of the Ace
if(card1Value !=1 card2Value !=1)
{
playersHand += card1Value += card2Value;
}
//if players first or second card is an ace
if(card1Value == 1 || card2Value == 1)
{
//if 1st card = 1 2nd card 10 OR 1st card = 10 2nd card = 1 YOU WIN
if(card1Value == 1 card2Value == 10 || card1Value == 10 card2Value == 1)
{
Win();
}
//if one of the cards is an ace and the other is not
if(card1Value == 1 card2Value != 1 || card1Value != 1 card2Value == 1)
{
optionLow += card1Value += card2Value;
optionHigh += card1Value += card2Value + 9;
}
}
Now I can let the user choose optionLow (ace =1) or optionHigh(ace =11). Needs more testing so Im on it, thank you all
Always assume that the Ace is 11. When you calculate the sum, check how many cards are an Ace and save the number of Aces.
If the sum exceeds 21 and one of the cards is an Ace, subtract 10. If it’s still over 21 and you have still once ace available, subtract another 10.
public enum CardType {
Two = 2, // tell it that the first value is a two
Three,
...,
Ten,
Ace, // 11
...,
King // 14
}
public struct Card {
public int Value;
public CardType Type;
public Card(CardType type) {
Type = type;
int value = (int)type;
Value = (value>11)?10:value; // for all values higher than 11 (picture cards) assign 10
}
}
// C# and Linq
List<Card> cards = new List<Card>();
cards.Add(new Card(CardType.Ace));
cards.Add(new Card(CardType.Ace));
cards.Add(new Card(CardType.King));
// Get the number of Aces
int numAces = cards.Where(card => card.Type == CardType.Ace).Count();
// Get the sum, i.e. 32 in this case
int sum = cards.Sum(card => card.Value);
// Before Loop: Sum 32, numAces = 2
// 1st Loop: Sum 22, numAces = 1
// 2nd Loop: Sum 12, numAces = 0
while(sum > 21 numAces > 0) {
numAce--;
sum -= 10;
}
if(sum <=21 ) {
Win()
} else {
Lose();
}