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