1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Card; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Class CardHand represents a hand of cards. |
7
|
|
|
*/ |
8
|
|
|
class CardHand |
9
|
|
|
{ |
10
|
|
|
/** @var Card[] */ |
11
|
|
|
private array $cards = []; |
12
|
|
|
|
13
|
21 |
|
public function addCard(Card $card): void |
14
|
|
|
{ |
15
|
21 |
|
$this->cards[] = $card; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @return Card[] |
20
|
|
|
*/ |
21
|
8 |
|
public function getCards(): array |
22
|
|
|
{ |
23
|
8 |
|
return $this->cards; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Get total points of the hand. |
28
|
|
|
* Handle the Aces. |
29
|
|
|
* @return int |
30
|
|
|
*/ |
31
|
8 |
|
public function getTotal(): int |
32
|
|
|
{ |
33
|
8 |
|
$sum = 0; |
34
|
8 |
|
$aces = []; |
35
|
|
|
|
36
|
8 |
|
foreach ($this->cards as $card) { |
37
|
4 |
|
if ($card->getValue() === 'Ace') { |
38
|
3 |
|
$aces[] = $card; |
39
|
3 |
|
continue; |
40
|
|
|
} |
41
|
2 |
|
$sum += $card->getNumericValue(); |
42
|
|
|
} |
43
|
8 |
|
$numAces = count($aces); |
44
|
|
|
|
45
|
8 |
|
if ($numAces === 2) { |
46
|
|
|
// If 2 Aces — one counts as 14, one as 1 |
47
|
1 |
|
$sum += 14 + 1; |
48
|
7 |
|
} elseif ($numAces === 1) { |
49
|
|
|
// One Ace — check the current sum |
50
|
1 |
|
$sum += ($sum + 14 <= 21) ? 14 : 1; |
51
|
6 |
|
} elseif ($numAces > 2) { |
52
|
|
|
// More than 2 Aces — treat one as 14, one as 1, rest as 1 |
53
|
1 |
|
$sum += 14 + 1 + ($numAces - 2) * 1; |
54
|
|
|
} |
55
|
8 |
|
return $sum; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Calculate total points of the hand for black jack game. |
60
|
|
|
* Handle the Aces. |
61
|
|
|
* @return int |
62
|
|
|
*/ |
63
|
8 |
|
public function getTotalBlackJack(): int |
64
|
|
|
{ |
65
|
8 |
|
$sum = 0; |
66
|
8 |
|
$aces = 0; |
67
|
|
|
|
68
|
8 |
|
foreach ($this->cards as $card) { |
69
|
8 |
|
if ($card->getValue() === 'Ace') { |
70
|
3 |
|
$aces++; |
71
|
3 |
|
continue; |
72
|
|
|
} |
73
|
8 |
|
$sum += $card->getBlackJackNumericValue(); |
74
|
|
|
} |
75
|
|
|
|
76
|
8 |
|
for ($i = 0; $i < $aces; $i++) { |
77
|
3 |
|
$sum += 11; |
78
|
3 |
|
if ($sum > 21) { |
79
|
1 |
|
$sum -= 10; |
80
|
|
|
} |
81
|
|
|
} |
82
|
8 |
|
return $sum; |
83
|
|
|
} |
84
|
|
|
|
85
|
1 |
|
public function getNrOfCards(): int |
86
|
|
|
{ |
87
|
1 |
|
return count($this->cards); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* Convert the hand to an array. |
92
|
|
|
* |
93
|
|
|
* @return array<int, array<string, string>> |
94
|
|
|
*/ |
95
|
2 |
|
public function toArray(): array |
96
|
|
|
{ |
97
|
2 |
|
$array = []; |
98
|
2 |
|
foreach ($this->cards as $card) { |
99
|
1 |
|
$array[] = $card->toArray(); |
100
|
|
|
} |
101
|
2 |
|
return $array; |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|