from random import choice as rc
def total(hand):
aces = hand.count(11)
t = sum(hand)
if t > 21 and aces > 0:
while aces > 0 and t > 21:
t -= 10
aces -= 1
return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
cwin = 0
pwin = 0
while True:
player = []
player.append(rc(cards))
player.append(rc(cards))
pbust = False
cbust = False
while True:
tp = total(player)
print ("The player has these cards %s with a total value of %d" % (player, tp))
if tp > 21:
print ("--> The player is busted!")
pbust = True
break
elif tp == 21:
print ("\a BLACKJACK!!!")
break
else:
hs = input("Hit or Stand/Done (h or s): ").lower()
if 'h' in hs:
player.append(rc(cards))
else:
break
while True:
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
while True:
tc = total(comp)
if tc < 18:
comp.append(rc(cards))
else:
break
print ("the computer has %s for a total of %d" % (comp, tc))
if tc > 21:
print ("--> The computer is busted!")
cbust = True
if pbust == False:
print ("The player wins!")
pwin += 1
elif tc > tp:
print ("The computer wins!")
cwin += 1
elif tc == tp:
print ("It's a draw!")
elif tp > tc:
if pbust == False:
print ("The player wins!")
pwin += 1
elif cbust == False:
print ("The computer wins!")
cwin += 1
break
print ("Wins, player = %d computer = %d" % (pwin, cwin))
exit = input("Press Enter (q to quit): ").lower()
if 'q' in exit:
break
print ("Thanks for playing blackjack with the computer!")
我是 python 新手。只是一个初学者。这不是我的实际代码。我做了一些调整。但大多数情况下,整体功能及其执行方式几乎相似。除了只显示数字,还有什么方法可以更改为:“黑桃”、“俱乐部”、“红心”、“钻石”、“A”、“2”、“3”、“4”、“ 5”、“6”、“7”、“8”、“9”、“10”、“J”、“Q”、“K”但仍能传递表示的值以集成到部分代码中. 我希望随着时间的推移可以改进我的代码。我对类还不是很熟悉,尽管它会使代码看起来很干净。希望任何人都可以指出错误或做出一些改进。