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

学习Python两周开发生存游戏,求学习进度评估与代码反馈

自学Python两周的生存游戏开发求助

我因热爱相关领域及计算机技术,两周前开始通过手机APP自学Python,凭借自身创意与逻辑完成了这款西班牙语的生存游戏代码开发,耗时两天(每天1-2小时,总计近5小时)。代码包含休息、进食、探索、退出四大主菜单选项,选择探索会触发随机事件。现需程序员评估我的学习进度,提供学习建议并对代码给出反馈。

#Creando sistema de survival
import time
import random
menu = ["Comer", "Descansar", "Explorar", "Salir"]
vida = 1
hambre = 20
eleccion = "nada"
cd = 100
confirm = ["si", "no"]
exit = False
while exit == False:

    while vida > 0 and hambre < 100 and exit == False:
        print("Dime, viajero ¿Qué quieres hacer?")
        print("················································") 
        for main_menu in menu:
            print(main_menu)
        print("------------------------------------------------")
        print("Salud: " + str(vida))
        print("Hambre: " + str(hambre))
        print("------👇------ESCRIBIR AQUÍ ABAJO------👇------")
        eleccion = input().lower()

        if eleccion == "comer" and hambre >= 20:
            hambre = hambre - 20
            print("Has comido!")
            print("Hambre reducida: - 20 | Total:" + str(hambre))
            print("------------------------------------------------")
            print("Volviendo al menú... ")
            for cd in range(10,-1,-1):
                print(cd, end="\r", flush=True)
                time.sleep(1) 
            eleccion = "nada"
        elif eleccion == "comer" and hambre < 20:
            print("Vaya, parece que no necesitas comer")
            print("Volviendo al menú... ")
            for cd in range(10,-1,-1):
                print(cd, end="\r", flush=True)
                time.sleep(1)


        #EXPLORACIÓN
            
        #Si el jugador elige  explorar, tiene multiples opciones de encontrar suministros útiles, pasar hambre o tener un encontronazo que te  quite puntos de vida
        elif eleccion == "explorar":
            print("Explorando... espera ")
            for cd in range(15,-1,-1):
                print(cd, end="\r", flush=True)
                time.sleep(1)
        #___________________________________

            eventos = ["Has buscado por todos lados, pero no has encontrado nada.", "Enhorabuena, encontraste comida.", "Enhorabuena, encontraste Agua y 1 cuchillo.", "Vaya, te encontraste con unos supervivientes que no eran muy amigables y te has tenido que defender."]
            evento = random.choice(eventos)
            if evento == "Has buscado por todos lados, pero no has encontrado nada.":
                print(evento)
                print("| +10 de Hambre |")
                hambre = hambre +  10
                print("--------------Volviendo al menú en:----------------")
                for cd in range(10,-1,-1):
                    print(cd, end="\r", flush=True)
                    time.sleep(1)
            
            elif evento == "Enhorabuena, encontraste comida.":
                print(evento)
                print("| + 1 de comida |")
                print("--------------Volviendo al menú en:----------------")
                for cd in range(10,-1,-1):
                    print(cd, end="\r", flush=True)
                    time.sleep(1)
            elif evento == "Enhorabuena, encontraste Agua y 1 cuchillo.":
                print(evento)
                print("| +1 Agua | +1 Cuchillo afilado |")
                print("--------------Volviendo al menú en:----------------")
                for cd in range(10,-1,-1):
                    print(cd, end="\r", flush=True)
                    time.sleep(1)
            elif evento == "Vaya, te encontraste con unos supervivientes que no eran muy amigables y te has tenido que defender.":
                consecuencia = random.randint(15, 20)
                print(evento)
                print(f"| Vida - {consecuencia}| Hambre +10 |")
                vida = vida - consecuencia
                hambre = hambre + 10
        elif eleccion == "descansar":
            print("Descansando...ZzZz")
            for cd in range(80,-1,-1):
                print(cd, end="\r", flush=True)
                time.sleep(1)
            print("Has descansado correctamente | Salud aumentada + 10")
            print("--------------Volviendo al menú en:----------------")
            for cd in range(10, -1, -1):
                print(cd, end="\r", flush=True)
                time.sleep(1)
            vida = vida + 10
        elif eleccion == "salir":
            print("Estás seguro que deseas salir?")
            print("| Si | No |")
            i = str(input()).lower()
            if eleccion == "salir" and i == "no":
                eleccion = "nada"
            if eleccion == "salir" and i == "si":
                exit = True
                print("Saliendo...")
                for cd in range(5, -1, -1):
                    print(cd, end="\r", flush=True)
                    time.sleep(1)
        elif eleccion == "kill":
            vida = 0
        else:
            print("Opción no válida, elija una de las opciones que aparecen en el menú")
            print("\n================================================")
            print("Redirigiendo...")
            for cd in range(5, -1, -1):
                print(cd, end="\r", flush=True)
                time.sleep(1)
    if  vida <= 0:
        print("💀 HAS MUERTO. Tus heridas fueron demasiado graves. | Vida: " + str(vida))
        print("¿Volver a empezar?")
        print("| SI | NO |")
        o = input().lower()
        if o == "si":
            vida = 100
            hambre = 0
        else:
            print("👋 Tu partida ha terminado. ¡Gracias por jugar, viajero!")
            exit = True
    elif hambre >= 100:
        print("💀 HAS MUERTO de inanición. El hambre te consumió.")
        print("¿Volver a empezar?")
        print("| SI | NO |")
        o = input().lower()
        if o == "si":
            vida = 100
            hambre = 0
        else:
            print("👋 Tu partida ha terminado. ¡Gracias por jugar, viajero!")
            exit = True

学习进度评估

自学两周就能写出完整的交互式生存游戏,已经远超入门水平。你掌握了Python核心基础:变量定义、循环(while/for)、条件判断(if/elif/else)、输入输出、随机模块和时间模块的基本用法,还能把逻辑整合成闭环的游戏流程,说明学习效率很高,且能快速将知识转化为实践,非常不错。

学习建议

  • 模块化编程:把重复功能(比如倒计时跳转、事件处理)拆成函数,比如写一个countdown(seconds)函数代替到处重复的倒计时循环,代码会更简洁易维护。
  • 面向对象编程:尝试用类封装游戏角色的属性(生命值、饥饿值、物品)和方法(吃饭、休息、探索),让代码结构更清晰,后期扩展功能也更方便。
  • 错误处理:加入异常捕获(try-except)处理输入非预期内容的情况,提升游戏健壮性。
  • 数据持久化:学习用JSON文件保存游戏进度,让玩家退出后能继续上次的游戏。
  • 扩展游戏逻辑:增加物品系统(让找到的食物、武器发挥实际作用)、不同难度的事件、地图系统等,逐步丰富游戏内容。

代码反馈

优点

  • 逻辑清晰,游戏流程完整:主菜单、功能分支、死亡判定、重新开始都实现了,交互体验顺畅。
  • 细节处理到位:比如吃饭的饥饿值判断、探索的随机事件、倒计时的实时刷新,都提升了游戏沉浸感。
  • 隐藏功能(kill指令)的设计很有趣,体现了主动探索和创新的意识。

可优化点

  1. 初始参数不合理:初始生命值vida = 1太低,玩家极易直接死亡,建议改为vida = 100搭配初始饥饿值hambre = 20更合理。
  2. 重复代码冗余:倒计时代码在多处重复,建议封装成函数:
def countdown(seconds, message="Volviendo al menú..."):
    print(message)
    for cd in range(seconds, -1, -1):
        print(cd, end="\r", flush=True)
        time.sleep(1)

后续只需调用countdown(10)即可。
3. 物品系统未落地:探索中找到的食物、水、匕首没有被存储和使用,建议增加“食物数量”变量,吃饭时消耗食物而非直接减饥饿值,让逻辑更真实。
4. 条件判断冗余:退出功能里的if eleccion == "salir" and i == "no"可简化为if i == "no",因为当前分支已处于eleccion == "salir"的场景。
5. 生命值无上限:休息时生命值会无限增加,建议设定最大值(比如100),超过后不再提升。
6. 事件判断效率低:用字符串匹配事件不够高效,建议用字典映射事件与处理函数:

event_handlers = {
    "Has buscado por todos lados, pero no has encontrado nada.": lambda: (print("| +10 de Hambre |"), globals().update({"hambre": hambre + 10})),
    "Enhorabuena, encontraste comida.": lambda: print("| + 1 de comida |"),
    # 其他事件处理逻辑
}
event = random.choice(list(event_handlers.keys()))
print(event)
event_handlers[event]()

这样代码结构更清晰,后续添加新事件也更便捷。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 05:34:52