为啥 Python 会在 Pygame 中为“事件”变量抛出未绑定的本地错误? [关闭]

Posted

技术标签:

【中文标题】为啥 Python 会在 Pygame 中为“事件”变量抛出未绑定的本地错误? [关闭]【英文标题】:Why does Python throw Unbound local error for 'event' variable in Pygame? [closed]为什么 Python 会在 Pygame 中为“事件”变量抛出未绑定的本地错误? [关闭] 【发布时间】:2019-08-18 11:02:50 【问题描述】:

在运行游戏循环时,使用箭头键移动游戏对象时游戏往往会崩溃。该错误似乎发生在未确定的点。 Python 抛出错误:

Exception has occurred: UnboundLocalError  
local variable 'event' referenced before assignment

我尝试为控件创建一个函数并调用它们,但这不起作用。我试图将逻辑缩进:pygame.event.get()中的事件:但随后无法控制对象。

def game_loop(): # The game loop which runs the core mechanics of the game

    x = (display_width * 0.5) # Initial x/y values of the circle, where it is placed
    y = (display_height * 0.6)

    dx = 0 #Change in those x,y values
    dy = 0 
    thing_startx = random.randrange(0,display_width)
    thing_starty = random.randrange(0,display_height)
    thing_speed = 7
    thing_width = random.randrange(50,500)
    thing_height = 100


    gameExit = False #This becomes true if the player wants to exit the game

    while not gameExit: # game loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            print(event)

        if event.type == pygame.KEYDOWN: # if a key is pressed down
            if event.key == pygame.K_LEFT: # if it is the left arrow key
                dx = -5 #change x by -5 (go left)
            elif event.key == pygame.K_RIGHT:
                dx = 5
        if event.type == pygame.KEYUP: # if key is released
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: #if neither left or right arrow keys are pressed, 
                dx = 0 #Do not change x

        x += dx #x+dx. add the change to the original

        if event.type == pygame.KEYDOWN: #as above but for y axis
            if event.key == pygame.K_UP:
                dy = -5
            elif event.key == pygame.K_DOWN:
                dy = 5

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                dy = 0
        y += dy

        gameDisplay.fill(darkGreen)#paint the display white

        #things (thingx,thingy,thingw,thingh,colour)
        things(thing_startx,thing_starty,thing_width,thing_height,red)
        thing_starty += thing_speed
        circle(x,y) # paint the circle into the display at x,y

        #Boundaries
        if x > display_width - circleWidth or x<0: 
            crash()#Call crash function if boundaries are met
        elif y >display_height - circleHeight or y<0:
            crash()


        if thing_starty > display_height:
            thing_starty = 0 - thing_height
            thing_startx = random.randrange(0,display_width)     

        #Detects collisions with obstacles in the road
        if y < thing_starty+thing_height:
            print('y crossover')
        if x > thing_startx and x < thing_startx + thing_width or x + circleWidth > thing_startx and x + circleWidth < thing_startx+thing_width:
            print('x crossover')
            #crash()

        pygame.display.update() #update the display
        clock.tick(60)#make game 60fps

这是错误:

Exception has occurred: UnboundLocalError
local variable 'event' referenced before assignment
  File "C:\Python\pythonWorkspace\Tutorial.py", line 131, in game_loop
    if event.type == pygame.KEYDOWN: # if a key is pressed down
  File "C:\Python\pythonWorkspace\Tutorial.py", line 73, in button
    game_loop()
  File "C:\Python\pythonWorkspace\Tutorial.py", line 101, in game_intro
    button("GO",150,450,100,50,green,brightGreen,"play")
  File "C:\Python\pythonWorkspace\Tutorial.py", line 180, in <module>
    game_intro()# call the game intro screen

【问题讨论】:

【参考方案1】:

这是Indentation 的问题。处理事件的代码和事件类型的检查(例如event.type == pygame.KEYDOWN)必须在事件循环而不是主游戏循环中完成:

def game_loop(): # The game loop which runs the core mechanics of the game

    # [...]

    while not gameExit: # game loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            #
            # --> INDENTATION: the following code has to be in the event loop
            #
            if event.type == pygame.KEYDOWN: # if a key is pressed down
                if event.key == pygame.K_LEFT: # if it is the left arrow key
                    dx = -5 #change x by -5 (go left)
                elif event.key == pygame.K_RIGHT:
                    dx = 5
            if event.type == pygame.KEYUP: # if key is released
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: 
                    #if neither left or right arrow keys are pressed, 
                    dx = 0 #Do not change x

            if event.type == pygame.KEYDOWN: #as above but for y axis
                if event.key == pygame.K_UP:
                    dy = -5
                elif event.key == pygame.K_DOWN:
                    dy = 5

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    dy = 0

        # this code has to be in the main game loop
        x += dx
        y += dy

但是你可以通过使用pygame.key.get_pressed()来简化代码:

def game_loop(): # The game loop which runs the core mechanics of the game

    # [...]

    while not gameExit: # game loop

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        keys = pygame.key.get_pressed()
        dx   = -5 if keys[pygame.K_LEFT] else 5 if keys[pygame.K_RIGHT] else 0
        dy   = -5 if keys[pygame.K_UP]   else 5 if keys[pygame.K_DOWN]  else 0

        x += dx
        y += dy

【讨论】:

以上是关于为啥 Python 会在 Pygame 中为“事件”变量抛出未绑定的本地错误? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

如何在Ubuntu16.04中为python3.5安装pygame?

如何在我的蛇游戏中为我的蛇的身体部位使用不同的图像? (Python、Pygame、Snake)

为啥 TensorFlow 会在 TensorBoard 可视化中为我的变量创建额外的命名空间?

为啥我的 python/pygame 应用程序没有正确弹出

为啥我的python用pygame做图片移动会留下轨迹?

有人可以帮我在pygame中为扑克游戏创建一副纸牌吗