我正尝试在python中制作二十一点,但是当计算机获胜时,它无法正常工作,我无法理解为什么。这是我的代码:
import random
hand = []
chand = []
bust = 'no'
sit = 'no'
value = 0
ais = 0
play = 'yes'
x = 0
cards = {
'a': 11,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'10': 10,
'j': 10,
'q': 10,
'k': 10,
}
print('''welcome to black jack
type draw or sit to get started''')
while x < 2:
cardc = random.choice(list(cards.keys()))
hand.append(cardc)
x = x + 1
print('your cards', ', '.join(hand))
while bust != 'yes' and sit != 'yes':
player = input('what would you like to do: ')
if player == 'draw':
cardc = random.choice(list(cards.keys()))
hand.append(cardc)
print('your cards', ', '.join(hand))
value = 0
for i in hand:
value = value + cards[i]
# print(value)
if value > 21:
bust = 'yes'
elif 'sit' in player:
print('you have sat')
sit = 'yes'
if 'yes' in bust:
print ('you lose')
if sit == 'yes':
while ais < value and ais < 21:
cardc = random.choice(list(cards.keys()))
chand.append(cardc)
ais = 0
for i in chand:
ais = ais + cards[i]
print(ais)
if ais > 21:
print('my score was', ais)
print('you win')
else:
print('my score was', ais)
print('you lose')
当计算机获胜时,本来是要显示计算机卡,但只是显示空白,而当玩家获胜时,则要显示计算机卡。 我对python很陌生,可能会遗漏一些明显的东西,但我不知道为什么会出错
答案 0 :(得分:1)
while ais < value and ais < 21:
是您面临的问题。如果ais
== value
永远不会运行,那么发牌者就不会抓牌。
您需要使用;
while ais <= value and ais < 21:
此外,这与您在此处遇到的问题有关;
if ais > 21:
print('my score was', ais)
print('you win')
else:
print('my score was', ais)
print('you lose')
您只检查庄家的手牌是否超过21张。您不检查是否有开奖(这会造成损失)。
如果玩家没有抓牌,您也不会设置值,这意味着即使用户比发牌者得分更高,如果玩家没有抓牌,发牌者也将永远获胜。
welcome to black jack
type draw or sit to get started
your cards a, 8
what would you like to do: sit
you have sat
5
my score was 5
you lose