我正在创建一个21点游戏,我熟悉游戏规则。但我的难题在别处。我能够随机附加卡片到计算机和用户。但是为了这个目的,我已经写了两次for循环。我想写一个函数来随机分配两个不同的套卡给用户和计算机。为了更好地理解
,我包含了下面的代码import random
print("Welcome to Blackjack!")
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def deal_cards():
return random.choice(cards)
user_cards = []
for _ in range(2):
card = random.choice(cards)
if card in user_cards:
continue
else:
user_cards.append(card)
computer_cards = []
for _ in range(2):
card = random.choice(cards)
if card in computer_cards:
continue
else:
computer_cards.append(card)
print(user_cards)
print(computer_cards)
你可以试试这样
def deal_hand():
hand = []
for _ in range(2):
card = random.choice(cards)
if card in hand:
continue
else:
hand.append(card)
return hand
和
user_hand = deal_hand()
dealer_hand = deal_hand()