【问题标题】:How do i fix the error in my hangman game in Python 3如何在 Python 3 中修复我的刽子手游戏中的错误
【发布时间】:2016-02-09 09:22:37
【问题描述】:

这段代码来自我过去一天左右一直在开发的一个小游戏,我知道我不应该真正发布整个代码,但我不完全确定代码的哪一部分不能正常工作有意,任何帮助将不胜感激。该代码是一个刽子手游戏,我知道代码中有大量重复,但不确定如何将其简化为适用于每个难度设置的每个功能。

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

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

    您可以通过defining it as a global variable 获得“快速修复”,尽管通常 using global variables isn't the best practice 并且您可能需要考虑一些其他解决方案,例如将words 传递给使用它或使用它的其他函数它在一个类的范围内。

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

    【讨论】:

    • 我怎样才能让他们识别它,我应该让它全球化吗?
    • 现在效果很好,我不敢相信这么小的东西可以让整个游戏停止工作
    • @L.Davis 很高兴它对你有用 :) 请考虑接受这个答案
    【解决方案2】:

    您在方法build_word_list 中定义了words

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

    【讨论】:

      猜你喜欢
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      相关资源
      最近更新 更多