BlackJack(Python):添加" HIT"卡价值

时间:2016-11-04 16:30:09

标签: append blackjack totals

我在python中编写了二十一点的代码。到目前为止,我已经为玩家处理了两张初始牌。如果它是一个自然的胜利,程序识别它并打印" BlackJack!"。如果它有可能被击中,那么它会提示用户"击中或站立? ^ h \ S。我无法弄清楚如何添加" hit"卡到前两张牌的价值。

这是我的代码:

import random


def create_hand(hand):
    for i in range(2):
        pip = random.choice(PIPS)
        suit = random.choice(SUITS)
        card = (pip,suit)
        player_hand.append(card)






def print_hand(hand):
    for pip, suit in hand:
        print(pip + suit,end=" ")
    print()

def sum_hand(hand):
    total = 0
    for pip,suit in player_hand:
        if pip == "J" or pip == "Q" or pip == "K":
            total += 10
        elif pip == "A" and total < 10:
            total += 11
        elif pip == "A" and total == 10:
            total +=11 
        elif pip == "A" and total > 10:
            total += 1
        else:
            total += int(pip)
        if total == 21:
            print("BlackJack!")
            return total

def hit_card():
    pip = random.choice(PIPS)
    suit = random.choice(SUITS)
    card = (pip, suit)
    return card


def hit(player_hand):         
    total = sum_hand(player_hand)
    choice = input("Hit or Stand? h/s: ")
    while choice.lower() == "h":
        if total != 21:

            player_hand.append(hit_card())
            print_hand(player_hand)







CLUB = "\u2663"
HEART = "\u2665"
DIAMOND = "\u2666"
SPADE = "\u2660"

PIPS = ("A","2","3","4","5","6","7","8","9","10","J","Q","K")
SUITS = (CLUB, SPADE, DIAMOND, HEART)

player_hand = []
total = sum_hand(player_hand)
create_hand(player_hand)
print_hand(player_hand)


hit(player_hand)

1 个答案:

答案 0 :(得分:0)

字符串适用于人类:计算机使用数字,所以我的第一个建议是用数字而不是字符串来表示卡片。将使代码更简单,更快。

但是,鉴于您现有的字符串,而您的“手”是一张卡片列表,点击只是附加另一张卡片。然后你只需要一个更好的sum_hand()函数来累计手牌,但是其中有很多牌。像这样:

def sum_hand(hand):
    total = 0
    acefound = False

    for card in hand:
        pip = card[0]
        if ("A" == pip):
            total += 1
            acefound = True
        elif (pip in [ "J", "Q", "K", "10" ]):
            total += 10
        else:
            total += int(pip)

    if (acefound and total < 12):
        return True, total + 10

    return False, total

重要的是不仅要获得数字总数,还要获得软/硬数据,因为这可以决定未来的行动。所以你使用这个函数,如:

soft, total = sum_hand(theHand)

从那里开始。