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

基于PySimpleGUI的Blackjack程序重复扣奖问题求助

解决Blackjack游戏重复金额变动的异常

问题根源

  1. 结算逻辑重复触发
    主循环中每次window.read()后都会调用check_win(),但一局游戏结束后,player_value仍保留着上一局的结果(比如玩家爆牌后player_value>21)。此时点击「Yes/No」,check_win()会检测到player_value>=21,再次调用stand(),导致end_game()和results()重复执行,二次修改player_money。

  2. 核心状态未及时重置
    新回合开始时,仅在count!=0时才调用start_game()重置状态,第一局后的旧变量值残留,加上check_win()的无差别触发,进一步加剧了重复结算的问题。

修复方案

1. 调整check_win()的调用时机

只在玩家点击「Deal」发牌后调用该函数,避免非游戏阶段触发结算:

while True:
    event, values = window.read()

    if event == "Deal":
        deal()
        window['pc'].update(F"Your cards: {player_cards}")
        window['pv'].update(F"The value of your cards: {player_value}")
        check_win()  # 仅在发牌后检查是否爆牌
        
    elif event == "Stand":
        stand()
         
    elif event == "Yes":
        window['-COL1-'].update(visible=False)
        window['-COL2-'].update(visible=True)

    elif event == "Start":
        bet_input = window["money"].get()
        if error_trap(bet_input):
            bet = int(bet_input)  # 提前转换为整数,避免后续重复转换
            window['-COL2-'].update(visible=False)
            window['-COL1-'].update(visible=True)
            start_game()  # 所有新回合都重置游戏状态
            update_layout()

2. 优化check_win()的触发条件

只有当玩家爆牌(player_value>21)时才触发结算,避免黑杰克(刚好21点)时误触发:

def check_win():
    global player_value
    if player_value > 21:
        stand()

3. 清理冗余全局变量转换

移除results()中重复的bet = int(bet),因为在「Start」按钮处理时已经完成了类型转换,避免潜在的重复计算问题:

def results():
    global player_value
    global computer_value
    global window
    global player_money
    global bet
    global count
    global end
    end = 0
    # 移除此处的bet=int(bet)
    if player_value > 21:
        player_money -= bet
        window['results'].update(F"You lost ${bet} and now have {player_money}.")
    # 剩余逻辑保持不变

修复效果

修改后,金额变动只会在每局游戏结束时执行一次,点击「Yes/No」切换回合时不会再触发重复结算,游戏状态在每次新回合都会被正确重置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 20:04:56