Search code examples
c#blackjack

How do I value card differently depending on whether there's just one or more than one?


I've been working on this card game for homework and hit a wall.

I'm working in the Score() method trying to value all my cards. I have a foreach loop with a switch.

The issue is the Ace. I want to say if more than 1 Ace, value them all as 1 else 11.

public int Score()
{
    int score = 0;

    foreach (Card c in hand)
    {
        switch (c.Value)
        {
        // Count all face cards as 10
        case 'A':
            score += 1;
            break;
        case 'T':
        case 'J':
        case 'K':
        case 'Q':
            score += 10;
            break;
        default:
            score += (c.Value - '0');
            break;
        }

        //if (score > 21)
        //    switch (c.Value)
        //    {
        //        case 'A':
        //            score += 11;
        //            break;
        //    }
    }
    return score;
}

I commented out a section I was playing around with, but I just can't wrap my head around trying to code the 'if more than one ace, value as 1, else 11'


Solution

  • You may want the Ace to count as 1 in other scenarios other than just "more than one ace". If the user has a Jack, Three, Ace, you want the Ace to count as 1. I would take all cards that aren't Aces and add them up. Then take how many Aces minus 1 and add that count to the total. Finally, check if your total is < 11, you can make the Ace count as 11, otherwise, you have to count it as 1.

    public int Score()
    {
        var score = 0;
        var aceCount = 0;
    
        foreach (Card c in hand)
        {
            switch (c.Value)
            {
                case 'A':
                    aceCount++;
                    break;
                case 'T':
                case 'J':
                case 'K':
                case 'Q':
                    score += 10;
                    break;
                default:
                    score += (c.Value - '0');
                    break;
            }
        }
    
        if(aceCount == 0)
        {
            return score;
        }
    
        //Any ace other than the first will only be worth one point.
        //If there is only one ace, no score will be added here.
        score += (aceCount-1);
    
        //Now add the correct value for the last Ace.
        if(score < 11)
        {
            score += 11;
        }
        else
        {
            score++;
        }
    
        return score;
    }