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

如何在游戏主菜单中添加可随时退出游戏的Exit函数?

实现游戏全局退出功能并集成到主菜单

第一步:定义退出函数

先导入sys模块实现程序退出,再编写退出函数:

import sys
from colorama import Fore  # 假设你已导入colorama模块

def exit_game():
    print_slow(Fore.RED + "感谢游玩,再见!" + Fore.RESET)
    sys.exit()

第二步:更新主菜单,添加退出选项

修改你的main_menu函数,补充退出指令说明,并加入输入循环处理用户操作:

def main_menu():
    # 打印游戏介绍与操作说明
    print_slow(Fore.BLUE + "屠龙冒险游戏")
    print_slow("你是屠龙者琼恩·雪诺")
    print_slow("丹妮莉丝·坦格利安正用她的巨龙挟持着整个小镇")
    print_slow("你被劳勃·拜拉席恩国王召唤,前来斩杀巨龙卓耿")
    print_slow("你必须收集全部6件物品才能斩杀卓耿,否则将葬身火海。")
    print_slow("移动指令:go South, go North, go East, go West")
    print_slow("收集物品:get '物品名称'")
    print_slow("退出游戏:exit" + Fore.RESET)

    # 主菜单输入循环
    while True:
        user_input = input("\n请输入指令:").strip().lower()
        if user_input == "exit":
            exit_game()
        elif user_input == "start":
            print_slow(Fore.GREEN + "开启你的屠龙之旅!" + Fore.RESET)
            break  # 退出菜单循环,进入游戏主逻辑
        else:
            print_slow(Fore.YELLOW + "无效指令,请重新输入!" + Fore.RESET)

第三步:确保游戏过程中随时可退出

在游戏主循环的输入处理环节,同样加入exit指令判断:

def game_loop():
    # 游戏初始化(示例)
    current_location = "小镇广场"
    inventory = []

    while True:
        # 显示当前状态
        print(f"\n当前位置:{current_location}")
        print(f"背包物品:{inventory}")
        
        user_input = input("\n请输入指令:").strip().lower()
        if user_input == "exit":
            exit_game()
        # 处理移动、收集物品等其他游戏逻辑
        # ...

这样无论在主菜单还是游戏进行中,用户输入exit就能触发退出函数,直接结束游戏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:18:26