【发布时间】:2021-02-07 14:59:42
【问题描述】:
我正在尝试编写一个具有以下功能的程序:
一个创建一副纸牌的函数,默认为 52 张,或在提供花色时仅为 13 张。
与
从卡组中删除第一张 card_count 卡的函数,将它们作为列表返回,并在卡用完时返回适当的错误。
预期结果如下。
>>> deck2 = Deck('♠')
>>> deck2.shuffle_deck()
>>> print(deck2.cards)
[A of ♠, 10 of ♠, 3 of ♠, 7 of ♠, 5 of ♠, 4 of ♠, 8 of ♠, J of ♠, 9 of ♠, Q of ♠, 6 of ♠, 2 of ♠, K of ♠]
>>> deck2.deal_card(7)
[A of ♠, 10 of ♠, 3 of ♠, 7 of ♠, 5 of ♠, 4 of ♠, 8 of ♠]
>>> deck2.deal_card(7)
Cannot deal 7 cards. The deck only has 6 cards left!
我的问题是每次运行代码时都会返回一个空列表。我想我已经正确设置了第一类(PlayingCard)和西装的可选参数。但是,我不太确定如何实现交易功能或为什么我的列表返回空。我错过了什么小东西吗?
import random
class PlayingCard():
def __init__(self, rank, suit):
acc_suit = ("♠", "♥", "♦", "♣")
acc_rank = (2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A")
assert rank in acc_rank, "Not a valid rank for a playing card."
assert suit in acc_suit, "Not a valid suit for a playing card."
self.suit = suit
self.rank = rank
def __repr__(self):
return self.rank + ' of ' + self.suit
class Deck():
def __init__(self, *suit):
acc_suit = ("♠", "♥", "♦", "♣")
self.cards = []
if suit == None:
for suit in range(4):
for rank in range (1,14):
card = PlayingCard(rank, suit)
self.cards.append(card)
if suit in acc_suit:
for rank in range (1,14):
card = PlayingCard(rank, suit)
self.cards.append(card)
def shuffle_deck(self):
random.shuffle(self.cards)
def deal_card(self):
return self.cards.pop(0)
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
【问题讨论】:
标签: python-3.x string class oop playing-cards