为什么我的for循环同时而不是一次添加到所有对象?

时间:2019-10-04 18:22:01

标签: python-3.x

我正在用python制作纸牌游戏,无法将纸牌分发给玩家(为简单起见,纸牌只是字符串,而AH是王牌。)我正尝试使用模数依次向每位玩家分发一张卡。但是,对于for循环的每次迭代,每个玩家都会获得同一张牌,而不仅仅是一个玩家。我不明白为什么-如果有人可以帮助我,我会很感激!

class Player:
    def __init__(self, hand = []):
        self.hand = hand


deck = ["AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS",
        "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH",
        "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC",
        "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD"]

player1 = Player()
player2 = Player()
player3 = Player()
players = [player1, player2, player3]


def dealCards(deck, players):
    for i in range(len(deck)):
        j = i % len(players)
        players[j].hand.append(deck[i])


calculateHandSize(deck, players)

1 个答案:

答案 0 :(得分:0)

这会得到我相信您想要的结果。我修复了一些问题:

class Player:
    def __init__(self, hand=None):
        if hand is None:
            self.hand = []
        else:
            self.hand = hand

deck = ["AS", "2S", "3S", "4S", "5S", "6S", "7S", "8S", "9S", "10S", "JS", "QS", "KS",
        "AH", "2H", "3H", "4H", "5H", "6H", "7H", "8H", "9H", "10H", "JH", "QH", "KH",
        "AC", "2C", "3C", "4C", "5C", "6C", "7C", "8C", "9C", "10C", "JC", "QC", "KC",
        "AD", "2D", "3D", "4D", "5D", "6D", "7D", "8D", "9D", "10D", "JD", "QD", "KD"]

player1 = Player()
player2 = Player()
player3 = Player()
players = [player1, player2, player3]


def deal_cards(deck, players):
    for i, card in enumerate(deck):
        j = i % len(players)
        players[j].hand.append(deck[i])


deal_cards(deck, players)

for p in players:
    print(p.hand)

手的样子:

['AS', '4S', '7S', '10S', 'KS', '3H', '6H', '9H', 'QH', '2C', '5C', '8C', 'JC', 'AD', '4D', '7D', '10D', 'KD']
['2S', '5S', '8S', 'JS', 'AH', '4H', '7H', '10H', 'KH', '3C', '6C', '9C', 'QC', '2D', '5D', '8D', 'JD']
['3S', '6S', '9S', 'QS', '2H', '5H', '8H', 'JH', 'AC', '4C', '7C', '10C', 'KC', '3D', '6D', '9D', 'QD']

我认为问题在于使用枚举是更好的选择的范围。我并没有深入证明到底出了什么问题。我还更改了__init__中的默认arg,以使Python更满意。

该解决方案可以进一步压缩,并且可以简化。