【问题标题】:Python Blackjack CountPython二十一点计数
【发布时间】:2016-12-29 17:19:21
【问题描述】:

与其说是问题或疑问,不如说是想知道其他人会如何处理这个问题。我正在使用 python 来通过 python 的类结构制作二十一点游戏,并且我已经将卡片组做成了一个数组,其中卡片作为字符串。这有助于在 21 点中 4 张牌值 10 而 A 可以值 1 或 11 的事实。但是,计算一手牌的价值是困难的。牌组在 init 中。这怎么可能更好?我考虑过字典,但它不处理重复项。任何想法表示赞赏。对不起,如果这是一个糟糕的帖子,我是新来的。

    self.deck = [['2']*4, ['3']*4, ['4']*4, ['5']*4, ['6']*4, ['7']*4, \
                ['8']*4, ['9']*4, ['10']*4, ['J']*4, ['Q']*4, ['K']*4, \
                ['A']*4]



    def bust(self, person):

      count = 0
      for i in self.cards[person]:
        if i == 'A':
            count += 1
        elif i == '2':
            count += 2
        elif i == '3':
            count += 3
        elif i == '4':
            count += 4
        elif i == '5':
            count += 5
        elif i == '6':
            count += 6

【问题讨论】:

  • 我会有一个字典,将每个 i 映射到一个数字。然后count = sum(counts[i] for i in self.cards[person]).

标签: python list dictionary blackjack


【解决方案1】:

帮自己一个忙,得到一张卡片价值的明确地图:

CARD_VALUE = {
  '2': 2,
  '3': 3,
  # etc
  'A': 1,
  'J': 12,
  'Q': 13,
  'K': 14,
}

# Calculate the value of a hand;
# a hand is a list of cards.
hand_value = sum(CARD_VALUE[card] for card in hand)

对于不同的游戏,您可以有不同的值映射,例如Ace 值 1 或 11。您可以将这些映射放入以游戏名称命名的字典中。

另外,我不会将我的手牌表示为一张简单的卡片列表。相反,我会使用计数来打包重复值:

# Naive storage, even unsorted:
hand = ['2', '2', '3', '2', 'Q', 'Q']

# Grouped storage using a {card: count} dictionary:
hand = {'2': 3, '3': 1, 'Q': 2}
# Allows for neat operations
got_a_queen = 'Q' in hand
how_many_twos = hand['2']  # only good for present cards. 
how_many_fives = hand.get('5', 0)  # 0 returned since '5' not found.
hand_value = sum(CARD_VALUE(card) * hand[card] for card in hand)

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    SOURCE

    所以这是你可以做的:

    让你的牌组成为一个字符串

    import random 
    
    cards = 'A'*4 + '2'*4 + ... + 'K'*4
    self.deck = ''.join(random.sample(cards,len(cards)))
    values = {'2': 2,
              '3': 3,
              '4': 4,
              '5': 5,
              '6': 6,
              '7': 7,
              '8': 8,
              '9': 9,
              'T': 10,
              'J': 10,
              'Q': 10,
              'K': 10
             }
    

    然后将手定义为字符串并使用计数方法:

    def counth(hand):
        """Evaluates the "score" of a given hand. """
        count = 0
        for i in hand:
            if i in values:
                count += values[i]
            else:
                pass
        for x in hand:
            if x == 'A':
            ## makes exception for aces
                if count + 11 > 21:
                    count += 1
                elif hand.count('A') == 1:
                    count += 11
                else:
                    count += 1
            else:
                pass
        return count
    

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 1970-01-01
      • 2017-12-01
      • 1970-01-01
      • 2012-06-23
      • 2011-02-02
      • 2020-08-12
      • 1970-01-01
      • 2011-01-25
      相关资源
      最近更新 更多