diff --git a/src/Domain/Hand.php b/src/Domain/Hand.php new file mode 100644 index 0000000..2177526 --- /dev/null +++ b/src/Domain/Hand.php @@ -0,0 +1,60 @@ +cards[] = $card; + } + + public function value(): int + { + $total = 0; + $aces = 0; + + foreach ($this->cards as $card) { + $total += $card->numericValue(); + if ($card->rank() === 'Ace') { + $aces++; + } + } + + while ($total > 21 && $aces > 0) { + $total -= 10; + $aces--; + } + + return $total; + } + + public function isBlackjack(): bool + { + return count($this->cards) === 2 && $this->value() === 21; + } + + public function isBust(): bool + { + return $this->value() > 21; + } + + public function isSoft(): bool + { + $total = 0; + $aces = 0; + + foreach ($this->cards as $card) { + $total += $card->numericValue(); + if ($card->rank() === 'Ace') { + $aces++; + } + } + + return $aces > 0 && $total <= 21; + } +} diff --git a/tests/Domain/HandTest.php b/tests/Domain/HandTest.php new file mode 100644 index 0000000..146f465 --- /dev/null +++ b/tests/Domain/HandTest.php @@ -0,0 +1,73 @@ +assertSame(0, $hand->value()); + } + + public function testHandWithOneCardReturnsCardValue(): void + { + $hand = new Hand(); + $hand->addCard(new Card('7', 'Hearts')); + + $this->assertSame(7, $hand->value()); + } + + public function testAceCountsAsOneWhenHandWouldBust(): void + { + $hand = new Hand(); + $hand->addCard(new Card('Ace', 'Hearts')); + $hand->addCard(new Card('King', 'Spades')); + $hand->addCard(new Card('5', 'Diamonds')); + + $this->assertSame(16, $hand->value()); + } + + public function testNaturalBlackjackWithAceAndKing(): void + { + $hand = new Hand(); + $hand->addCard(new Card('Ace', 'Hearts')); + $hand->addCard(new Card('King', 'Spades')); + + $this->assertTrue($hand->isBlackjack()); + } + + public function testThreeCardTwentyOneIsNotBlackjack(): void + { + $hand = new Hand(); + $hand->addCard(new Card('7', 'Hearts')); + $hand->addCard(new Card('7', 'Spades')); + $hand->addCard(new Card('7', 'Diamonds')); + + $this->assertFalse($hand->isBlackjack()); + } + + public function testHandIsBustWhenValueExceeds21(): void + { + $hand = new Hand(); + $hand->addCard(new Card('King', 'Hearts')); + $hand->addCard(new Card('Queen', 'Spades')); + $hand->addCard(new Card('5', 'Diamonds')); + + $this->assertTrue($hand->isBust()); + } + + public function testHandWithAceCountedAs11IsSoft(): void + { + $hand = new Hand(); + $hand->addCard(new Card('Ace', 'Hearts')); + $hand->addCard(new Card('6', 'Spades')); + + $this->assertTrue($hand->isSoft()); + } +}