【问题标题】:Referencing an event variable before assignment error and I dont know how to fix it在赋值错误之前引用事件变量,我不知道如何修复它
【发布时间】:2018-01-07 20:50:50
【问题描述】:

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

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()

【问题讨论】:

  • 如错误所说,event 未定义
  • event 仅存在于 for event 循环内。

标签: python events event-handling pygame mouseevent


【解决方案1】:

help() 方法中:

def help(self):

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

event 是在for 循环中定义的,但您指的是它之前

解决此问题的一种方法是将if event.type == MOUSEBUTTONDOWN 语句移动到for 循环内。

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

(顺便说一句,我以为错误信息很清楚;你没看懂吗?)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    相关资源
    最近更新 更多