This commit is contained in:
2025-09-23 11:11:47 +08:00
parent 674a7b16b7
commit 45f86ba95e
11 changed files with 121 additions and 377 deletions

View File

@@ -1,7 +1,4 @@
"""
Card module for poker game
"""
from functools import total_ordering
from enum import Enum
from typing import List, Tuple, Optional
@@ -15,7 +12,6 @@ class Suit(Enum):
def __str__(self):
return self.value
class Rank(Enum):
TWO = (2, '2')
THREE = (3, '3')
@@ -41,12 +37,21 @@ class Rank(Enum):
def __str__(self):
return self.symbol
def __eq__(self, other):
if isinstance(other, Rank):
return self.numeric_value == other.numeric_value
return NotImplemented
def __lt__(self, other):
if not isinstance(other, Rank):
return NotImplemented
return self.numeric_value < other.numeric_value
if isinstance(other, Rank):
return self.numeric_value < other.numeric_value
return NotImplemented
def __hash__(self):
return hash(self.numeric_value)
@total_ordering
class Card:
def __init__(self, rank: Rank, suit: Suit):
self.rank = rank
@@ -55,22 +60,20 @@ class Card:
def __str__(self):
return f"{self.rank}{self.suit}"
def __eq__(self, other):
if not isinstance(other, Card):
return False
return self.rank == other.rank and self.suit == other.suit
if isinstance(other, Card):
return self.rank == other.rank and self.suit == other.suit
return NotImplemented
def __lt__(self, other):
if not isinstance(other, Card):
return NotImplemented
return self.rank.numeric_value < other.rank.numeric_value
if isinstance(other, Card):
if self.rank != other.rank:
return self.rank < other.rank
return self.suit.value < other.suit.value
return NotImplemented
@classmethod
def create_card(cls, card_str: str) -> 'Card':
"""
从字符串创建Card对象例如 "As", "Kh", "2c"
"""
def createCard(cls, card_str) -> 'Card':
if len(card_str) != 2:
raise ValueError(f"Invalid card string: {card_str}")
@@ -100,9 +103,9 @@ class Card:
return cls(rank, suit)
@classmethod
def parse_cards(cls, cards_str: str) -> List['Card']:
def parseCards(cls, cards_str) -> List['Card']:
"""
从字符串解多张牌,例如 "AsKs AhAdAc6s7s"
从字符串解多张牌, "AsKs AhAdAc6s7s"
"""
cards_str = cards_str.strip()
if not cards_str:
@@ -122,8 +125,4 @@ class Card:
i += 2
else:
raise ValueError(f"Invalid card format at position {i}")
result = []
for card_str in card_strings:
card_tmp = cls.create_card(card_str)
result.append(card_tmp)
return result
return [cls.createCard(card_str) for card_str in card_strings]