如何将一个列表中的两个项目迭加起来,形成一个总数(21点手牌中的牌)?

问题描述 投票:0回答:1

PlayersHand是这样设置的。

import random

PlayersHand = []
DealersHand = []
Ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10","Ace", "Jack", "Queen", "King"]
Suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
Deck = []
for num in Ranks:
    for  suit in Suits:
        card = num + ' of ' + suit
        Deck += [card]
        random.shuffle(Deck)

print()

for i in Deck:
    numval=(i[0]) 

PlayersHand = random.choices(Deck, k=2)
        print(name,"Your cards are", PlayersHand)
        DealersHand = random.choices(Deck, k=1)
        print("Dealer, your cards are Blank +",DealersHand)
        total = 0

  for i in PlayersHand:
        countval=(i[0])#to get the value of the card(perhaps need first two values for one or ten)
        print ("count is", countval);
        print("-------------")
        print(i)
    if countval == "J" or countval =="K" or countval =="Q": total +=10
    elif  countval =="A":
            total = 11
    else:
            total=countval

    print ("countval is",countval)
    print ("countval is",total)

在代码中,我放了一些标记,以帮助我理解流程.i值重复,因为它应该,但采取(第二)值,我似乎不能抓住和使用第一个值分开,所以我可以添加它们.即countval1添加到countval2将成为totalI然后需要能够添加下一个新的卡.我知道有更好的方法,我不太明白(如dicts等),但我'想完成这样的,因为我挣扎了这么久。

我知道还有更好的方法,但我还不太明白(如dicts等),但我想这样完成,因为我已经挣扎了很久了!

python blackjack
1个回答
1
投票

请注意,在另外两个分支的 if 语句,你忘了 + 因此,与其说是加总(+=),你就会覆盖这个值(=).

假设 PlayersHand 是一个可迭代的字符串对象(即一个列表),你的代码应该像这样。

total = 0

for i in PlayersHand:
    countval = i[:2] # up to two characters

    if countval in 'JKQ':
        total += 10
    elif countval == 'A':
        total += 11
    else:
        total += int(countval) # cast a string to a number 
© www.soinside.com 2019 - 2024. All rights reserved.