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

如何让程序回到起始位置?Python冒险游戏重启逻辑修复请求

实现程序流程回到起始位置&修复冒险游戏代码

嘿,很高兴能帮到你!要让程序执行流程回到起始位置,最实用的做法就是把整个核心逻辑包裹在一个循环结构里——比如while True无限循环。当需要重启时,用continue语句直接跳回循环开头;如果想结束程序,就用break退出循环。

针对你提供的Python 2.x冒险游戏代码,我发现了几个逻辑问题:choice_2的作用域错误(选Hill时会触发未定义错误)、眼镜蛇分支的循环逻辑混乱,还有缺少重启/退出的合理控制。下面是修复后的完整代码,我会逐一解释关键修改点:

修复后的代码

while True:
    print 'Adventure Game'
    # 增加退出选项,让用户可以主动结束游戏
    choice_1 = raw_input('You are travelling down a long road, there is a fork in the route, one side goes to a jungle, and the other leads to a hill biome, which side do you choose? J for Jungle, H for Hill, Q to Quit ')
    
    # 处理退出请求
    if choice_1.upper() == 'Q':
        print 'Thanks for playing!'
        break
    
    # 丛林分支逻辑
    if choice_1.upper() == 'J':
        print 'Jungle?, very well then'
        choice_2 = raw_input('In the jungle, a king cobra appears behind you, as you look forward, an ape leaps from a tree onto the ground. Do you take your chances with the venomous king cobra, or the enormous ape? C for cobra, A for ape ')
        
        if choice_2.upper() == 'C':
            print 'Sorry, you were bit by the cobra and died'
            print 'Restarting game...\n'
            # 回到循环开头,重启整个游戏
            continue
        elif choice_2.upper() == 'A':
            print 'You were almost mauled by the ape, luckily, it fled the scene after losing sight of you'
            # 让玩家选择是否继续游戏
            play_again = raw_input('Do you want to play again? Y/N ')
            if play_again.upper() != 'Y':
                print 'Thanks for playing!'
                break
            else:
                print '\nRestarting game...\n'
                continue
        else:
            print 'Invalid choice, restarting game...\n'
            continue
    # 山丘分支逻辑
    elif choice_1.upper() == 'H':
        print 'Hill, good decision'
        # 山丘路线后续可以在这里扩展,先保留重启选项
        play_again = raw_input('Do you want to play again? Y/N ')
        if play_again.upper() != 'Y':
            print 'Thanks for playing!'
            break
        else:
            print '\nRestarting game...\n'
            continue
    # 处理无效输入
    else:
        print 'Invalid choice, please try again.\n'

关键修改说明

  • 主循环包裹:把整个游戏放在while True循环里,这是实现重启的核心——continue会直接回到循环开头,重新执行游戏初始化代码。
  • 输入大小写兼容:用upper()统一转换输入为大写,这样用户输入小写j/c也能被识别,提升体验。
  • 修复作用域问题:把choice_2的所有判断都放在if choice_1 == 'J'的代码块内,避免选Hill时出现NameError。
  • 明确重启逻辑:当用户选C(眼镜蛇)时,提示死亡后用continue直接重启游戏,完全符合你的需求。
  • 增加退出选项:添加Q选项让用户可以主动结束游戏,避免程序一直循环无法退出。
  • 无效输入处理:对所有不符合要求的输入给出提示,并引导重启或重新选择,让流程更流畅。

这样修改后,游戏就能完美实现预期功能,同时解决了原代码的其他逻辑漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:11:19