【问题标题】:How do I replace the values of a key in Python?如何替换 Python 中键的值?
【发布时间】:2021-12-04 22:53:50
【问题描述】:

我有这个二十一点游戏,我正在尝试更改函数calculate_hand_value (hand) 并考虑到 Ace 的值可以是 1 而不是 11(如果总值超过 21,您希望 Ace计为 1)。谁能帮帮我?

import random

full_deck = {"Two of clubs": 2, "Three of clubs": 3, "Four of clubs": 4, "Five of clubs": 5, "Six of clubs": 6,
             "Seven of clubs": 7, "Eight of clubs": 8, "Nine of clubs": 9, "Ten of clubs": 10,
             "Jack of clubs": 10, "Queen of clubs": 10, "King of clubs": 10, "Ace of clubs": 11,
             "Two of diamonds": 2, "Three of diamonds": 3, "Four of diamonds": 4, "Five of diamonds": 5,
             "Six of diamonds": 6, "Seven of diamonds": 7, "Eight of diamonds": 8, "Nine of diamonds": 9,
             "Ten of diamonds": 10, "Jack of diamonds": 10, "Queen of diamonds": 10, "King of diamonds": 10,
             "Ace of diamonds": 11, "Two of hearts": 2, "Three of hearts": 3, "Four of hearts": 4, "Five of hearts": 5,
             "Six of hearts": 6,"Seven of hearts": 7, "Eight of hearts": 8, "Nine of hearts": 9, "Ten of hearts": 10,
             "Jack of hearts": 10, "Queen of hearts": 10, "King of hearts": 10, "Ace of hearts": 11,
             "Two of spades": 2, "Three of spades": 3, "Four of spades": 4, "Five of spades": 5, "Six of spades": 6,
             "Seven of spades": 7,  "Eight of spades": 8, "Nine of spades": 9, "Ten of spades": 10,
             "Jack of spades": 10, "Queen of spades": 10, "King of spades": 10, "Ace of spades": 11,
             }


def get_new_shuffled_deck():
    deck = list(full_deck.keys())
    random.shuffle(deck)
    return deck


def get_card_value(card):
    return full_deck[card]


def calculate_hand_value(hand):
    hand_value = 0

    for card in hand:
        hand_value += get_card_value(card)

    return hand_value

【问题讨论】:

    标签: python function key blackjack


    【解决方案1】:
    for card in hand:
        hand_value += get_card_value(card)
    
        if hand_value > 21:
            hand_value -= 10
    
    return hand_value
    

    【讨论】:

    • 这行不通,因为如果手牌中有 A,您只能减去 10。
    • 我不玩黑杰克!对不起
    【解决方案2】:

    您可以为 ace 添加一个计数器,如果超过 21 个,您可以为每个 ace 减去 10 分。

    def calculate_hand_value(hand):
        hand_value = 0
        aces = 0
    
        for card in hand:
            card_value = get_card_value(card)
            if card_value = 11:
                aces += 1
            hand_value += card_value
    
        for _ in range(aces):
            if hand_value > 21:
                hand_value -= 10
    
        return hand_value
    

    【讨论】:

    • 当我尝试你的代码时,我所有的卡值都是 0 :/
    • 当我将它与@nadapez 的代码混合时,我让它工作了 :)
    • 我刚刚修复了这个错误。很高兴您能够自己修复它。
    猜你喜欢
    • 2016-03-02
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2023-02-20
    相关资源
    最近更新 更多