【问题标题】:BlackJack(Python): Adding the "HIT" card value二十一点(Python):添加“命中”卡值
【发布时间】:2017-03-18 13:49:34
【问题描述】:

我正在用 python 编写二十一点代码。到目前为止,我已经为玩家处理了两张初始牌。如果是自然获胜,程序会识别它并打印“BlackJack!”。如果有可能命中,则会提示用户“命中还是站立?H\S。我无法弄清楚如何将“命中”卡的值添加到前两张卡的值中。

这是我的代码:

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)

【问题讨论】:

    标签: append blackjack


    【解决方案1】:

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

    但是,鉴于您现有的字符串,并且您的“手”是一张卡片列表,点击只是附加另一张卡片。然后你只需要一个更好的 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)
    

    然后从那里出发。

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-12
      • 2018-04-17
      相关资源
      最近更新 更多