2016-11-26 3 views
-5

это моя программа палача. он возвращает «NameError: name« a »не определен». пожалуйста, помогите мне в исправлении этого. Большое спасибо.имя python не определено

import random 

invalid= [" ","'",".",",","'", '"', "/", "\ ", '"',";","[","]", "=", "-", "~", "`", "§","±","!","@","#","$","%","^","&","*","(",")","_","+","{","}","|",":","?",">","<","0","1","2","3","4","5","6","7","8","9"] 
choice = 0 

print("Welcome to HANGMAN!") 

def Menu(): 
    print("[1] Play Hangman") 
    print("[2] Instructions ") 
    print("[3] Highscores") 
    print("[4] Exit") 

    choice = int(input("Please choose from the Menu: ")) 
    if(not(choice <=4)): 
     print("Choose again.") 
     return Menu() 
    return choice 

while True: 
    choice = Menu() 
    if choice == 1: 
     print("Categories: ") 

     print("[1] Movies") 
     print("[2] Animals") 
     print("[3] Something Blue") 
     choice_category = int(input("Please Choose a Category: ")) 

     print("-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-0-") 

     print("Difficulties:") 

     print("[1] Easy") 
     print("[2] Average") 
     print("[3] Difficult") 
     choice_difficulty = int(input("Please Choose a Difficulty: ")) 

     superword = a(choice_category, choice_difficulty) 
     legitgame(superword) 

    elif choice == 2: 
     print("Let yourself be hanged by mistaking the letters.") 

    elif choice == 3: 
     readHandle = open("Scores.txt","r") 
     names = [] 
     for line in readHandle: 
      name = line[:-1] 
      names.append(name) 
     readHandle.close() 
     print() 
     Menu() 
    elif choice == 4: 
     print("Thank you for playing.") 
     Menu() 


hangman =["       ==========" 
      "  |  |" 
      "  O  |" 
      "    |" 
      "    |" 
      "   | ", 

      "  ==========" 
      "  |  |" 
      "  O  |" 
      "  |  |" 
      "   |" 
      "   | ", 

      "  ========== "  
      "  |  |" 
      "  O  |" 
      "  /|  |" 
      "    |" 
      "   | ", 

      "  ==========" 
      "  |  |" 
      "  O  |" 
      "  /|\  |" 
      "   |" 
      "   | ", 

      "  ==========" 
      "  |  |" 
      "  O  |" 
      "  /|\  |" 
      " / |" 
      "   | ", 

      "  ==========" 
      "  |  |" 
      "  O  |" 
      "  /|\  |" 
      " /\  |" 
      "   | "] 

#definition функция для различных опций в конкретной категории и сложности
четкости с (choice_category, choice_difficulties):

if choice_category == 1: 
     readHandle = open("movies.txt", 'r') 
     lines = readHandle.readlines() 
    elif choice_category == 2: 
     readHandle = open("animals.txt", 'r') 
     lines = readHandle.readlines() 
    elif choice_category == 3: 
     readHandle = open("something blue.txt", 'r') 
     lines = readHandle.readlines() 
    else: 
     print("Please choose again.") 


    if choice_difficulty == 1: 
     word = (lines[0]) 
    elif choice_difficulty == 2: 
     word = (lines[1]) 
    elif choice_difficulty == 3: 
     word = (lines[2]) 
    else: 
     print("Please enter valid characters.") 





    legitword = word[:-1].split(".") 
    return (random.choice(legitword)) 


def legitgame (meh): 

    length = "__" * len(meh) 
    characters = [] 
    mistake = 0 

    while mistake < 6 and length != meh: 
     print(hangman[mistake]) 
     print(length) 
     print("Number of wrong guesses: ", mistake) 

     guess = (input("Guess:")).upper() 


     while len(guess) != 1: 
      print("You have inputted multiple letters. Please input a single letter.") 
      guess = input("Guess: ").upper() 

     while guess in invalid: 
      print("You have inputted an invalid character. Please try again.") 
      guess = input ("Guess: ").upper() 

     while guess in characters: 
      print("You have already inputted this letter. Please try again.") 
      guess= input("Guess: ").upper() 


     if guess in meh: 
      print() 
      print("Fantastic! You have entered a correct letter.") 
      characters.append(guess) 
      correct = "" 

      for x in range (0,len(meh)): 
       if guess == meh[x]: 
        correct += guess 
       else: 
        correct += length[x] 
      length = correct 

     else: 
      character.append(guess) 
      print("Sorry. You have inputted an incorrect letter. Please try again.") 
      mistake += 1 

     if mistake >= 6: 
      print(hangman[6]) 
      print("The correct word is: ", meh) 
      print("Sorry. You killed the guy. Your conscience is chasing you.") 
      print("Game over") 

     elif correct == meh: 
      print("Congratulations! You saved the puny man.") 
      print("You have guessed ", word, "correctly!") 
      win() 
     Menu() 

def win(): 
    readHandle = open("Scores.txt", "a") 
    name = input("Enter your name: ") 
    readHandle.write(name + "\n") 
    readHandle.close 

menu() 
+5

В чем ваш вопрос? Какова максимальная трассировка вашей ошибки? И ваш код нуждается в большем контексте, показывая нам, где определен 'legalgame()'. Пожалуйста, прочитайте [Как создать минимальный, полный и проверенный пример] (http://stackoverflow.com/help/mcve). –

+0

В чем вопрос HOMEWORK? – Inconnu

+0

Прошу прощения за неполноту. это часть моего кода палача. он также является источником NameError: имя 'a' не определено. пожалуйста, помогите мне в исправлении этого. Спасибо. – Questioner

ответ

0

Я не могу точно сказать, со всем кодом, но из данный код Я предполагаю, что ошибка заключается в том, что вы вызываете a(choice_category, choice_difficulty), прежде чем определили его. Поместите def a(... перед тем superword = a(choice_category, choice_difficulty), и вы должны быть хорошо идти (если это действительно проблема)

+0

Я уже разместил полный код – Questioner

0

«а» по-видимому, функция в вашей программе, как у вас есть:

def a(choice_category, choice_difficulty) 

Эта строка определяет " а»функция, которая требует 2 аргумента (choice_category и choice_difficulty)

вы должны определить функцию, прежде чем вы можете использовать его

программы вы зовёт/с помощью функции этой линии

superword = a(choice_category, choice_difficulty) 
Смежные вопросы