Python - For 循环没有启动(二十一点游戏)

标签 python if-statement for-loop blackjack

我刚刚开始学习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/

相关文章:

python - 以敏捷/BDD 方式在 Django 中使用 Doctests 的示例

string - R字符串分割函数(strsplit)中的非字符参数

java - 无法将 : receive user input "yes" or "y", boolean 值翻转为 true

swift - 我的 for 循环出了什么问题 - 它没有达到最高等级

python - For-Loop打印整个范围

python - 未在 Tornado 中设置 Content-Type header

python - Performance_Python 根据元组的 3 个元素中的 2 个获得 2 个元组列表的并集

python - Pyside 或 PyQt 支持 Qt 5.0 和 Qt Quick 2

java - 为输入的每个字符分配一个值并显示输入的值