2016-08-23 77 views
1

不是一個問題或問題,只是想知道其他人會如何處理這個問題。我正在Python中通過python的類結構來製作二十一點遊戲,並且我已經將卡片作爲字符串作爲數組。這有助於事實上4張牌在二十一點值10,Ace可以在1或11上。但是,計算一手牌的價值是很難的。該套牌位於init。這怎麼能更好?我考慮過一本字典,但不能處理重複。任何想法都表示讚賞。對不起,如果這是一個壞的帖子,我是新來的。Python Blackjack Count

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 
+1

我會有一個字典映射每個'我'的數字。然後'計數=總和(在自我卡[人]中計數[i])'。 – zondo

回答

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) 

希望這會有所幫助。

0

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