在Python中定义类

时间:2014-11-01 21:17:39

标签: python

创建一个代表一副牌的类Deck。您的班级应该有以下方法:

  • 构造函数:按标准顺序创建一个包含52张卡片的新套牌。
  • shuffle:随机化卡片的顺序。
  • dealCard:从牌组顶部返回一张牌并从牌组中取出牌
  • cardsLeft:返回牌组中剩余的牌数。

测试你的程序,让它从一个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)

1 个答案:

答案 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)]