我正在学习Python,尽管我已经找到了关于这个错误的资源,但当应用到我的案例中时,他们的解决方案并不是特别清楚。
这就是:
完整错误:
Traceback (most recent call last):
File "main.py", line 136, in <module>
game()
File "main.py", line 131, in game
dealer_result = dealer()
File "main.py", line 66, in dealer
dvalue = value(dealer_hand)
File "main.py", line 36, in value
value += cards.get(c)
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
背景:
- 这是21点游戏。
- game()是一个围绕整个游戏的函数,每个方面都有一个完整的函数子集。
- 错误不一致
代码流:我有卡片2到A,它们的值在字典中定义。
cards = {
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"10": 10,
"J": 10,
"Q": 10,
"K": 10,
"A": 11,
}
游戏从定义玩家和庄家手牌的变量开始player_hand = start()
和dealer_hand = start()
其中
def start():
hand = []
hand.extend([random.choice(list(cards)), random.choice(list(cards))])
return hand
全局“flag”变量被预先设置为“h”以允许代码进入游戏的主要部分上的循环
首先,我们将使用value(hand)
函数计算玩家手牌的值:
def value(hand):
value = 0
for c in hand:
if c != "A":
value += cards.get(c)
elif c == "A" and value >= 11:
value += 1
else:
value += 11
return value
并将其归因于p_value变量。
我想这就是错误的地方,虽然,由于手是从字典中随机选择的卡片,它怎么可能在浏览同一本字典时找不到这样的卡片呢?
玩家阶段:
def main(flag):
p_value = value(player_hand)
if p_value == 21:
result = "blackjack"
else:
while flag == "h":
if p_value == 21:
flag = "s"
elif p_value > 21:
print("Bust")
flag = "s"
if flag != "s":
flag = str(input("[h]it, [s]tay or [q]uit?: "))
if flag == "h":
player_hand.extend(hit())
p_value = value(player_hand)
print("Player: Current value: " + str(p_value) + ". Current hand: " + ', '.join(player_hand))
elif flag == "q":
exit()
result = p_value
return result
然后,我使用返回的结果来比较最终玩家结果与最终庄家结果
经销商阶段:
def dealer():
dvalue = value(dealer_hand)
print("Dealer value: " + str(dvalue) + ". Dealer hand: " + ', '.join(dealer_hand))
if dvalue == 21:
result = "blackjack"
else:
while dvalue < 17:
dealer_hand.extend(hit())
dvalue = value(dealer_hand)
print("Dealer value: " + str(dvalue) + ". Dealer hand: " + ', '.join(dealer_hand))
result = dvalue
return result
发生错误的真实的场景:
Play again? y/n: y
Player: Current value: 10. Current hand: 2, 8
Dealer: Current hand: ?, 5
[h]it, [s]tay or [q]uit?: s
Dealer value: 7. Dealer hand: 2, 5
Traceback (most recent call last):
File "main.py", line 136, in <module>
game()
File "main.py", line 131, in game
dealer_result = dealer()
File "main.py", line 66, in dealer
dvalue = value(dealer_hand)
File "main.py", line 36, in value
value += cards.get(c)
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
预期结果是庄家继续循环hit()函数,直到他的手牌值value(dealer_hand)
等于或大于17。
2条答案
按热度按时间hgc7kmma1#
extend
接受一个“iterable”,并将该iterable中的所有元素添加到列表中。字符串是一个iterable,其中一个值包含多个字符。另一方面,
append
获取一个值并将其原样添加到列表中。此示例说明了问题所在:
dfddblmv2#
以下是我的心灵调试尝试:
可能发生的情况:
hit()
返回字符串..._hand.extend(hit())
然后将字符串中的每个字符添加到手形中"10"
,则会拆分为"1"
和"0"
,这两个卡不在cards
中cards.get(c)
返回None
解决方案是什么:将
extend
更改为append
;请参见https://docs.python.org/3/tutorial/datastructures.html#more-on-lists或https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types。