【发布时间】: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_x和move_y在函数的前几行中重新定义;它们可用于main中的任何内部函数。 -
我错误地复制和粘贴了我的代码,但前两行代码只是引用了 ball_move() 函数中的两行。使用全局变量对我有很大帮助,非常感谢。
-
@OakenDuck 它们可用于在全局范围内阅读,但不能用于assignment。