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

Blackjack游戏开发求助:调用calculating_scores函数时循环异常

二十一点游戏calculating_scores函数调用问题修复

问题根源

你的代码主要有三个问题导致你误以为无法进入calculating_scores函数:

  • game_continue变量未初始化,且输入"y"后循环不会终止,导致重复回到输入步骤,看起来像"回溯"
  • 调用calculating_scores后没有处理/打印返回值,你看不到函数执行的结果,误以为没进入函数
  • calculating_scores内部逻辑错误,玩家拿到21点时错误判定庄家赢

修复后的完整代码

# 初始化全局变量
game_continue = True

def deal_cards():
    # 补全发牌逻辑,随机返回牌面数值
    import random
    cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
    return random.choice(cards)

def play():
    global game_continue
    user_cards = []
    dealer_cards = []
    for _ in range(2):
        user_cards.append(deal_cards())
        dealer_cards.append(deal_cards())

    total_user = sum(user_cards)
    print(f"你的手牌: {user_cards}, 当前总分: {total_user}\n")
    print(f"庄家的明牌: {dealer_cards[0]}\n")

    while game_continue:
        another_card = input("要再发一张牌吗?输入'y'确认,'n'结束:\n").lower()
        if another_card in ["yes", "y"]:
            user_cards.append(deal_cards())
            # 调用calculating_scores处理A的转换并获取正确总分
            user_total = calculating_scores(user_cards)
            print(f"你的手牌: {user_cards}, 当前总分: {user_total}")
            # 玩家爆牌直接终止循环
            if user_total > 21:
                print("你爆牌了,庄家获胜!")
                game_continue = False
                continue
            print(f"庄家的暗牌还未揭晓\n")
        elif another_card in ["no", "n"]:
            game_continue = False
            # 处理庄家手牌总分
            dealer_total = calculating_scores(dealer_cards)
            print(f"庄家的手牌: {dealer_cards}, 总分: {dealer_total}")
            # 获取玩家最终总分
            user_total = calculating_scores(user_cards)
            # 判定胜负
            if user_total > 21:
                print("你爆牌了,庄家获胜!")
            elif dealer_total > 21 or user_total > dealer_total:
                print("你获胜了!")
            elif user_total == dealer_total:
                print("平局!")
            else:
                print("庄家获胜!")
        else:
            print("输入无效,请重新输入!")

def calculating_scores(card_list):
    total = sum(card_list)
    # 黑杰克判定:初始两张牌和为21
    if len(card_list) == 2 and total == 21:
        return "blackjack"
    # 处理A的转换:总分超21且有A时,将11替换为1
    if 11 in card_list and total > 21:
        card_list.remove(11)
        card_list.append(1)
        total = sum(card_list)
    return total

# 启动游戏
play()

关键修复点说明

  1. 初始化全局变量:在函数外定义game_continue = True,避免未定义错误
  2. 处理函数返回值:调用calculating_scores后将结果赋值给变量,用于打印和胜负判定,直观看到函数执行效果
  3. 修正循环逻辑:玩家爆牌时直接终止循环,输入"y"后不再提前暴露庄家暗牌(符合二十一点规则)
  4. 优化calculating_scores逻辑:
    • 新增黑杰克判定规则
    • 修正玩家21点的胜负判定错误
    • 优化A牌的转换逻辑,确保总分计算准确
  5. 补充胜负判定:玩家结束拿牌后,对比双方总分完成胜负判定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:45:49