纸牌游戏
import json from collections import namedtuple """ Tuple还有一个兄弟,叫namedtuple。虽然都是tuple,但是功能更为强大。 对于namedtuple,你不必再通过索引值进行访问,你可以把它看做一个字典 通过名字进行访问,只不过其中的值是不能改变的。 """ Card = namedtuple("Card", ["rank", "suit"]) # rank 是牌面大小,suit是花色 class FranchDeck: ranks = [str(n) for n in range(2, 11)] + list("JQKA") # 牌面大小 suits = ["红心", "黑桃", "方片", "梅花"] def __init__(self): self.__cards = [Card(rank, suit) for rank in FranchDeck.ranks for suit in FranchDeck.suits] # 循环嵌套,获取数字,花色 def __len__(self): return len(self.__cards) def __getitem__(self, item): return self.__cards[item] def __setitem__(self, key, value): self.__cards[key] = value def __str__(self): return json.dumps(self._cards, ensure_ascii=False) deck = FranchDeck() print(deck[10]) # 获取牌 # 洗牌 from random import choice print(choice(deck)) print(choice(deck)) # 切片 from random import shuffle shuffle(deck) print(deck[10]) print(deck[:5])