python中的21点程序



我上周刚开始学习编程,在编写21点程序时遇到了问题。我可以生成一个牌组列表,但我似乎想不出根据21点规则分配牌值的方法。就像人脸卡等于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)

您可以在此处使用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

我会做一些类似的事情

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()        

相关内容

  • 没有找到相关文章

最新更新