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

Python冒险游戏开发:函数间属性传递及值/EOL错误解决

解决方案:属性全局化与输入错误修复

一、解决属性跨函数传递问题

你的核心问题是全局变量被函数参数遮蔽,且提前调用story()导致用初始0值执行。修改方案如下:

  • 移除Point_sys和story函数的属性参数,直接操作全局变量
  • 在Point_sys内用global声明要修改的全局属性,将滑块赋值同步到全局变量
  • 删除开头直接调用story()的代码,让剧情仅在玩家完成属性分配后触发

二、解决输入相关错误

你遇到的invalid literal for int() with base 10: 'Lift'是因为错误地对字符串输入执行了int()转换,完全没必要。优化方案:

  • 不要对用户输入的命令字符串做整数转换
  • 统一输入的大小写(比如转成大写),兼容用户输入lift/LIFT等情况
  • 增加默认分支,处理非预期输入

修改后的完整代码

from ipywidgets import interact_manual, widgets
from IPython.display import display, HTML

# 全局属性变量
Strength = 0
Perception = 0
Luck = 0
Agility = 0  # 统一变量名首字母大写,保持风格一致

print("This is the skill tree, whichever abilities you invest in shall change the story and what you are able to do and how you solve situations and fight. Strength allows one to wield bigger weapons, solve situations with brute force, and will make fights easier. Perception allows secrets, chests, and many secret items to be found, and solutions ones with lesser perception might not spot otherwise. Luck allows certain situations to be bypassed, enemies to miss, and is the wild card of the abilities. Agility allows to bypass situations using acrobatics, and is useful in every situation. Create your character how you want, as long as the points add up to 20")

def Point_sys():
    # 声明要修改的全局变量
    global Strength, Perception, Luck, Agility
    # 计算总属性点
    P_all = Strength + Perception + Luck + Agility
    if P_all != 20:
        display(HTML('<h1>Error! make sure all the points add up to 20</h1>'))
    else:
        display(HTML('<h1>Character correctly made, loading game</h1> '))
        # 分配完成后启动剧情
        story()

# 配置滑块并绑定到全局变量
interact_manual(Point_sys, 
                Strength=widgets.IntSlider(min=0, max=20, step=1, value=0),
                Perception=widgets.IntSlider(min=0, max=20, step=1, value=0),
                Luck=widgets.IntSlider(min=0, max=20, step=1, value=0),
                Agility=widgets.IntSlider(min=0, max=20, step=1, value=0))

def story():
    choice = input("Do you want to lift the weight? (Enter 'Lift' to try, anything else to leave): ").strip().upper()
    if choice == 'LIFT':
        if Strength >= 17:
            print("You lifted the weight with ease!")
        else:
            print("You strain and fail to lift the weight - you're too weak!")
    else:
        print("You decide to leave the weight be and move on.")

# 不再提前调用story,由Point_sys在属性分配完成后触发

关键修改说明

  1. 全局变量处理:通过global关键字在函数内声明要修改的全局属性,确保滑块的值能同步到全局,供后续剧情函数使用
  2. 输入优化:用.strip().upper()统一输入格式,避免大小写问题;明确提示用户输入内容,增加容错分支
  3. 逻辑修正:删除了初始的story()调用,确保剧情仅在玩家完成属性分配后启动,使用正确的属性值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:53:19