好的,所以我试图用Python制作一个扑克游戏..我想将已用过的牌从列表中移动到另一个列表,我将存储用过的牌。我使用此代码:
deck = ['AS', 'KS', 'QS', 'JS', '10S', '9S', '8S', '7S', '6S', '5S', '4S', '3S', '2S',\
'AD', 'KD', 'QD', 'JD', '10D', '9D', '8D', '7D', '6D', '5D', '4D', '3D', '2D',\
'AC', 'KC', 'QC', 'JC', '10C', '9C', '8C', '7C', '6C', '5C', '4C', '3C', '2C',\
'AH', 'KH', 'QH', 'JH', '10H', '9H', '8H', '7H', '6H', '5H', '4H', '3H', '2H']
used = []
p1 = []
p2 = []
a = 0
while (a < 2):
drawn_card = random.choice(deck)
deck.append(drawn_card)
deck = [f for f in deck if f not in used]
p1.append(drawn_card)
a+=1
# Don't read anything below this line
card1 = p1[0]
card2 = p1[1]
f_card1 = "Name/Suit"
f_card2 = "Name/Suit"
# Formatting Player1's first drawn card
if card1[0] == "A":
f_card1 = "Ace"
elif card1[0] == "K":
f_card1 = "King"
elif card1[0] == "Q":
f_card1 = "Queen"
elif card1[0] == "J":
f_card1 = "Jack"
else:
f_card1 = card1[0]
if card1[1] == "S":
f_card1 = f_card1 + " of Spades"
elif card1[1] == "D":
f_card1 = f_card1 + " of Diamonds"
elif card1[1] == "C":
f_card1 = f_card1 + " of Clubs"
else:
f_card1 = f_card1 + " of Hearts"
# Formatting Player1's second drawn card
if card2[0] == "A":
f_card2 = "Ace"
elif card2[0] == "K":
f_card2 = "King"
elif card2[0] == "Q":
f_card2 = "Queen"
elif card2[0] == "J":
f_card2 = "Jack"
else:
f_card2 = card2[0]
if card2[1] == "S":
f_card2 = f_card2 + " of Spades"
elif card2[1] == "D":
f_card2 = f_card2 + " of Diamonds"
elif card2[1] == "C":
f_card2 = f_card2 + " of Clubs"
else:
f_card2 = f_card2 + " of Hearts"
print(f_card1)
print(f_card2)
while函数是我的问题所在。我打印时有时会得到相同的卡片。我怎么能解决这个问题?我的错误在哪里?提前谢谢
答案 0 :(得分:1)
您只需将提取的卡片附加到used
列表,而不是回到deck
:
used.append(drawn_card) #instead of deck.append(..)
答案 1 :(得分:1)
while (a < 2):
drawn_card = random.choice(deck)
used.append(drawn_card)
deck = [f for f in deck if f not in used]
p1.append(drawn_card)
a+=1
<强> used.append(drawn_card)强>
答案 2 :(得分:1)
简单的解决方法是使用其他人建议的used.append(drawn_card)
。
更好的方法是随机洗牌,然后从中切割所需数量的卡片:
CARDS_PER_HAND = 2
random.shuffle(deck)
hand = deck[:CARDS_PER_HAND]
但是,你可能在同一套牌上交易多手牌。你可以通过跟踪进入洗牌的牌组的偏移来处理,然后从那里切片,但这很麻烦。或者你可以制作deck
的副本,随意播放,并为每只手弹出所需数量的卡片:
shuffled_deck = deck[:] # make a copy of deck
random.shuffle(shuffled_deck)
hand1 = [shuffled_deck.pop() for i in range(CARDS_PER_HAND)]
hand2 = [shuffled_deck.pop() for i in range(CARDS_PER_HAND)]
... etc.
最简单的方法可能是使用itertools.islice()
从迭代器中获取第一个 n 项:
from itertools import islice
random.shuffle(deck)
shuffled_deck = iter(deck) # returns an iterator
hand1 = list(islice(shuffled_deck, CARDS_PER_HAND))
hand2 = list(islice(shuffled_deck, CARDS_PER_HAND))
... etc.