我正在尝试编写一个蟒蛇代码来模拟二十一点,并且正在使用各种功能进行交易,击球,站立等等。我一直坚持我的"手"在调用不同的函数之间不会节省。
例如,如果我调用deal()并且它返回我的手和经销商的手,那么我调用hit()它会返回一张卡,而不是我发出的牌和新牌。
我想知道如何保存我的手,因为我认为使用追加只会在我的手上添加卡片。
这是我的代码:
import random
import itertools
deck = [val for val in range(2,12) for _ in range(4)]
for i in range(12):
deck.append(10)
player_hand=[]
dealer_hand=[]
def deal():
player_hand = []
dealer_hand = []
carddeal1 = random.sample(deck,2)
carddeal2 = random.sample(deck,2)
for i in range(2):
deck.remove(carddeal1[i])
deck.remove(carddeal2[i])
player_hand.append(carddeal1[i])
dealer_hand.append(carddeal2[i])
evaluate(player_hand)
evaluate(dealer_hand)
return player_hand,dealer_hand
def hit():
cardhit = random.sample(deck,1)
deck.remove(cardhit[0])
player_hand.append(cardhit[0])
return player_hand
def dealer_hit():
cardhit = random.sample(deck,1)
deck.remove(cardhit[0])
dealer_hand.append(cardhit[0])
return dealer_hand
def evaluate(hand):
if 11 in hand and sum(hand)>21:
if sum(hand)>31:
return "bust"
else:
return "okay"
elif sum(hand)==21:
print "21!!!!"
else:
if sum(hand)>21:
return "bust"
else:
return "okay"
def stand():
if sum(dealer_hand)>16 and sum(dealer_hand)>sum(player_hand) and
evaluate(dealer_hand)!="bust":
print "dealer wins, type deal() to restart"
elif sum(dealer_hand)>16 and sum(dealer_hand)<sum(player_hand) and
evaluate(player_hand)!="bust":
print "You win! type deal() to restart"
else:
dealer_hit()
stand()