You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Blackjack游戏中无法修改Boolean变量终止循环问题

Blackjack模拟器循环无法终止的问题分析与修复

核心问题

  1. 变量作用域错误:你在hand()函数里写的playing=False并没有修改全局的playing变量,而是在函数内部创建了一个同名的局部变量。Python默认在函数内部对变量赋值时,会将其视为局部变量,除非显式声明要修改全局变量。
  2. 逻辑位置错误:输入'n'的分支中,playing=False被放在了dealer补牌的while循环内部。如果dealer初始手牌总和已经≥17,这个循环不会执行,playing根本不会被设为False,循环自然停不下来。

修复方案

  1. 在hand()函数开头添加global playing声明,让函数能直接修改全局的playing变量。
  2. 将输入'n'分支里的playing=False移到dealer补牌循环的外面,确保只要用户输入'n'就会触发终止逻辑。
  3. 补充输入'n'后的结果显示逻辑,让用户能看到最终胜负。

修复后的完整代码

from art import logo
import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
my_hand = []
dealer_hand = []

def hand():
    global playing  # 声明要修改全局变量playing
    continue_play = input("Type 'y' to get another card, type 'n' to pass: ")
    
    if continue_play == 'y':
        my_hand.append(random.choice(cards))
        dealer_hand.append(random.choice(cards))
        
        if sum(my_hand) > 21:
            print(f"Your final hand: {my_hand}, final score: {sum(my_hand)}")
            print(f"Computers final hand: {dealer_hand}, final score: {sum(dealer_hand)}")
            print("You went over. You lose 😤")
            playing = False
            
        elif sum(my_hand) <= 21:
            print(f"Your cards: {my_hand}, current score: {sum(my_hand)}")
            print(f"Computers first card: {dealer_hand[0]}")

    elif continue_play == 'n':
        sumz = sum(dealer_hand)
        while sumz < 17:
            dealer_hand.append(random.choice(cards))
            sumz = sum(dealer_hand)
        # 将playing=False移到循环外,确保输入'n'就终止
        playing = False
        # 显示最终结果
        print(f"Your final hand: {my_hand}, final score: {sum(my_hand)}")
        print(f"Computers final hand: {dealer_hand}, final score: {sum(dealer_hand)}")
        my_final = sum(my_hand)
        dealer_final = sum(dealer_hand)
        if my_final > 21:
            print("You went over. You lose 😤")
        elif dealer_final > 21 or my_final > dealer_final:
            print("You win 🎉")
        elif my_final == dealer_final:
            print("It's a draw 🙃")
        else:
            print("Dealer wins 😤")

first_play = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ")

if first_play == 'y':
    print(logo)
    my_hand = random.sample(cards, 2)
    dealer_hand = random.sample(cards, 2)
    print(f"Your cards: {my_hand}, current score: {sum(my_hand)}")
    print(f"Computers first card: {dealer_hand[0]}")

playing = True

while playing:
    hand()

额外说明

  • 原代码里每次玩家拿牌时dealer也跟着拿,这不符合标准Blackjack规则(dealer是在玩家停止拿牌后才补牌到≥17),修复后的代码保留了原逻辑,但你可以根据规则调整这部分。
  • 当玩家手牌总和超过21时,直接判定输,不需要再进入后续的胜负判断。

内容的提问来源于stack exchange,提问作者Salah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:24:52