在python中,我正在尝试创建一个RPG,当我执行“def townbar()时:”它说它没有定义。
此代码仅供参考,以确保一切正常:
class Player:
def __init__(self, name):
self.name = name
self.health2 = 100
self.health = self.health2
self.attack = 10
# Game
def main():
print("Welcome player.")
print("1. Start")
print("2. Load")
print("3. Exit")
option = input("> ")
if option == "1":
start()
elif option == "2":
pass
elif option == "3":
sys.exit()
else:
main()
def start():
print('\n' * 80)
print("Hello, what is your name?")
option = input("> ")
global PlayerIG
PlayerIG = Player(option)
start1()
def start1():
print('\n' * 80)
print("Name: %s" % PlayerIG.name)
print("Attack: %i" % PlayerIG.attack)
print("Health: %i/%i\n" % (PlayerIG.health, PlayerIG.health2))
print("1. Go to nearby town")
print("2. Stand here and do nothing")
option = input("> ")
if option == "1":
town()
if option == "2":
print("Really? This is the guy we chose to be the hero of this story?
*sigh* Pick again.")
start1()
else:
start1()
def town():
print('\n' * 80)
print("You arrive at the town and you see 3 signs.\n")
print("1. Go to the bar")
print("2. Go to the market")
print("3. Go to the king")
option = input("> ")
if option == "1":
townbar()
elif option == "2":
market()
elif option == "3":
print("The king ignores you, as you are but a peasant\n")
town()
else:
town()
这是给我带来问题的部分,它说bar没有定义(这是城镇栏的旧名称)。在我更改名称并检查一切正常后,它仍然显示错误。
def townbar():
print('\n' * 80)
print("You see many people in the bar.")
print("1. Talk to the bartender")
print("2. Talk to the people in the bar")
print("3. Exit the bar")
option = input("> ")
if option == "1":
print("The bartender greets you.\n")
bartendertalk()
elif option == "2":
print("The people don't care enough or are too drunk to speak to
you.\n")
townbar()
elif option == "3":
town()
else:
townbar()
def bartendertalk():
print('\n' * 80)
print("Would you like to hear of the local news? [Y/N]")
option = input("> ")
if option == "Y":
print("Would you like to hear the gossip or some real news?\n")
print("1. Gossip")
print("2. Real news")
option2 = input("> ")
if option2 == "1":
print("I've heard that Ron has been cheating on Margaret with
Beatrice! Very sad.\n")
bartendertalk()
elif option2 == "2":
print("People talk of a destroyed castle holding centuries worth
of gold in there, but nobody has ever explored it.")
bartendertalk()
if option == "N":
print("Then why are you talking to me?\n")
townbar()
else:
bartendertalk()
main()
错误:
File "C:\Users\Leo\Documents\Loadingscreens\PyCharm Community Edition
2017.3.2\helpers\pydev\pydevd.py", line 1668, in <module>
main()
File "C:\Users\Leo\Documents\Loadingscreens\PyCharm Community Edition
2017.3.2\helpers\pydev\pydevd.py", line 1662, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Users\Leo\Documents\Loadingscreens\PyCharm Community Edition
2017.3.2\helpers\pydev\pydevd.py", line 1072, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Users\Leo\Documents\Loadingscreens\PyCharm Community Edition
2017.3.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 63, in
<module>
main()
File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 21, in
main
start()
File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 35, in
start
start1()
File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 46, in
start1
town()
File "C:/Users/Leo/PycharmProjects/RPG Project/Game File.py", line 57, in
town
bar()
NameError: name 'bar' is not defined
答案 0 :(得分:1)
这不是你问题的答案..因此在我再次删除它之前会得到一些downvotes; o)但如果你决定在整个地方使用这种菜单,你应该考虑将功能打包到其中功能如下:
def choicer(choices, onErrorMessage):
'''Uses a dict of choices to present a menue.
The menuChoice with key -1 is used as flavour text before
first input occures, the onErrorMessage (or if None the -1 option
is used for consecutive inputs after illegan user choice.
It returns the key of the option choosen.'''
def flavourTextOnInput():
'''print flavour text if present'''
if -1 in choices.keys(): # print flavour text if given:
print(choices[-1])
def printMenu():
''' print all choices without key -1'''
for key in choices:
if key != -1:
print(key, '. ', choices[key])
def inputNumber():
'''ask for input, convert to int else return None'''
num = None
numText = input()
try:
num = int(numText)
except:
pass
return num
flavourTextOnInput()
printMenu()
c = inputNumber()
while(c not in choices.keys()):
if onErrorMessage:
print(onErrorMessage)
else:
flavourTextOnInput()
c = inputNumber()
return c
并像这样使用它:
retVal = choicer({-1: "Howdy - what do you like to do?", # spezial by definition
1: "drink beer",
2: "drink whisky",
3: "get drunk by rum",
4: "hit some patron"}, # set of choices
"What'cha want? Too loud - not heard correctly") # onErrorMessage
# then you can handle retVar to your liking
您提供包含选项和错误消息的字典。 dict键-1
是特殊的,它在第一个输入()之前作为flavor文本打印。每次输入错误时都会打印onErrorMessage
。该函数返回所选选项的整数键,并将重复,直到输入有效选项。
你应该为Y / N答案做一个更容易的功能,它将一个字符串作为qestion和循环,直到答案是Y或N.你的主程序将变得不那么复杂,并且更容易跟踪一切正在发生 - 通过重用防故障功能来防止错误。
def yesNo(text):
'''Prints text once and repeats input until first non space character
is nN or yY - returns a True if yY else False. Ignores all other inputs
then the first non space one'''
print(text, " [Y/N]")
c = None
while (c not in ['Y','N']):
c = (input().strip()[0].upper()) # use 1st non space upper case character as input
return c == "Y" # else False
用法:
if yesNo("Quit now?"): # please rename the functions, naming is hackish
print("Quitting")
else:
print("continuing")
答案 1 :(得分:0)
如果townbar()
是类外的函数,则将其置于调用者之上,即town()
。这应该是它说功能没有定义的原因。应在调用者之前定义被调用者。