Blackjack游戏pc_moves函数求和忽略第4个元素的原因排查
问题分析与修复:Blackjack游戏中电脑手牌总和计算错误
问题现象
在实现Blackjack游戏的pc_moves()函数时,当电脑手牌增加到第4张时,pc_sum没有正确计算所有手牌的总和。例如:
computers_cards: [4, 1, 10, 10]
pc sum : 15
实际总和应为25,但pc_sum只计算了前3张牌的和。
问题根源
问题出在嵌套函数add_new_card_pc的递归调用逻辑中:当递归调用add_new_card_pc时,没有将递归的返回值传递回来,导致上层函数的pc_sum无法更新为最新的总和。
具体来说,以下两处递归调用缺少return语句:
- 处理Ace转1后,若
pc_sum仍小于17时的递归调用 - 当
pc_sum小于17且未触发其他条件时的递归调用
这会导致递归计算的新总和无法传递到上层函数,最终pc_sum停留在递归前的数值。
修复方案
在递归调用add_new_card_pc的位置加上return,确保递归计算的结果能被正确返回并更新pc_sum。同时优化部分逻辑,避免重复计算总和:
import random # 补充原代码遗漏的random模块导入 cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] your_cards = [] computers_cards = [] game = True pc_sum = 0 def f_wants_to_play(): global game wants_to_play = input("Do you want to play a game of Blackjack? Type 'y' or 'n':") if wants_to_play == "y": print("blackjack") elif wants_to_play == "n": print("You don't wanna play! Goodbye!") game = False else: print("Type 'y' or 'n'!") f_wants_to_play() def pc_moves(): global pc_sum global computers_cards computers_cards = random.sample(cards, 2) pc_sum = sum(computers_cards) print(f"computers cards: {computers_cards}") def add_new_card_pc(current_sum, current_cards): if current_sum == 22: return current_sum elif current_sum < 17: current_cards.append(random.choice(cards)) current_sum = sum(current_cards) if current_sum == 21: return current_sum elif current_sum > 21: if 11 in current_cards: ace_index = current_cards.index(11) current_cards[ace_index] = 1 current_sum = sum(current_cards) if current_sum > 21: return current_sum else: # 递归调用时返回结果,更新总和 return add_new_card_pc(current_sum, current_cards) else: return current_sum elif 17 <= current_sum < 21: # 修正条件,包含等于17的情况(符合Blackjack规则) return current_sum else: # 递归调用时返回结果,更新总和 return add_new_card_pc(current_sum, current_cards) return current_sum pc_sum = add_new_card_pc(pc_sum, computers_cards) def blackjack(): while game == True: f_wants_to_play() if not game: break your_cards = random.sample(cards, 2) print(f"Your cards: {your_cards}, current score: {sum(your_cards)}") # 改用sum简化计算 user_sum = sum(your_cards) pc_moves() print(f"pc sum : {pc_sum} computers_cards: {computers_cards}") blackjack()
关键修复点
- 在两处递归调用
add_new_card_pc的位置添加return,确保递归计算的最新总和能传递回上层函数 - 修正条件判断
17<pc_sum<21为17<=current_sum<21,符合Blackjack规则(电脑手牌总和≥17时停止拿牌) - 补充原代码遗漏的
import random模块 - 简化用户手牌总和的计算逻辑,直接使用
sum()函数
内容的提问来源于stack exchange,提问作者MaximusPrima
相关产品推荐
相关产品推荐

