Pygame局部变量在赋值前被引用
我想用键盘控制一个矩形移动,但在第34行出现了一个错误:
UnboundLocalError: local variable 'x' referenced before assignment
我不知道怎么修复这个错误。请帮帮我。
这是我的代码:
import pygame
import sys
from pygame.locals import *
fps = 30
fpsclock = pygame.time.Clock()
w = 640
h = 420
blue = (0, 0, 255)
white = (255, 255, 255)
x = w / 3
y = 350
boxa = 20
movex = 0
def drawwindow():
global screen
pygame.init()
screen = pygame.display.set_mode((w, h))
screen.fill(blue)
def drawbox(box):
if box.right > (w - boxa):
box.right = (w - boxa)
if box.left < 0:
box.left = 0
pygame.draw.rect(screen, white, box)
def main():
drawwindow()
box1 = pygame.Rect(x, y, boxa, boxa)
drawbox(box1)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_RIGHT:
movex = +4
if event.key == K_LEFT:
movex = -4
if event.type == KEYUP:
if event.key == K_RIGHT:
movex = 0
if event.key == K_LEFT:
movex = 0
x += movex
pygame.display.update()
fpsclock.tick(fps)
if __name__ == '__main__':
main()
1 个回答
3
名字 x
是在全局范围内的。因此,如果你想在函数 main
里面修改它的值,你需要用 global
来声明它是全局的:
def main():
global x
...
x += movex
注意,只有在你要 修改 全局变量的时候,才需要这样做。如果只是访问它们的值,那是没问题的。