|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Smr\Blackjack; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* A game of blackjack between the dealer and a player. |
|
7
|
|
|
*/ |
|
8
|
|
|
class Table { |
|
9
|
|
|
|
|
10
|
|
|
private Deck $deck; |
|
11
|
|
|
public Hand $playerHand; |
|
12
|
|
|
public Hand $dealerHand; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(bool $deal = true) { |
|
15
|
|
|
$this->deck = new Deck(); |
|
16
|
|
|
$this->playerHand = new Hand(); |
|
17
|
|
|
$this->dealerHand = new Hand(); |
|
18
|
|
|
|
|
19
|
|
|
if ($deal) { |
|
20
|
|
|
$this->deal(); |
|
21
|
|
|
} |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Deal the initial 4 cards (2 for player, 2 for dealer) |
|
26
|
|
|
*/ |
|
27
|
|
|
public function deal(): void { |
|
28
|
|
|
$this->playerHand->addCard($this->deck->drawCard()); |
|
29
|
|
|
$this->dealerHand->addCard($this->deck->drawCard()); |
|
30
|
|
|
$this->playerHand->addCard($this->deck->drawCard()); |
|
31
|
|
|
$this->dealerHand->addCard($this->deck->drawCard()); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Player draws a card |
|
36
|
|
|
*/ |
|
37
|
|
|
public function playerHits(): void { |
|
38
|
|
|
$this->playerHand->addCard($this->deck->drawCard()); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Dealer draws cards until their hand has a value >= $limit |
|
43
|
|
|
*/ |
|
44
|
|
|
public function dealerHitsUntil(int $limit): void { |
|
45
|
|
|
if ($this->playerHand->getValue() < 21) { |
|
46
|
|
|
while ($this->dealerHand->getValue() < $limit) { |
|
47
|
|
|
$this->dealerHand->addCard($this->deck->drawCard()); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Check if the game is forcibly over (a hand has blackjack or busted) |
|
54
|
|
|
*/ |
|
55
|
|
|
public function gameOver(): bool { |
|
56
|
|
|
return $this->playerHand->getValue() >= 21 || $this->dealerHand->getValue() >= 21; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Get the result of the completed game from the player's perspective |
|
61
|
|
|
*/ |
|
62
|
|
|
public function getPlayerResult(): Result { |
|
63
|
|
|
return match (true) { |
|
64
|
|
|
$this->playerHand->hasBusted() => Result::Lose, |
|
65
|
|
|
$this->playerHand->hasBlackjack() => Result::Blackjack, |
|
66
|
|
|
$this->playerHand->getValue() == $this->dealerHand->getValue() => Result::Tie, |
|
67
|
|
|
$this->playerHand->getValue() > $this->dealerHand->getValue() => Result::Win, |
|
68
|
|
|
$this->dealerHand->hasBusted() => Result::Win, |
|
69
|
|
|
default => Result::Lose, |
|
70
|
|
|
}; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
} |
|
74
|
|
|
|