【问题标题】:Python pygame - bouncing ball (UnboundLocalError: local variable 'move_y' referenced before assignment)Python pygame - 弹跳球(UnboundLocalError:分配前引用的局部变量'move_y')
【发布时间】:2020-12-05 02:37:30
【问题描述】:

我想创建一个负责从屏幕边缘弹跳球的函数。我知道我可以用数学和 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()

【问题讨论】:

  • 你必须将move_y声明为一个全局变量,否则ball_move()函数认为它是一个局部变量。
  • 我认为这不是整个脚本,因为顶部有一个if 语句会影响move_y。如果您还没有这样做,请发布完整的回溯及其描述的行。
  • @JohnGordon 变量move_xmove_y 在函数的前几行中重新定义;它们可用于main 中的任何内部函数。
  • 我错误地复制和粘贴了我的代码,但前两行代码只是引用了 ball_move() 函数中的两行。使用全局变量对我有很大帮助,非常感谢。
  • @OakenDuck 它们可用于在全局范围内阅读,但不能用于assignment

标签: python pygame


【解决方案1】:

问题是由函数引起的

导致问题的代码在函数中:

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:赋值前引用了局部变量“move_y”

如果你想将变量解释为全局变量,你必须使用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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 2020-01-16
    • 2019-12-05
    • 2017-09-19
    相关资源
    最近更新 更多