我正在创建一个黑色杰克启发游戏,我使用以下代码生成卡座和手:
suits = 'SCHD'
values = '23456789TJQKA'
deck = tuple(''.join(card) for card in itertools.product(values, suits))
dealershand = random.sample(deck, 1)
yourhand = random.sample(deck, 2)
问题在于,很少有机会在'dealerhand'和'yourhand'中拉出同一张卡片我想检查卡片是否已经存在,如果卡片已存在,则生成另一张卡片。像这样:
while yourhand is in dealershand:
yourhand=random.sample(deck,2)
答案 0 :(得分:10)
你可以使用random.shuffle(deck)
来改组牌组(需要list
而不是tuple
),然后你可以使用deck.pop()
来一张牌时间。
答案 1 :(得分:0)
有一种方法可以安全地使用它:
from itertools import product
from random import sample
suits = 'SCHD'
values = '23456789TJQKA'
deck = tuple(''.join(card) for card in product(values, suits))
dealershand = sample(deck, 1)
yourhand = sample(tuple([x for x in deck if x not in dealershand]), 2)