以Old Maid纸牌游戏为例的课堂继承练习

时间:2018-08-30 05:55:12

标签: python class inheritance

我目前正在学习python中的类继承。在下面的示例中,目标是在包含13张不同的随机卡的单手牌中移除卡对(任何两张具有相同值和颜色的卡,例如3个心形和3个菱形)。 看来错误在第127行:if match in self.cards:。即使match不在self.cards中,该语句也始终返回true。错误为ValueError: list.remove(x): x not in list。任何人都知道如何实现预期目标吗?谢谢。 ps的学习方法:如何像计算机科学家一样思考。

class Card:
    """represents a card found in a standard deck with 52 cards."""
    suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
    ranks = ["narf", "Ace", "2", "3", "4", "5", "6", "7",
             "8", "9", "10", "Jack", "Queen", "King"]

    def __init__(self, suit=0, rank=0):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return (self.ranks[self.rank] + ' of ' + self.suits[self.suit])

    def cmp(self, other):
        if self.suit > other.suit:
            return 1
        if self.suit < other.suit:
            return -1
        if self.rank < other.rank:
            return 1
        if self.rank < other.rank:
            return -1
        return 0

    def __eq__(self, other):
        return self.cmp(other) == 0

    def __le__(self, other):
        return self.cmp(other) <= 0

    def __lt__(self, other):
        return self.cmp(other) < 0

    def __ge__(self, other):
        return self.cmp(other) >= 0

    def __gt__(self, other):
        return self.cmp(other) > 0

    def __ne__(self, other):
        return self.cmp(other) != 0


class Deck:
    """Contains a list of cards as attribute and generates the 52 cards"""
    def __init__(self):
        self.cards = []
        for suit in range(4):
            for rank in range(1, 14):
                self.cards.append(Card(suit, rank))

    def __str__(self):
        s = ""
        for i in range(len(self.cards)):
            s = s + " " * i + str(self.cards[i]) + "\n"
        return s

    def print_deck(self):
        for card in self.cards:
            print(card)

    def shuffle(self):
        """shuffles the deck of cards randomly."""
        import random
        rng = random.Random()
        rng.shuffle(self.cards)

    def remove(self, card):
        """Removes a single specified card from the deck."""
        if card in self.cards:
            self.cards.remove(card)
            return True
        else:
            return False

    def pop(self):
        """Select a single card from the deck"""
        return self.cards.pop()

    def is_empty(self):
        if self.cards == []:
            return True
        return False

    def deal(self, hands, num_cards=52):
        """Deals cards from the deck to a list of hands.
        If number of card to deal is not specified, the entire deck is dealt."""
        for i in range(num_cards):
            if self.cards == []:
                break
            card = self.pop()
            hand = hands[i % len(hands)]
            hand.add(card)


class Hand(Deck):
    def __init__(self, name=''):
        Deck.__init__(self)
        self.cards = []
        self.name = name

    def __str__(self):
        string = "The Hand " + self.name
        if self.is_empty():
            string += 'is empty.\n'
        else:
            string += ' contains:\n'
        return string + Deck.__str__(self)

    def add(self, card):
        self.cards.append(card)


class CardGame:

    def __init__(self):
        self.deck = Deck()
        self.deck.shuffle()

class OldMaidHand(Hand):
    """Creates a hand for a single player to play a game of Old Maid."""

    def remove_matches(self):
        cards = self.cards[:]
        for card in cards:
            match = Card(3 - card.suit, card.rank)
            if match in self.cards:
                self.cards.remove(card)
                self.cards.remove(match)
                print('Hand {0} removed {1} and {2}.'
                          .format(self.name, card, match))


game = CardGame()
player1 = OldMaidHand('test')
game.deck.deal([player1], 13)
player1.print_deck()
player1.remove_matches()

0 个答案:

没有答案