Python For loop没有启动(21点游戏)

2024-04-26 05:05:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习python,我的第一个项目是基于文本的21点游戏。你知道吗

芬德是玩家的手牌,普托塔尔是玩家牌的总数。你知道吗

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])

任何帮助都将不胜感激!你知道吗


Tags: or项目代码文本import游戏for玩家
1条回答
网友
1楼 · 发布于 2024-04-26 05:05:01

我想你想要的是

#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])

相关问题 更多 >