一副纸牌
收藏
本篇文章给大家分享《一副纸牌》,覆盖了文章的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

我最近一直在与 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();
}
}
今天关于《一副纸牌》的内容介绍就到此结束,如果有什么疑问或者建议,可以在米云公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
版本声明 本文转载于:dev.to 如有侵犯,请联系 删除
