Reputation: 3
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'
Upvotes: 0
Views: 231
Reputation: 1893
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;
}
Upvotes: 0
Reputation: 1982
One of the approaches that I can think of is adding a counter for aces. Effectively, the case A:
would be:
case 'A':
score+=1;
ctrA++;
break;
And outside the switch
:
if(ctrA == 1) //only one ace
score+= 10; //add 10 to make the score for that ace 11.
Upvotes: 1
Reputation: 1111
I would suggest adding more logic in and after your switch case. For example you could use a counter to keep track of how many Aces were in the hand. For example:
public int Score()
{
int score = 0;
int amountOfAces = 0;
foreach (Card c in hand)
{
switch (c.Value)
{
// Count all face cards as 10
case 'A':
amountOfAces++;// increment aces by 1
score += 11;
break;
case 'T':
case 'J':
case 'K':
case 'Q':
score += 10;
break;
default:
score += (c.Value - '0');
break;
}
// Then adjust score if needed
if(amountOfAces>1){
//since we know how many were found.
score = score-amountOfAces*11;
score = score+amountOfAces;
}
}
return score;
}
Upvotes: 0
Reputation: 2620
I would take a separate variable to count the aces and evaluate it at the end. If 1 ace present add 11, else add 1 * numberOfAces.
Add it next to the score, outside of the foreach loop. So the score evaluation at case "A" should be done after the loops is finished and you have the aces count.
Upvotes: 1