我如何修复Python 3中的刽子手游戏中的错误

时间:2016-02-09 09:22:38

标签: python python-3.x

此代码来自我过去一天左右工作的小游戏,我知道我不应该发布整个代码,但我不完全确定哪部分代码不能正常工作打算,任何帮助将不胜感激。代码是一个刽子手游戏,我知道代码中有大量的重复,但我不确定如何将它减少到适用于每个难度设置的每个函数之一。

import random
import time


#Variables holding different words for each difficulty
def build_word_list(word_file):
    words = [item.strip("\n") for item in word_file]
    return words

EASYWORDS = open("Easy.txt","r+")
MEDWORDS = open("Med.txt","r+")
HARDWORDS = open("Hard.txt","r+")
INSANEWORDS = open("Insane.txt", "r+")

easy_words = build_word_list(EASYWORDS)
medium_words = build_word_list(MEDWORDS)
hard_words = build_word_list(HARDWORDS)
insane_words = build_word_list(INSANEWORDS)



#Where the user picks a difficulty
def difficulty():

    print("easy\n")
    print("medium\n")
    print("hard\n")
    print("insane\n")

    menu=input("Welcome to Hangman, type in what difficulty you would like... ").lower()
    if menu in ["easy", "e"]:
        easy()

    if menu in ["medium", "med", "m"]:
        med()

    if menu in ["hard", "h"]:
        hard()

    if menu in ["insane", "i"]:
        insane()

    else:   
        print("Please type in either hard, medium, easy or insane!")
        difficulty()


def difficulty2():

    print("Easy\n")
    print("Medium\n")
    print("Hard\n")
    print("Insane\n")
    print("Quit\n")

    menu=input("Welcome to Hangman, type in the difficulty you would like. Or would you like to quit the game?").lower()

    if menu == "hard" or menu == "h":

        hard()

    elif menu == "medium" or menu == "m" or menu =="med":

        med()

    elif menu == "easy" or menu == "e":

        easy()

    elif menu == "insane" or menu == "i":

        insane()

    elif menu == "quit" or "q":
        quit()

    else:   
        print("Please type in either hard, medium, easy or insane!")
        difficulty()



#if the user picked easy for their difficulty
def easy():
    global score 
    print ("\nStart guessing...")

    time.sleep(0.5)

    word = random.choice(words).lower()
    guesses = ''
    fails = 0
    while fails >= 0 and fails < 10:         
        failed = 0                
        for char in word:      
            if char in guesses:    
                print (char,)

            else:
                print ("_"),     
                failed += 1    
        if failed == 0:        
            print ("\nYou won, WELL DONE!")
            score = score + 1
            print ("your score is,", score)
            print ("the word was, ", word)
            difficultyEASY()

        guess = input("\nGuess a letter:").lower()
        while len(guess)==0:
            guess = input("\nTry again you muppet:").lower()
        guess = guess[0]
        guesses += guess 
        if guess not in word:
            fails += 1
            print ("\nWrong")

            if fails == 1:
                print ("You have", + fails, "fail....WATCH OUT!" )
            elif fails >= 2 and fails < 10:
                print ("You have", + fails, "fails....WATCH OUT!" )
            if fails == 10:
                print ("You Lose\n")
                print ("your score is, ", score)
                print ("the word was,", word)
                score = 0
                difficultyEASY()

#if the user picked medium for their difficulty
def med():
    global score 
    print ("\nStart guessing...")

    time.sleep(0.5)

    word = random.choice(words).lower()
    guesses = ''
    fails = 0
    while fails >= 0 and fails < 10:           
        failed = 0                
        for char in word:      
            if char in guesses:    
                print (char,)    

            else:
                print ("_"),     
                failed += 1    
        if failed == 0:        
            print ("\nYou won, WELL DONE!")
            score = score + 1
            print ("your score is,", score)
            difficultyMED()

        guess = input("\nGuess a letter:").lower()
        while len(guess)==0:
            guess = input("\nTry again you muppet:").lower()
        guess = guess[0]
        guesses += guess   
        if guess not in word:  
            fails += 1        
            print ("\nWrong")

            if fails == 1:
                print ("You have", + fails, "fail....WATCH OUT!" )
            elif fails >= 2 and fails < 10:
                print ("You have", + fails, "fails....WATCH OUT!" ) 
            if fails == 10:           
                print ("You Lose\n")
                print ("your score is, ", score)
                print ("the word was,", word)
                score = 0 
                difficultyMED()     

#if the user picked hard for their difficulty
def hard():
    global score  
    print ("\nStart guessing...")

    time.sleep(0.5)

    word = random.choice(words).lower()
    guesses = ''
    fails = 0
    while fails >= 0 and fails < 10:  #try to fix this         
        failed = 0                
        for char in word:      
            if char in guesses:    
                print (char,)    

            else:
                print ("_"),     
                failed += 1    
        if failed == 0:        
            print ("\nYou won, WELL DONE!")
            score = score + 1
            print ("your score is,", score)
            difficultyHARD()

        guess = input("\nGuess a letter:").lower()
        while len(guess)==0:
            guess = input("\nTry again you muppet:").lower()
        guess = guess[0]
        guesses += guess   
        if guess not in word:  
            fails += 1        
            print ("\nWrong")

            if fails == 1:
                print ("You have", + fails, "fail....WATCH OUT!" )
            elif fails >= 2 and fails < 10:
                print ("You have", + fails, "fails....WATCH OUT!" ) 
            if fails == 10:           
                print ("You Lose\n")
                print ("your score is, ", score)
                print ("the word was,", word)
                score = 0 
                difficultyHARD()


#if the user picked insane for their difficulty
def insane():
    global score  
    print ("This words may contain an apostrophe. \nStart guessing...")

    time.sleep(0.5)

    word = random.choice(words).lower()
    guesses = ''
    fails = 0
    while fails >= 0 and fails < 10:  #try to fix this         
        failed = 0                
        for char in word:      
            if char in guesses:    
                print (char,)    

            else:
                print ("_"),     
                failed += 1    
        if failed == 0:        
            print ("\nYou won, WELL DONE!")
            score = score + 1
            print ("your score is,", score)
            difficultyINSANE()

        guess = input("\nGuess a letter:").lower()
        while len(guess)==0:
            guess = input("\nTry again you muppet:").lower()
        guess = guess[0]
        guesses += guess   
        if guess not in word:  
            fails += 1        
            print ("\nWrong")

            if fails == 1:
                print ("You have", + fails, "fail....WATCH OUT!" )
            elif fails >= 2 and fails < 10:
                print ("You have", + fails, "fails....WATCH OUT!" ) 
            if fails == 10:           
                print ("You Lose\n")
                print ("your score is, ", score)
                print ("the word was,", word)
                score = 0 
                difficultyINSANE()


def start():

    Continue = input("Do you want to play hangman?").lower()
    while Continue in ["y", "ye", "yes", "yeah"]:
        name = input("What is your name? ")
        print ("Hello, %s, Time to play hangman! You have ten guesses to win!" % name)
        print ("\n")
        time.sleep(1)
        difficulty()
    else:
        quit

#whether they want to try a diffirent difficulty or stay on easy

def difficultyEASY():
    diff = input("Do you want to change the difficulty?. Or quit the game? ")
    if diff == "yes" or difficulty =="y":
        difficulty2()
    elif diff == "no" or diff =="n":
        easy()

#whether they want to try a diffirent difficulty or stay on medium

def difficultyMED():
    diff = input("Do you want to change the difficulty?. Or quit the game? ")
    if diff == "yes" or difficulty =="y":
        difficulty2()
    elif diff == "no" or diff =="n":
        med()

#whether they want to try a diffirent difficulty or stay on hard

def difficultyHARD():
    diff = input("Do you want to change the difficulty?. Or quit the game? ")
    if diff == "yes" or difficulty =="y":
        difficulty2()
    elif diff == "no" or diff =="n":
        hard()

#whether they want to try a diffirent difficulty or stay on insane

def difficultyINSANE():
    diff = input("Do you want to change the difficulty?. Or quit the game? ")
    if diff == "yes" or difficulty =="y":
        difficulty2()
    elif diff == "no" or diff =="n":
        insane()

score = 0

start()

当我运行此代码时,我得到的错误是:

Traceback (most recent call last):
  File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 316, in <module>
    start()
  File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 274, in start
    difficulty()
  File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 41, in difficulty
    insane()
  File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 227, in insane
    word = random.choice(words).lower()
NameError: name 'words' is not defined

我不确定单词或如何修复它有什么问题。

2 个答案:

答案 0 :(得分:3)

您的words变量仅在build_word_list函数的范围内定义。 所有其他功能都无法识别,因此您无法在那里使用它。

你可以拥有一个&#34; quickfix&#34;通过defining it as a global variable,虽然通常 using global variables isn't the best practice,但您可能需要考虑其他解决方案,例如将words传递给您使用它的其他函数或在限制范围内使用它一个班级。

(如果避免全局变量让您感兴趣,也许您想阅读thisthis

答案 1 :(得分:1)

您已在方法build_word_list中定义了words

您应该将self声明为全局变量,以便可以在任何地方访问它或将您的程序重组为一个类,并使用int cv::partition(const vector<_Tp>& vec, vector<int>& labels, _EqPredicate predicate=_EqPredicate()) 来引用它。