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

Python文本RPG开发中跨文件修改选定英雄属性功能失效如何解决

问题原因

你定义的character_attributes字典存储的是角色属性的值副本,Python中整数属于不可变类型,修改字典内的数值只会更新字典本身的内容,不会同步修改Hero类实例的对应属性,因此修改不会真正生效。

修复方案

方案1:直接操作实例属性(无需修改原Hero类定义)

通过getattr、setattr内置函数直接读写实例的属性,不需要额外存属性值副本,修改后的train函数如下:

def train(character):
    if character.attribute_points <= 0:
        print("Not enough attribute points")
        return
    # 定义缩写和Hero类真实属性名的映射
    attr_mapping = {
        "str": "strength",
        "dex": "dexterity",
        "end": "endurance",
        "mag": "magic"
    }
    print("Which attribute you want to train?")
    for abbr in attr_mapping:
        print(abbr)
    select = input(">>")
    if select in attr_mapping:
        # 读取原属性值+1后写回实例
        new_value = getattr(character, attr_mapping[select]) + 1
        setattr(character, attr_mapping[select], new_value)
        character.attribute_points -= 1
        print(f"Your {select} is now {new_value}")
    else:
        print("Invalid attribute")

方案2:属性统一存字典(扩展性更强)

如果后续需要频繁增减属性,建议修改Hero类定义,把所有属性统一存到一个字典字段中,后续修改直接操作字典即可:

class Hero:
    def __init__(self, Hstrength, Hdexterity, Hendurance, Hmagic, Hname, Hlocation):
        self.level = 1
        self.xp_needed = 100
        self.attribute_points = 0
        # 所有属性统一存储在字典中
        self.attrs = {
            "str": Hstrength,
            "dex": Hdexterity,
            "end": Hendurance,
            "mag": Hmagic
        }
        self.name = Hname
        self.location = Hlocation

对应的train函数简化为:

def train(character):
    if character.attribute_points <= 0:
        print("Not enough attribute points")
        return
    print("Which attribute you want to train?")
    for attr in character.attrs:
        print(attr)
    select = input(">>")
    if select in character.attrs:
        character.attrs[select] += 1
        character.attribute_points -= 1
        print(f"Your {select} is now {character.attrs[select]}")
    else:
        print("Invalid attribute")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:06:08