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

Python文本游戏导入错误:无法从Race模块导入character_name

解决文本游戏角色创建阶段的ImportError及相关逻辑问题

错误根源

你遇到的ImportError: cannot import name 'character_name' from 'Race',核心原因是:

  • Race.py中根本没有定义character_name这个可被导入的变量/函数,里面只有dwarf()函数,且函数内的plyer_name是拼写错误(应为player_name),还是局部变量,无法被外部模块导入。
  • 代码逻辑存在变量作用域、流程传递的问题,导致角色信息无法在模块间正确共享。

修复方案

步骤1:修正Race.py的拼写错误,让种族函数返回角色信息

把拼写错误的plyer_name改为player_name,并让dwarf()函数返回种族和名字,方便后续模块接收:

# Race.py
def dwarf():
    player_race = 'Dwarf'
    player_name = input(f"What is your name {player_race}? > ")
    # 返回种族和名字,供其他模块使用
    return player_race, player_name

步骤2:修改Race_Selection.py,接收角色信息并传递给character_creation

在race_choice()中调用dwarf()后,获取返回的种族和名字,再传递给character_creation():

# Race_Selection.py
from elf import elfinfo
from dwarf import dwarfinfo
from giant import giantinfo
from goblin import goblininfo
from human import humaninfo
from minotaur import minotaurinfo
from orc import orcinfo
from troll import trollinfo
from vampier import vampireinfo
from millennial_vampire import millennialvampireinfo
from Race import dwarf
from Character_Creation import character_creation

def race_info():
    print("You can choose from the following Races below.")
    print("To learn more about the available races type the race name with a '?' after")
    print("\nPress 'q' at any time to quit")

def race_choice():
    print("\nPlease Choose From The Races Below\nDwarf\nElf\nGiant\nGoblin\nHuman\nMinotaur\nOrc\nTroll\nVampire\nMillennial Vampire")
    player_race = input("What is your race? > ")
    if player_race == 'Dwarf?':
        dwarfinfo()
        race_choice()
    elif player_race == 'Elf?':
        elfinfo()
        race_choice()
    elif player_race == 'Giant?':
        giantinfo()
        race_choice()
    elif player_race == 'Goblin?':
        goblininfo()
        race_choice()
    elif player_race == 'Human?':
        humaninfo()
        race_choice()
    elif player_race == 'Minotaur?':
        minotaurinfo()
        race_choice()
    elif player_race == 'Orc?':
        orcinfo()
        race_choice()
    elif player_race == 'Troll?':
        trollinfo()
        race_choice()
    elif player_race == 'Vampire?':
        vampireinfo()
        race_choice()
    elif player_race == 'Millennial Vampire?':
        millennialvampireinfo()
        race_choice()
    elif player_race == 'q':
        exit()
    elif player_race == 'Dwarf':
        # 获取种族和名字
        race, name = dwarf()
        # 传递参数给角色创建函数
        character_creation(race, name)
    else:
        print("That is not a valid selection")
        race_choice()

把多个if改为elif,避免无效判断,提升代码效率

步骤3:重构Character_Creation.py,移除错误导入,接收参数并生成文件

删掉错误的导入语句,修改函数接收种族和名字参数,去掉不必要的嵌套函数,用更安全的方式操作文件:

# Character_Creation.py
def character_creation(player_race, player_name):
    # 可选:让用户确认名字,为空则使用之前输入的名字
    character_name = input(f"Confirm your name {player_race.title()}? ({player_name}) > ") or player_name
    try:
        # 使用with语句自动管理文件资源
        with open(f"{character_name.title()}.txt", "x") as f:
            f.write(f"Player Name: {character_name.title()}\nPlayer Race: {player_race.title()}")
        print(f"Character file {character_name.title()}.txt created successfully!")
    except FileExistsError:
        print(f"Error: Character file {character_name.title()}.txt already exists!")

步骤4:调整Main_Menu.py的流程

因为race_choice()现在会直接调用character_creation(),所以移除重复的导入和调用:

# Main_Menu.py
from Race_Selection import race_info, race_choice

def main_menu():
    print("Hello!! And welcome to Norubia. Please Choose your race.")
    race_info()
    race_choice()

额外优化建议

  • 对用户输入做大小写统一处理(比如player_race = input(...).strip().capitalize()),避免因大小写导致的无效选择。
  • 用字典映射种族名到对应的信息函数,减少重复的elif代码,比如:
    race_info_map = {
        'Dwarf?': dwarfinfo,
        'Elf?': elfinfo,
        # 其他种族映射...
    }
    if player_race in race_info_map:
        race_info_map[player_race]()
        race_choice()
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:30:47