我想做什么:
我正在使用一个函数来 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 preferred 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')
我想知道是否有人可以为我指明正确的方向。
答案 0 :(得分:1)
您可以通过在 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
变量,不要这样做,因为它被认为是一种不好的做法。>