我正在做一個 Blackjack 專案。
我希望能夠在整數 2-10 的串列中使用字母“A”。
我在傳遞字串的值時迷路了,在這種情況下,'A' 進入卡片的 sum() 函式,然后回傳該值,但顯示卡片中的 'A' 是我迷路的地方。
例如:cards = ['A',2,3,4,5,6,7,8,9,10]
該串列將隨機回傳 2 個值,范圍從 A-10 然后如果 A 回傳另一個數字,我想計算字母 A 整數的值
它會向用戶列印類似“你的手是:[A,7] 總計 = 18”的內容
這是我迄今為止一直在試驗的。
import random
A = ord("A") - 64
def deal():
cards = [A, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
player = []
dealer = []
while len(player) < 2:
player.append(random.choice(cards))
dealer.append(random.choice(cards))
return player, dealer
#this is ITERABLE UNPACK it separates the returned values from the deal() function and assigns them to their respective variables.
player, dealer = deal()
#sum the value of the cards
player_cards = sum(player)
dealer_cards = sum(dealer)
print(f"Your cards are {player}. Total = {player_cards}")
print(f"The dealer shows [{dealer[0]}, *]. Total = {dealer_cards}")
uj5u.com熱心網友回復:
嘗試:
def get_sum(cards):
return sum(card if not card == 'A' else 11 for card in cards)
player = ['A', 7]
dealer = [8, 'A']
player_cards = get_sum(player)
dealer_cards = get_sum(dealer)
print(f"Your cards are {', '.join([', '.join(str(i) for i in player)])}. Total = {player_cards}")
print(f"The dealer shows {dealer[0]}. Total = {dealer_cards}")
輸出:
Your cards are A, 7. Total = 18
The dealer shows 8. Total = 19
如果你有 King、Queen 和 Jack,你可以使用這個版本:
player = ['A', 'K']
def get_sum(cards):
vals = {'A': 11, 'K': 10, 'Q': 10, 'J': 10}
return sum(vals.get(card, card) for card in cards)
print(get_sum(player))
print(f"Your cards are {player}. Total = {player_cards}")
print(f"The dealer shows [{dealer[0]}, *]. Total = {dealer_cards}")
輸出:
21
uj5u.com熱心網友回復:
在處理卡片時,我更喜歡使用,random.sample(cards, len(cards))因為這喜歡隨意混合卡片。
# let's define cards
card_values = {'A': 11, 'K': 10, 'Q': 10, 'J': 10}
card_values.update({k: k for k in range(2, 11)})
# because I am too lazy to write all card values by hand
cards = card_values.keys()
def random_select(cards, k=2):
new_order = random.sample(cards, len(cards))
return new_order[:k], new_order[k:]
# and you can choose first 2 by:
two_cards, rest_deck = random_select(cards, k=2)
# and for next player you do:
two_next_cards, rest_deck = random_select(rest_deck, k=2)
# in this way, the already selected cards are removed from the original deck (rest_deck).
def card_sums(cards):
return sum([card_values[x] for x in cards])
def deal(players, cards, k=2):
result = {}
rest_cards = cards
for player in players:
chosen, rest_cards = random_select(rest_cards, k = k)
result[player] = chosen
return result, rest_cards
players = {'player': [], 'dealer': []}
selected_cards, rest_cards = deal(players, cards, k=2)
print(f"Your cards are {selected_cards['player']}. Total = {card_sums(selected_cards['player'])}")
print(f"The dealer shows {selected_cards['dealer']}. Total = {card_sums(selected_cards['dealer'])}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362108.html
