Python pygame - 弹跳球(UnboundLocalError : local variable 'move_y' referenced before assignment)

标签 python pygame

我想创建一个函数来负责从屏幕边缘弹跳球。我知道我可以使用数学和 Vector2 函数做得更好,但我想知道为什么会出现此错误,以及为什么我可以在没有这行代码的情况下运行窗口:

if ball.y >= HEIGHT - 10:
    move_y = -vall_vel

代码

class Ball:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color

    def draw(self, window):
        pygame.draw.circle(window, self.color, (self.x, self.y), 10)

ball = Ball(WIDTH // 2, HEIGHT // 2, red)

def main():
    run = True

    ball_vel = 10
    move_x = ball_vel
    move_y = ball_vel

    def update():
        WINDOW.fill(black)

        ball.draw(WINDOW)

        player.draw(WINDOW)
        pygame.display.update()

    def ball_move():
        
        if HEIGHT - 10 > ball.y > 0 and WIDTH - 10 > ball.x > 0:
            ball.x += move_x
            ball.y += move_y
        
        if ball.y >= HEIGHT - 10:
            move_y = -ball_vel

    while run:
        clock.tick(FPS)

        ball_move()

        update()

最佳答案

该问题是由功能引起的

导致问题的代码位于函数中:

def ball_move():

   if HEIGHT - 10 > ball.y > 0 and WIDTH - 10 > ball.x > 0:
       ball.x += move_x
       ball.y += move_y

   if ball.y >= HEIGHT - 10:
       move_y = -ball_vel

在函数中,ball_move 被写入变量move_y。这意味着该变量是在函数体内声明的,并且是一个局部变量(在 ball_move 中为局部变量)。在声明变量之前读取变量会导致错误

UnboundLocalError: local variable 'move_y' referenced before assignment

您必须使用global statement如果你想将变量解释为全局变量。实际上在函数main中存在一个同名的变量。但由于要在 main 中设置相同的变量,因此也必须将其声明为全局变量:

def main():
    global run, move_x, move_y        # <---- ADD

    run = True
    ball_vel = 10
    move_x = ball_vel
    move_y = ball_vel

    def update():
        WINDOW.fill(black)
        ball.draw(WINDOW)
        player.draw(WINDOW)
        pygame.display.update()

    def ball_move():
        global move_x, move_y         # <---- ADD

        if HEIGHT - 10 > ball.y > 0 and WIDTH - 10 > ball.x > 0:
            ball.x += move_x
            ball.y += move_y
        if ball.y >= HEIGHT - 10:
            move_y = -ball_vel

    while run:
        clock.tick(FPS)
        ball_move()
        update()

关于Python pygame - 弹跳球(UnboundLocalError : local variable 'move_y' referenced before assignment),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65153237/

相关文章:

python - 我必须安装什么来解决 Could not find any typelib for GtkSource, Cannot import : GtkSourceView, cannot import name GtkSource

Python:当 readline() 使用 Popen() 调用的进程时收到垃圾

python - 使用 Python 流式传输音频(没有 GStreamer)

python - 如何使用 Pygame 矩形

python - 如何在pygame中点击并拖动一个对象?

python - Pygame 滚动 map 进阶

python - 无法从 __future__ 导入注释

python - 如何在 matplotlib 中以不同颜色呈现 LaTeX 字符串的子字符串?

python - windows环境下cygwin中无法运行pybot批处理文件

python - 如何使表面(次表面)围绕矩形居中? (缩放 Sprite 碰撞箱/碰撞矩形)