Python - For 循环未启动(二十一点游戏)
Python - For loop isn't kicking in (blackjack game)
我刚刚开始学习 python 我的第一个项目是基于文本的二十一点游戏。
pHand 为玩家手牌,pTotal 为玩家牌总数。
for 循环似乎在第一次迭代后退出。当我在循环后打印 pTotal 和 pHand out 时,它每次都只显示第一张卡片的值。
代码:
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 循环遍历 pHand
中的项目,使用 x
作为每个值的临时变量。在你的例子中,在第一次迭代中,你有 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 我的第一个项目是基于文本的二十一点游戏。
pHand 为玩家手牌,pTotal 为玩家牌总数。
for 循环似乎在第一次迭代后退出。当我在循环后打印 pTotal 和 pHand out 时,它每次都只显示第一张卡片的值。
代码:
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 循环遍历 pHand
中的项目,使用 x
作为每个值的临时变量。在你的例子中,在第一次迭代中,你有 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])