2017-12-30 3 views
-2

Pythonでは、私はRPGを作成しようとしています。私が "def townbar()"を実行するとき、定義されていないと言います。Python - 関数が定義されていません

このコードは、すべてが意味を作っていることを確認するために参照するためのものです:

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() 

は、これは私の問題を与える部分であり、それは(それがtownbarの古い名前だった)バーが定義されていないことを言います。私は名前を変更し、すべてが問題ないことを確認した後、それでもエラーが表示されます。

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() 

エラー:townbar()はクラスの外の関数がある

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

たちにスタックトレースを表示します。そしてあなたのコードを適切にフォーマットしてください。 – ubadub

+0

美しいコード - 今すぐ正しくフォーマットしてください。これを行う簡単な方法は、インデントをスペースに変更し、ここにコピーし、** {} **形式を使用することです。現在のところ、コードインデントが乱れており、Pythonにとって重要なことです。 –

+0

@PatrickArtnerより簡単な方法があります。私は彼のために編集提案として提出しました。つまり、関数定義をインデントして中括弧を使ってすべてを取り消します。 – ubadub

答えて

0

場合、town()すなわち、発信者の上にそれを置きます。これは、関数が定義されていないと言っている理由です。呼び出し先は、呼び出し元の前に定義する必要があります。

+0

私はこれを試した、それは動作しませんでした – lldrem22

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は特別で、最初のinput()の前にフレーバーテキストとして出力されます。 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") 
関連する問題