我正在創建一個二十一點游戲,我熟悉游戲規則。但我的難題在于別處。我可以將卡隨機附加到計算機和用戶。但是為了這個目的,我已經寫了兩次 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)
uj5u.com熱心網友回復:
你可以試試這樣的
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/342655.html
