我最近一直在與 Verbs 和 Livewire 合作,並認為嘗試創建一些我喜歡玩的紙牌遊戲是一個有趣的實驗。
為了促進這一點,我需要定義一副卡片,我可以在之後從事的任何專案中使用它。
一副牌需要包含 Card、Deck 和 CardCollection 類別。一張牌應有花色和數值,一副牌應由 52 張牌組成。因為花色和數值都是為一副牌定義的,所以我可以使用枚舉來表示牌的屬性。
CardCollection 類別允許我以 Verbs 狀態安全地儲存卡片集合。
<?php // Cards/Enums/Suit.php declare(strict_types=1); namespace Cards\Enums; enum Suit: string { case Clubs = 'Clubs'; case Diamonds = 'Diamonds'; case Hearts = 'Hearts'; case Spades = 'Spades'; }
<?php // Cards/Enums/Value.php declare(strict_types=1); namespace Cards\Enums; enum Value: string { case Two = 'Two'; case Three = 'Three'; case Four = 'Four'; case Five = 'Five'; case Six = 'Six'; case Seven = 'Seven'; case Eight = 'Eight'; case Nine = 'Nine'; case Ten = 'Ten'; case Jack = 'Jack'; case Queen = 'Queen'; case King = 'King'; case Ace = 'Ace'; }
<?php // Cards/Card.php declare(strict_types=1); namespace Cards; use Cards\Enums\Suit; use Cards\Enums\Value; final readonly class Card { public function __construct( public Suit $suit, public Value $value, ) {} }
<?php // Cards/CardCollection.php declare(strict_types=1); namespace Cards; use Illuminate\Support\Collection; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Thunk\Verbs\SerializedByVerbs; class CardCollection extends Collection implements SerializedByVerbs { public static function deserializeForVerbs(mixed $data, DenormalizerInterface $denormalizer): static { return static::make($data) ->map(fn($serialized) => Card::deserializeForVerbs($serialized, $denormalizer)); } public function serializeForVerbs(NormalizerInterface $normalizer): string|array { return $this->map(fn(Card $card) => $card->serializeForVerbs($normalizer))->toJson(); } }
<?php // Cards/Deck.php declare(strict_types=1); namespace Cards; use Cards\Enums\Suit; use Cards\Enums\Value; final class Deck { public CardCollection $cards; public function __construct() { $this->cards = CardCollection::make([]); collect(CardSuit::cases()) ->each(function (CardSuit $suit): void { collect(CardValue::cases()) ->each(function (CardValue $value) use ($suit): void { $this->cards->push(new Card($suit, $value)); }); }); $this->shuffle(); } public function shuffle(): void { $this->cards = $this->cards ->shuffle() ->reverse(); } public function deal(): ?Card { if (0 === $this->cards->count()) { return null; } return $this->cards->pop(); } public function remainingCards(): int { return $this->cards->count(); } }
以上是一副紙牌的詳細內容。更多資訊請關注PHP中文網其他相關文章!