0

我上周刚开始学习编程,但在编写二十一点程序时遇到了麻烦。我可以生成一个牌组列表,但我似乎想不出一种根据二十一点规则分配牌值的方法。就像面卡等于 10,ace 可以是 1 或 1,1,其余的等于它们的面值。我知道我的代码对你们来说可能是一团糟,但我宁愿继续它并犯错误并学习,而不是复制和粘贴专业人士的工作。所以你能给我一些分配卡片价值的技巧吗,谢谢。

这是我到目前为止所拥有的

import random
import time

deck = []
hand = []
dealer_hand = []
def deck_shuffle():
    for suit in ["Clubs", "Dimonds", "Hearts", "Spades"]:
        for face in ["Jack", "Queen", "King", "Ace"]:
            deck.append([face, suit])
        for num in range(2, 11):
            deck.append([num, suit])
    random.shuffle(deck)
    return deck



def deal_cards():
    for x in range(0,2):
        deal_card = deck.pop(0)
        hand.append(deal_card)
        deal_card = deck.pop(0)
        dealer_hand.append(deal_card)



deck_shuffle()
deal_cards()
print (deck)



print("Dealers hand is", dealer_hand)
print("Your hand is", hand)
4

2 回答 2

1

你可以在dict这里使用:

例子:

>>> card_vals = {"Jack" : 5, "Queen": 15, "King": 20, "Ace":10}
>>> card_vals.update({ x:x for x in range(2,11)})
>>> card_vals["Jack"]
5
>>> card_vals["Jack"]
5
>>> card_vals[2]
2
>>> card_vals[5]
5
于 2013-06-30T19:26:34.927 回答
1

我会做这样的事情

class Card:
     def __init__(self,suit,value):
         self.suit = suit
         self.value = value
     def __str__(self):
         return "A,2,3,4,5,6,7,8,9,10,J,Q,K".split(",")[self.value]+" of "+["Clubs", "Dimonds", "Hearts", "Spades"][self.suit]
     def getValue(self):
          if 0 <self.value < 10: return self.value + 1
          if self.value == 0: return 11
          return 10

class Deck:
      def __init__(self):
          self.cards = [Card(i,j) for i in range(4) for j in range(13)]
          self.cards.shuffle()

d = Deck()
print d.cards[0]
print d.cards[0].getValue()        
于 2013-06-30T19:33:04.030 回答