0

这是课程:

class Player:
    #variables
    hand = []
    name = 'Test Player'
    #functions
    def take(self, card): #allows player to take a card
        self.hand.append(card)
    def __str__(self):
        msg = self.name
        if len(self.hand) > 0:
            msg = msg + "\nIn hand:"
            for card in self.hand:
                msg = msg + ' ' + card.short_name
        return msg

这是功能:

def deal(players):
    deck = Deck.generate_deck()
    if len(players) <= 4:
        for player in players:
            for cards in range (0, 7):
                card = random.choice(deck)
                player.take(card)
                deck.remove(card)
    else:
        for player in players:
            for cards in range (0, 5):
                card = random.choice(deck)
                player.take(card)
                deck.remove(card)
    return deck

这是问题所在。当我调用函数向五个玩家发牌时,这就是我得到的。

Player 1
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

Player 2
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

Player 3
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

Player 4
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

Player 5
In hand: JC 2H KD 8H QD KH AS 10S QC 10H AH 6S JD 4H 5S 4S 9C 3C QH 9S AD 6D 8S 10C 7C
25

ps 之后的数字是我测试代码中的一个小调试,没有影响。

4

1 回答 1

3

您的问题是您的hand = []清单附在班级上;它是一个类属性并在实例之间共享。

为方法中的每个玩家创建一个新列表__init__

class Player:
    def __init__(self):
        self.hand = []
于 2013-02-08T20:03:28.573 回答