NameError:未定义名称“字符”

some_user_3

我正在尝试做的是:

我正在对pickle包含字符统计信息的字典使用函数我定义了一个字典,定义了字符统计信息,如下所示:

character = {'health': health, 'damage': damage, 'shield': shield, 'magic': magic, 'luck': luck, 'name': name}

然后,我要求用户输入以告知程序用户想要调用其保存文件的内容,然后使用我的save_character函数进行保存。

用户输入:

character_file_name = input('> ')
save_character(character_file_name)

保存字符功能如下所示:

def save_character(save_name):
    save_name_pickle = save_name + '.pickle'
    type('> saving character')
    w(1)
    with open(save_name_pickle, 'wb') as f:
        pickle.dump(character, f)
        type('> character saved successfully')

问题:

如果我运行该程序,并要求输入文件名,则会返回名称错误:

NameError: name 'character' is not defined

即使我可以看到已经定义了这个。

完全回溯错误:

  File "C:\Users\sbenf\OneDrive\Python Projects\Large Projects\Adventure_Colussus_Game\adventure_colussus.py", line 166, in <module>
    character_generator()
  File "C:\Users\sbenf\OneDrive\Python Projects\Large Projects\Adventure_Colussus_Game\adventure_colussus.py", line 133, in character_generator
    save_character(character_file_name)
  File "C:\Users\sbenf\OneDrive\Python Projects\Large Projects\Adventure_Colussus_Game\adventure_colussus.py", line 40, in save_character
    pickle.dump(character, f)
NameError: name 'character' is not defined

完整代码:

from os import system
from ascii_art_functions import mountain_range
from ascii_art_functions import character_selection_horse_and_knight
from ascii_art_functions import screen_line

import random
import math
import time
import datetime
import pickle
import sys
import os

#miscellaneous functions + procedures

def w(t):
    time.sleep(t)

def version_counter(filename="adventure_colussus_version_counter.dat"):
    with open(filename, "a+") as f:
        f.seek(0)
        val = int(f.read() or 0) + 1
        f.seek(0)
        f.truncate()
        f.write(str(val))
        return val
counter = version_counter()

def type(text):
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(0.021)

def save_character(save_name):
    save_name_pickle = save_name + '.pickle'
    type('> saving character')
    w(1)
    with open(save_name_pickle, 'wb') as f:
        pickle.dump(character, f)
        type('> character saved successfully')

def load_character(load_name):
    load_name_pickle = load_name + '.pickle'
    type('> loading character...')
    w(1)
    with open(load_name_pickle, 'rb') as f:
        character = pickle.load(f)
        type('> character loaded successfully\n')
        type('n> welcome back ')
        type(character['name'])
        type('!!!\n')
        w(0.5)
        type('\n> here are your stats from last time: ')
        type(character)



def character_generator():
    type('\n > we have reached the first crucial part of your journey: we must choose the path that you will take! the decision\n')
    w(0.5)
    type(' > is up to you my friend! Whether you choose to be a bloodthisty warrior or a cunning and strategic fighter,\n')
    w(0.8)
    type(' > the choice is yours!\n')
    w(0.5)
    type('\n > now then, lets get right into it!')
    w(0.8)
    type(' are you more of a tanky player[1] or a strategic player[2]?')
    
    player_type_choice_1 = input('\n > ')

    if player_type_choice_1 == '1':
        health = 100
        damage = 75

    elif player_type_choice_1 == '2':
        health = 75 
        damage = 50

    type('\n > so, we have that out of the way, lets carry on!')
    w(0.8)
    type(' oh of course! sorry to forget! another quick question: ')
    w(0.5)
    type('do you like \n')
    type(' > to use magic from great distances[1] or run in to the thick of battle weilding a deadly blade[2]? ')

    player_type_choice_2 = input('\n > ')

    if player_type_choice_2 == '1':
        shield = 50
        magic = 75

    elif player_type_choice_2 == '2':
        shield = 75 
        magic = 45

    type('\n > good good! we have decided your play style and your preffered ways of attacking the enemy!\n')
    w(0.5)
    type(' > now, we must see what luck we are able to bestow upon you. be warned: it is entirely random!\n')
    w(0.8)
    random_luck = input('\n > press enter to roll a dice...')
    w(0.3)
    type(' > rolling dice...\n')
    luck = random.randint(0,10)
    w(1)
    print(' > your hero has',luck,'luck out of 10!')
    w(0.8)
    type('\n > we have reached the most important part of creating your character! The naming!\n')
    type(' > choose wisely. your hero will be named this for the rest of their lives...\n')
    w(1)

    type('\n > what should your hero be named?\n ')
    name = input('> ')
    w(1)
    type('\n > welcome mighty hero! you shall be named: ')
    type(name)
    type(' !!!\n')
    type(' > a fine choice')
    type('\n')

    type(' \n > now then. i guess you be on your way! you have a journey to start and a belly to fill!\n')
    type(' > i have to say, i have rather enjoyed your company! feel free to come by at any time!\n ')
    type('> goodbye and god speed!')
    w(1)
    print('\n')
    type(' > your final stats are as follows: \n')
    w(0.3)
    print(' >', '[', 'health:', health, ', damage:',  damage, ', shield:', shield, ', magic:', magic, ', luck:', luck, ', name:', name, ']')
    type('\n > we should now save your character if you want to come back to it later:\n ')

    character = {'health': health, 'damage': damage, 'shield': shield, 'magic': magic, 'luck': luck, 'name': name}
    character_file_name = input('> ')
    save_character(character_file_name)



# main game        

w(0.5)
e = datetime.datetime.now()
screen_line()
print('\n  <Adventure Colussus>         version: v',counter,'| current date: ',e, '| date of creation: 9.2.2021')
screen_line()
w(0.5)
mountain_range()
screen_line()
print('\n > [1] create new game')
print(' > [2] load existing game')
print(' > [3] end game')
print(' > [4] credits')
choice = input("\n > ")

if choice == '1':

    type("\n > you have chosen to create a new game: redirecting...")
    w(0.75)
    system('cls')
    screen_line()
    print('  \n  we will begin with creating your character:                                        quick tip: choose wisely')
    screen_line()
    w(0.5)
    character_selection_horse_and_knight()
    screen_line()
    w(0.3)
    
    character_generator()




elif choice == '2':

    type("\n > you have chosen to load an existing game: redirecting...")
    w(0.75)
    system('cls')
    w(0.5)
    screen_line()
    print('  \n  we will begin with choosing an existing character:                             quick tip: make sure it exists!')
    screen_line()
    w(0.5)
    character_selection_horse_and_knight()
    screen_line()
    

    character_file_name = input('> character file name: ')
    load_character(character_file_name)



elif choice == '3':

    type(' > ending session...')
    w(0.5)
    type(' > session ended successfully')
    w(1)
    sys.exit()

elif choice == '4':
    pass

else:
    type('incorrect response. please try again')
    

我想知道是否有人可以指出我正确的方向。

安禅

您可以通过在save_character函数中添加另一个参数来解决此问题,以便character在调用函数时必须将变量传递到方括号中:

def save_character(save_name, character):
    save_name_pickle = save_name + '.pickle'
    type('> saving character')
    w(1)
    with open(save_name_pickle, 'wb') as f:
        pickle.dump(character, f)
        type('> character saved successfully')

在调用该函数的代码上,

    character = {'health': health, 'damage': damage, 'shield': shield, 'magic': magic, 'luck': luck, 'name': name}
    character_file_name = input('> ')
    save_character(character_file_name)

像这样character变量插入save_character函数的括号中:

    character = {'health': health, 'damage': damage, 'shield': shield, 'magic': magic, 'luck': luck, 'name': name}
    character_file_name = input('> ')
    save_character(character_file_name, character)

上面是处理此问题的正确方法,但是另一种方法是global用于全局化character变量,请勿执行此操作,因为这被认为是不好的做法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

NameError:未定义名称“字符”

来自分类Dev

NameError:名称“ a”未定义

来自分类Dev

nameError 名称未定义

来自分类Dev

Paraview:NameError:未定义名称“输入”

来自分类Dev

NameError:全局名称'numpy'未定义

来自分类Dev

NameError:名称“ datetime”未定义

来自分类Dev

模块导入:NameError:名称未定义

来自分类Dev

NameError:未定义名称“ StaticLiveServerCase”

来自分类Dev

NameError:名称“ __main__”未定义

来自分类Dev

PySNMP NameError:未定义名称“ getCmd”

来自分类Dev

NameError:即使未定义名称“ self”?

来自分类Dev

Python:NameError:未定义名称“ Stack”?

来自分类Dev

NameError:名称“ true”未定义

来自分类Dev

NameError:名称“ requests”未定义

来自分类Dev

NameError:未定义名称“ ABNF”

来自分类Dev

NameError:名称“ RegexValidator”未定义

来自分类Dev

NameError:未定义名称“随机”

来自分类Dev

NameError:未定义名称“ BillPayer”

来自分类Dev

NameError:未定义名称“菜单”

来自分类Dev

熊猫NameError:未定义名称'合并'

来自分类Dev

NameError:未定义名称“ Usuario”

来自分类Dev

NameError:未定义名称“烧瓶”

来自分类Dev

修改脚本:NameError:名称“”未定义

来自分类Dev

Django NameError:未定义名称“ forms”

来自分类Dev

Python错误NameError:未定义名称“ ...”

来自分类Dev

NameError:名称“系列”未定义

来自分类Dev

NameError:名称“年龄”未定义

来自分类Dev

NameError:名称“ __file__”未定义

来自分类Dev

NameError:名称未定义全局声明