我正在制作一款支持多名玩家的二十一点游戏。它通过拥有一个玩家对象列表来实现此目的,每个对象都有一个卡片变量,用于存储玩家的卡片。
我想抽一张牌并将其附加到玩家 2 的牌列表中(玩家 2 是最后一个玩家)。 我有一个绘制卡片的函数,我认为可以仅从中获取输出并将其附加到玩家的卡片列表中。
所以我用这行代码做到了:
players[2].cards.append(drawCard())
但相反,它将卡片附加到所有玩家对象卡片变量中
我不知道为什么
这是代码:
import random
players: list[object] = [] # list for the player objects to be put into
def drawCard(): # Takes a random number from 2, 14 and returns it. Like in blackjack
card = random.randint(2,14)
if (card >= 11) and (card <= 13):
print("[DRAWCARD] - Facecard")
card = 10
elif card == 14:
print("[DRAWCARD] - Ace")
card = 11
return card
class Player: # The player with a list of cards
cards: list[int] = []
for i in range(3): # Make three players and save them in players list
players.append(Player())
players[2].cards.append(drawCard()) # use drawCard() and append players[2]'s card list with the given card
for player in players: # print the cards of all players
print(player.cards)
print(player)
这是输出:(当然,每次运行时数字都会改变,但问题仍然存在,它应该只给最后一个玩家一张牌)
[5]
<__main__.Player object at 0x00000140AEB5A3F0>
[5]
<__main__.Player object at 0x00000140AEB5A330>
[5]
<__main__.Player object at 0x00000140AEB5BDA0>
cards: list[int] = []
在那里分配,这将创建一个由所有实例共享的 class 属性。要创建每个实例唯一的实例属性,请使用
__init__
:
class Player: # The player with a list of cards
def __init__(self):
self.cards: list[int] = []
或者使该类成为数据类。