Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/Domain/Hand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace App\Domain;

final class Hand
{
public function __construct(
private array $cards = []
) {}

public function addCard(Card $card): void
{
$this->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;
}
}
73 changes: 73 additions & 0 deletions tests/Domain/HandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace App\Tests\Domain;

use App\Domain\Card;
use App\Domain\Hand;
use PHPUnit\Framework\TestCase;

final class HandTest extends TestCase
{
public function testEmptyHandHasValueOfZero(): void
{
$hand = new Hand();

$this->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());
}
}
Loading