【问题标题】:Python - For loop isn't kicking in (blackjack game)Python - For 循环没有启动(二十一点游戏)
【发布时间】:2015-08-16 13:21:43
【问题描述】:

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

任何帮助将不胜感激!

【问题讨论】:

  • 第一张卡片?第一张单卡或前两张卡添加为[deck[0], deck[1]]。如果是第二种情况,则 for 循环运行正常。
  • 不,正在打印的只是 [deck[0]。不过,谢谢,
  • 我必须说,一个很棒的初学者问题 :);我在 python 中只有一周大:P

标签: python if-statement for-loop blackjack


【解决方案1】:

我想你想要的是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2023-03-21
    • 2020-05-18
    • 2013-12-27
    • 2014-10-22
    相关资源
    最近更新 更多