在赋值错误之前引用事件变量,我不知道如何解决它



每当我尝试打开帮助部分时,我都会收到此错误:

Traceback (most recent call last):
  File "C:/Users/Chris/Desktop/Paul's stuff/Paul/CpmpProject/Window.py", line 142, in <module>
    game.help()
  File "C:/Users/Chris/Desktop/Paul's stuff/Paul/CpmpProject/Window.py", line 76, in help
    if event.type == MOUSEBUTTONDOWN:
UnboundLocalError: local variable 'event' referenced before assignment

我不知道如何解决这个问题。我有很多代码,我觉得要找到错误需要经历很多。如果您能帮助我解决此问题,我将不胜感激,我知道其他一些从事类似项目的人会很感激,他们也会遇到同样的问题。我的代码如下。我不期望任何人经历它,但我会感谢任何人愿意并找到我遇到的错误。我已经包含了所有这些,以防万一它比我预期的更远,但我认为问题出在帮助函数定义中。

import pygame, sys
from pygame.locals import *
import random
from random import shuffle
back = True
backbutton = pygame.image.load("Back button.png")
helpsection = pygame.image.load("Hunt Help section.png")
class Game():
    def question(self):
        questions = ["What species of bird is also a nickname for New Zealand?",
                     "Which Twins can you play as in Assassin's Creed Syndicate?",
                     "Which year was 'Killing In The Name' Christmas Number one?"]
        answers = [["kiwi", "Kiwi", "Falcon", "Sparrow", "Crow"], ["frye", "Frye", "Bank", "Green", "Bundy"],
                   ["2009", "2009",
                    "1999", "1993",
                    "2004"]]
        # I had to do it in two separate lists as it's easier to work with later on
        # Also I made the correct answers non-case sensitive to make it easier to test.
        Game_back = True
        while Game_back == True:
            r = len(questions)
            score = 0
            s = random.randrange(0, r, 1)
            # This generates a random number within the range of how many questions there are
            # and then prints out that question
            print(questions[s])
            list = answers[s]
            output = []
            for i in range(1, 5):
                output.append(answers[s][i])
            shuffle(output)
            print(output[0] + "     ", output[1] + "     ", output[2] + "      ", output[3])
            # this takes the answers that correspond with the randomly generated question and shuffles the answers
            # I did this as otherwise, the answer would always be the first answer to appear and the player could exploit this
            player_answer = input()
            if player_answer == answers[s][0] or player_answer == answers[s][1]:
                score += 1
                print(score)
            else:
                print("Wrong")
            panswer = input("Would you like to play another round?: ")
            quit = ["Yes", "yes", "Yeah", "yeah"]
            if panswer in quit:
                Game_back = False
            else:
                pygame.quit()
                sys.exit()
            # this is the basics of the algorithm that will determine if a player can move forward or not in the maze and the score
            # they will have at the end
            ## it takes the input from the player and compares it to the first 2 answers in the corresponding answer set which is
            ## a separate list from the list that is printed out to the player
    def help(self):
        pygame.init()
        self.FPS = 60
        self.fps_clock = pygame.time.Clock()
        self.surface = pygame.display.set_mode((640, 480))
        # This class sets the basic attributes for the window.
        # The clock is set to 60 and the name of the window
        # is set to The Hunt which is a working title for my project
        DISPLAY_SURF.blit(helpsection, (0, 0))
        DISPLAY_SURF.blit(backbutton, ((640 - 124), (480 - 87)))
        if event.type == MOUSEBUTTONDOWN:
            if (640 -124) >= mouse[0] > 640 and (480 - 87) >= mouse[1] > 480:
                back = False
        while True:
            pygame.display.update()
            self.fps_clock.tick(self.FPS)
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()

            # This updates the window display to refresh every clock tick
            # and to set the background colour as white
            # using the RGB colours. I might use these to alter the window's look at a later date


#Initialize pygame and define colours
pygame.init()
white = 255, 255, 255
#Sets the resolution to 640 pixels by 720 pixels and caption for pygame window
DISPLAY_SURF = pygame.display.set_mode((640, 720))
pygame.display.set_caption("The Hunt!")

#Create a clock object
clock = pygame.time.Clock()
FPS = 60
#Define a variable to refer to image
background = pygame.image.load("Startermenu.png")
start = pygame.image.load("PlayGameButton.png")
help = pygame.image.load("HelpButton.png")
credits = pygame.image.load("ShowCreditsButton.png")
Hoveringhelp = pygame.image.load("HoveringHelpButton.png")

#Start main loop
while True:
    for event in pygame.event.get():
        mouse = pygame.mouse.get_pos()
        DISPLAY_SURF.fill(white)
        DISPLAY_SURF.blit(background, (0, 0))
        DISPLAY_SURF.blit(start, (0, 140))
        DISPLAY_SURF.blit(help, (0, 186))
        DISPLAY_SURF.blit(credits, (0, 235))
        pygame.display.update()
        #if 0 <= mouse[0] < 260 and 180 <= mouse[1] < 230:
         #   DISPLAY_SURF.blit(Hoveringhelp, (0, 186))
          #  print("hovering over help")
        #elif 0 <= mouse[0] < 260 and 235 <= mouse[1] < 270:
         #   print("hovering over credits")
        #elif 0 <= mouse[0] < 260 and 0 <= mouse[1] < 180:
         #   print("hovering over play button")
        if event.type == MOUSEBUTTONDOWN:
            if 0 <= mouse[0] < 260 and 140 <= mouse[1] < 180:
                game = Game()
                game.question()
            elif 0 <= mouse[0] < 260 and 180 <= mouse[1] < 230:
                game = Game()
                game.help()
            elif 0 <= mouse[0] < 260 and 240 <= mouse[1] < 285:
                game = Game()
                game.credits()
        elif event.type == QUIT:
            pygame.quit()
            sys.exit()

help()方法中:

def help(self):
    ...
    if event.type == MOUSEBUTTONDOWN:
    ...
    while True:
        ...
        for event in pygame.event.get():

event是在for循环中定义的,但您在此之前引用了它。

修复它的一种方法是在for循环内移动 if event.type == MOUSEBUTTONDOWN 语句。

或者,由于 .help() 仅从已知事件MOUSEBUTTONDOWN的底部事件循环调用,也许您可以完全删除 if 语句?

(顺便说一句,我认为错误消息很清楚;你不明白吗?

相关内容

  • 没有找到相关文章

最新更新