首页 文章

在赋值之前引用的Pygame局部变量

提问于
浏览
1

我想制作一个使用键运行的矩形,但我在第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 回答

  • 1

    名称 x 位于全局范围内 . 因此,为了在函数 main 中修改其值,您需要使用global将其声明为全局:

    def main():
        global x
        ...
            x += movex
    

    请注意,如果修改全局,则只需执行此操作 . 访问他们的 Value 观工作得很好 .

相关问题