I’m writing a PHP version of Blackjack. I’m having trouble dealing with the aces. I know this is a particular problem when it comes to coding this game. I’ve had a look around at some of the other questions that others have asked, but I can’t find just what I’m looking for.
I think the problem lies in the fact that once the getValue function is called on for a particular card, it doesn’t call on it again for that card. Is there a way to get it to call on the getValue function again if, for example, you hit with an ace and a 7 (which is 8 or 18) and you get a 10 (turning it to 18 or 28). With the game I’ve built it goes bust in that scenario because it doesn’t check the cards again to get the total.
Code is below. I hope it makes sense out of context and I’ve explained the problem well enough.
function getValue($drawn, $total){
$splitter = str_split($drawn);
$value = $splitter[0];
if($value == 'j' or $value == 'q' or $value == 'k' or $value == 1){
$value = 10;
}else if($value == 'a' and (($total + 11) > 21)){
$value = 1;
}else if($value == 'a' and (($total + 11) <= 21)){
$value = 11;
}else{
$value = $value;
}
return $value;
}
function calculateScore($cardsArray){
for($i = 0; $i < count($cardsArray); ++$i){
$total += getValue($cardsArray[$i]);
}
return $total;
}
The need to “know” when you have two total value possibilities based on one common set of cards is a good reason to use OOP here.
You could have a
handclass, to which you dealcards, and if your card isaceyou know that it has two values.Upon receipt of an ace you could either duplicate your hand and run both hands until end, or you could write your
handandcardclasses such that$hand->getTotal()returns an array with all possible totals.This is trivially easy with OOP.