aboutsummaryrefslogtreecommitdiff
path: root/poker/models.py
blob: bbb474cf67d5271decb2f99f8d6f4dd66b9c6197 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from __future__ import annotations

from collections import Counter

from pydantic import BaseModel, validator

from poker.constants import Rank, Suit, Value


class Card(BaseModel):
    """Card domain model class."""

    suit: Suit
    value: Value

    def __hash__(self) -> int:
        """Hash function."""
        return hash(f"{self.value} {self.suit}")

    def __le__(self, other: Card) -> bool:
        """Less than or equal to."""
        return self.value <= other.value

    def __lt__(self, other: Card) -> bool:
        """Strictly less than."""
        return self.value < other.value


class Hand(BaseModel):
    """Hand domain model class."""

    cards: list[Card]

    @validator("cards")
    def validate_unique(cls, cards: list[Card]) -> list[Card]:
        """Validate hand comprises unique cards."""
        if len(cards) != len(set(cards)):
            raise ValueError("Hand contains duplicate cards.")
        return cards

    @validator("cards")
    def validate_length(cls, cards: list[Card]) -> list[Card]:
        """Validate hand has five cards."""
        if len(cards) != 5:
            raise ValueError("Hand must have five cards.")
        return cards

    @property
    def value_counts(self) -> list[tuple[Value, int]]:
        """Return count of each card value in hand."""
        return Counter([card.value for card in self.cards]).most_common()


class RankedHand(Hand):
    """Ranked hand  domain model class."""

    rank: Rank
    description: str