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

Python冒险游戏开发:如何触发指定if语句执行逻辑

解决Python冒险游戏中的逻辑复用问题

你的核心需求是让用户从河岸返回后选择过桥时,触发和第一次选桥相同的成功逻辑。最简洁且易维护的方式是把重复的逻辑封装成函数,具体实现如下:

重构后的代码

# 封装过桥成功的逻辑为函数
def cross_bridge():
    print('you have crossed the bridge congrats ! ')

name = input('what is your name : ')
print(f'welcome {name} to this game ! ')
choice = input('do you want to play the game ? ')

if choice.lower() == 'y':
    print('ok , cool ! ')
else :
    print('bye')
    exit()  # 用户不玩时直接退出,避免执行后续流程

advent = input('there is a road . do you want to go left or right ? ')
if advent.lower() == 'left':
    path = input('you have reached an river . do you want to swim or cross a bridge ? ')

    if path.lower() == 'bridge':
        cross_bridge()  # 第一次选桥时调用函数
    elif path.lower() == 'swim':
        croc = input('now you are swimming . oops ! there is a crocodile . what do you want to do ? ')
        if croc.lower() == 'go back to the river bank':
            bank_path = input('now you are in the river bank and do you want to cross the bridge ? ')
            if bank_path.lower() == 'cross the bridge':
                cross_bridge()  # 从河岸返回选桥时,同样调用函数触发逻辑
        elif croc.lower() == 'go ahead':
            print('you are ded -_- ! . The croc ate you ')

关键改进点

  • 函数封装:把过桥成功的打印逻辑放到cross_bridge()函数中,任何需要触发该逻辑的地方直接调用函数即可,避免重复写代码,也解决了"跳转"逻辑的需求。
  • 修复缩进问题:原代码中第12行的if path没有缩进在if advent块内,会导致用户选right时path未定义报错,重构后修正了缩进。
  • 添加退出逻辑:用户选择不玩游戏时,用exit()终止程序,避免执行后续的冒险流程。
  • 使用elif替代独立if:减少不必要的条件判断,让逻辑更清晰。

如果你不想用函数,也可以直接把print('you have crossed the bridge congrats ! ')复制到第19行的位置,但这种方式会产生重复代码,后续修改逻辑需要改两处,不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:45:36