创建一个方法,将对二十一点的嵌套值求和

时间:2015-08-18 21:29:41

标签: python string list methods int

我正在制作一个Python Blackjack游戏,我将其设置为获取用户名并创建一个随机随机播放并向用户显示一手牌的牌组。

我还想为用户显示一个运行总计。鉴于用户可能“点击”,我想让这个方法我可以回想起更清洁的代码。

我开始研究它(参见下面的代码),但我仍然坚持如何编写一个正确的方法来做到这一点。我假设必须发生一些str到int转换,并且“face cards”必须被赋值为10.另外一个Ace理想情况下会运行某种条件循环,如果总数低于11,则计为11,但如果总数为11超过11它算作1.

user_name = input("Please enter your name:")
print ("Welcome to the table {}. Let's deal!".format(user_name))

import random

suits = ["Heart", "Diamond", "Spade", "Club"]    
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
deck = [(suit, rank) for rank in ranks for suit in suits]

random.shuffle(deck,random.random)

user_hand = []
dealer_hand = []
user_hand.append(deck.pop())
dealer_hand.append(deck.pop())
user_hand.append(deck.pop())
dealer_hand.append(deck.pop())

def handtotal (hand):
    total = 0
    rank = [][1]

    for rank in hand:
        if rank == "J" or "Q" or "K":
            total += 10
        elif rank ==


print ("Your current hand is {}".format(user_hand))

user_hitstay = input("Will you hit (H) or stay (S)":)

2 个答案:

答案 0 :(得分:0)

你可以这样做:

try:
    total += int(card)
with ValueError:
    # must be a face card...
    if val == 'K':
        total += 13
    elif val == 'Q':
        ...
    elif val == 'A' and total <= 10:
        ...
    elif val == 'A' and total > 10:
        ...

其中card是其中一个字符串

答案 1 :(得分:0)

for rank in hand:
    if rank == "J" or "Q" or "K":
        total += 10
    elif rank == 'A' and total < 11:
        total += 11
    elif rank == 'A' and total >= 11:
        total += 1

......等等

您可以添加其余条件