繁体   English   中英

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

[英]How do i fix the error in my hangman game in Python 3

这段代码来自我过去一天左右一直在努力的一款小游戏,我知道我不应该真正发布整个代码,但是我不能完全确定代码的哪一部分不能按预期工作,帮助将不胜感激。 该代码是一个子手游戏,我知道代码中有大量重复,但是不确定如何将其简化为可以与每个难度设置一起使用的每个功能之一。

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

我不确定单词有什么问题或如何解决。

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

您可以通过将其定义为全局变量来获得“快速修正”,尽管通常不建议 使用全局变量,并且您可能需要考虑其他解决方案,例如将words传递给使用该变量的其他函数,或者在内部使用它一类的范围。

(如果避免了全局变量感兴趣的你,也许你想读这个这个

你有words中定义的方法build_word_list

您应该将words声明为全局变量,以便可以在任何地方访问它,也可以将程序重组为一个类并使用self来引用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM