创建一个代表一副牌的类Deck
。您的班级应该有以下方法:
测试你的程序,让它从一个shuffle deck中处理一系列n
卡,其中n
是用户输入。
class Deck:
def __init__(self):
self.cardList=[]
for suit in ["d","c","h","s"]:
for rank in range(1,14):
card=PlayingCard(suit, rank)
self.cardList.append(card)
def shuffle(self):
#I DON'T KNOW HOW TO SHUFFLE MY CARDS PLEASE HELP.
#self.cardList[pos1] = self.cardList[pos2]
#self.cardList[pos2] = self.cardList[pos1]
#these two lines above are not working
def dealCard(self):
return self.cardList.pop()
def cardsLeft(self):
return len(self.cardList)
答案 0 :(得分:1)
阅读random.shuffle
上的文档。它应该对你有很大的帮助! :)
from collections import namedtuple
from random import shuffle
PlayingCard = namedtuple('PlayingCard', "suit rank")
class Deck:
def __init__(self):
self.cardList = [PlayingCard(suit, rank) for suit in"dchs" for rank in range(1,14)]
def shuffle(self):
shuffle(self.cardList)
def dealCard(self):
return self.cardList.pop()
def cardsLeft(self):
return len(self.cardList)
d = Deck()
d.shuffle()
print [d.dealCard() for _ in range(5)]