我刚刚开始学习Python,我的第一个项目是一个基于文本的二十一点游戏。
pHand 是玩家的手牌,pTotal 是玩家的牌总数。
for 循环似乎在第一次迭代后退出。当我在循环后打印 pTotal 和 pHand 时,它每次只显示第一张卡的值。
代码:
import random
f = open('Documents/Python/cards.txt', 'r')
deck = f.read().splitlines()
f.close
pTotal = 0
cTotal = 0
random.shuffle(deck)
pHand = [deck[0], deck[1]]
cHand = [deck[2]]
for x in pHand:
if deck[x][0] == '1' or deck[x][0] == 'J' or deck[x][0] == 'Q' or deck[x][0] == 'K':
pTotal += 10
elif deck[x][0] == 'A':
pTotal += 11
else:
pTotal += int(deck[x][0])
如有任何帮助,我们将不胜感激!
最佳答案
我想你想要的是
#using x as a list item
for x in pHand:
if x[0] == '1' or x[0] == 'J' or x[0] == 'Q' or x[0] == 'K':
pTotal += 10
elif x[0] == 'A':
pTotal += 11
else:
pTotal += int(x[0])
for-in 循环使用x
作为每个值的临时变量来迭代pHand
中的项目。就您而言,在第一次迭代中,您有 x = Deck[0]
。在第二次迭代中,您有 x = Deck[1]
。
在您发布的代码中,您尝试使用 x
作为索引,这很好,只要您为循环使用正确的值即可。
#using x as an index
for x in range(0, len(pHand)):
if deck[x][0] == '1' or deck[x][0] == 'J' or deck[x][0] == 'Q' or deck[x][0] == 'K':
pTotal += 10
elif deck[x][0] == 'A':
pTotal += 11
else:
pTotal += int(deck[x][0])
关于Python - For 循环没有启动(二十一点游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30601352/