我正在尝试开始正确使用对象,我已经构建了一副纸牌,这就是我的对象。我希望能够从中洗牌和发牌。但是,我不知道如何让 shuffle 方法正常工作,或者即使这是最好的方法。
import itertools
import random
class Deck:
'''Deck of cards to be used in a card game'''
def __init__(self):
self.faces = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4','3', '2']
self.suits = ['c', 'd', 'h', 's']
self.cards = set(itertools.product(self.faces, self.suits))
def shuffle(self):
self.cards = random.shuffle(self.cards)
def deal(self):
card = self.cards.pop()
return card[0] + card[1]
使用;
deck = Deck()
deck.shuffle()
deck.deal()
最佳答案
集合
没有排序,您可以使用list()
来获取有序的牌组。
此外,random.shuffle(l)
直接作用于列表并返回 None
,因此您将用 None
覆盖列表。
import itertools
import random
class Deck:
'''Deck of cards to be used in a card game'''
def __init__(self):
self.faces = ['A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4','3', '2']
self.suits = ['c', 'd', 'h', 's']
self.cards = list(itertools.product(self.faces, self.suits)) # ordered deck
# self.cards = set(itertools.product(self.faces, self.suits)) # unordered deck
def shuffle(self):
random.shuffle(self.cards)
def deal(self):
card = self.cards.pop()
return card[0] + card[1]
关于类中的 Python 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55164847/