创建一个扑克牌类Python

时间:2017-03-15 04:24:15

标签: python class attributes comparison

我创建了一个具有等级,套件和二十一点值属性的扑克牌对象。

二十一点值部分持续获得一个TypeError,表示我无法在listint的实例之间进行比较。我不知道如何解决(如何/如果我只能比较列表的索引,然后根据其索引给它二十一点值)?

if / elif块是属于bjValue()函数还是属于 init ()函数?

这是我的代码:

class Card:

    """playing card object where numeric rank, suit and blackjack values are stored"""

    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit
        self.ranks = [None, "Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
       self.suits = {"d": "Diamonds",
                   "c": "Clubs",
                   "h": "Hearts",
                   "s": "Spades"}




    def getRank(self):
        """returns the rank of the card"""
        return self.rank

    def getSuit(self):

        return self.suits.get(self.suit)

    def bjValue(self):

        if self.rank > 1 or self.rank < 11:
            self.value = self.rank

        elif self.rank == "Ace":
            self.value = 1

        elif self.rank == "Jack" or self.ranks == "Queen" or self.ranks == "King":
            self.value = 10


        return self.value


    def __str__(self):

        return "%s of %s" % (self.ranks[self.rank], self.suits.get(self.suit))





c1 = Card(1,"s")
c2 = Card(11,"d")
print(c1) #expect Ace of Spades
print(c2) #expect Jack of Diamonds

c3 = Card(5,"c") #expect 5 of clubs
print(c3.getRank())
print(c3.getSuit()) #expect Five
print(c3.bjValue()) #expect 5
print(c3)

c4 = Card(1,"s")
print(c4)

编辑:所以,我修正了我的拼写错误,我没有得到任何错误,但我仍然得到杰克,女王和国王卡的不正确的二十一点价值(我得到他们的二十一点值作为他们的排名,即使我有if语句)我不明白我逻辑中的缺陷在哪里......

1 个答案:

答案 0 :(得分:0)

因为你是初学者。让我们考虑一下它给你的错误:

    if self.ranks > 1 or self.ranks < 11:
TypeError: '>' not supported between instances of 'list' and 'int'

您的bjValue函数中存在拼写错误:

if self.ranks > 1 or self.ranks < 11:
    self.value = self.ranks

您要与ranks列表进行比较,而不是实际(当前)rank值。

你的意思可能是:

if self.rank > 1 or self.rank < 11:
    self.value = self.ranks[self.rank]

修改

根据你的评论,我怀疑你想要的是这样的。

class Card:
    def __init__(self, rank, suit):
        self.ranks = [None, "Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
        self.rank = self.ranks[rank]
        self.suits = {"d": "Diamonds", "c": "Clubs", "h": "Hearts", "s": "Spades"}
        self.suit = self.suits[suit]
        self.value = -1

    def getRank(self):
        return self.rank

    def getSuit(self):
        return self.suit

    def bjValue(self):
        if self.rank == "Ace":
            self.value = 1
        elif self.rank == "Jack" or self.rank == "Queen" or self.rank == "King":
            self.value = 10
        elif type(self.rank) is int:
            if self.rank > 1 and self.rank < 11:
                self.value = self.ranks[self.rank]
        return self.value

除非您希望能够更改任何已创建的卡片的等级或套装,否则我建议将bjValue中的if语句移至__init__ < / p>