How can I reduce the lines with the correct toggle case
I am working on a blackjack game project. I have a method helper()
that guides the user through their actions. For example:
dealer's card up: the 8
total amount of the player's hands:16
The player is not sure if he should hit or stay. This is where the function works helper()
.
It mainly counts the number of good cards on the deck ( playerTotal
+ goodcard
<= 21)
So, I'm going to do it this way (pseudocode)
public void helper() {
remain = 21 - playerTotal;
if (remain == 1) {
for (int i = 0; i < deck.last(); i++) {
switch (deck[i]) {
case A: numOfGood += 1
default: numOfBad +=1
}
}
}
else if (remain == 2) {
for (....) {
switch (deck[i]) {
case A: numOfGood += 1
case 2: numOfGood += 1
default: numOfBad +=1
}
}
}
//goes like this
}
I need to build a commutator and loop for all cards (A, 2,3,4,5,6,7,8,9, J, K, Q, K), but this looks like a huge mess. How can I reduce the number of lines by doing something different?
source to share
First, write a method GetValue
that can compute the (minimum) numeric value for the map. You can implement it with switch
or however you want:
public static int GetValue(char card)
{
//...
}
Once you have it, your method implementation becomes much shorter and simpler:
foreach(var card in deck)
if(GetValue(card) <= remain)
numOfGood++;
else
numOfBad++;
Also note that you can simply count the number of good or bad cards and use the total remaining cards to calculate another if needed.
var oddsOfSuccessfulHit = deck.Count(card => GetValue(card) <= remain) /
(double) deck.Count;
source to share
Alternatively, since the logic of the map values โโcannot change, there is no need to encode it - just save it as data.
struct CardEffect
{
public string CardGlyph;
public int MinValue;
public int MaxValue;
}
... load from XML file or some other location and load into ...
public Dictionary<string, CardEffect> cardValues;
Then use the logic suggested by Servy.
source to share