我上周开始学习编程,而且我在编写二十一点程序时遇到了麻烦。我可以生成一个套牌列表,但我似乎无法想出根据二十一点的规则分配卡值的方法。像面牌等于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)
答案 0 :(得分: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
答案 1 :(得分: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()