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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| import collections from random import choice
""" # 先挖个坑在这里挨个来吧 * namedtuple factory function for creating tuple subclasses with named fields * deque list-like container with fast appends and pops on either end * ChainMap dict-like class for creating a single view of multiple mappings * Counter dict subclass for counting hashable objects * OrderedDict dict subclass that remembers the order entries were added * defaultdict dict subclass that calls a factory function to supply missing values * UserDict wrapper around dictionary objects for easier dict subclassing * UserList wrapper around list objects for easier list subclassing * UserString wrapper around string objects for easier string subclassing """
Card = collections.namedtuple('Card', ['rank', 'suit']) c = Card("7", "diamonds") print("方块七的分值:{}, 方块七的花色:{}".format(c.rank, c.suit))
class FrenchDeck: """别在意这个名字的含义。。。。""" ranks = [str(n) for n in range(2, 11)] + list('JQKA') suits = 'spades diamonds clubs hearts'.split()
def __init__(self): """初始化我们的纸牌""" Card = collections.namedtuple('Card', ['rank', 'suit']) self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]
def __len__(self): """返回纸牌的数量""" return len(self._cards)
def __getitem__(self, position): """给出位置,返回纸牌 example: c = FrenchDeck() print(c[51]) """ return self._cards[position]
def pick(self): """选随机牌""" return choice(self)
@staticmethod def spades_high(card): """返回牌的分值""" suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0) rank_value = FrenchDeck.ranks.index(card.rank) return rank_value * len(suit_values) + suit_values[card.suit]
if __name__ == "__main__": c = FrenchDeck().pick() mark = FrenchDeck.spades_high(c) print("随机抽牌为:{},{}, 分值为:{}".format(c.suit, c.rank, mark)) print(f"随机抽牌为:{c.suit},{c.rank}, 分值为:{mark}")
|