我想制作一个使用键运行的矩形,但我在第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()
答案 0 :(得分:1)
名称x
位于全球范围内。因此,为了在函数main
中修改其值,您需要使用global
将其声明为全局:
def main():
global x
...
x += movex
请注意,如果您修改全局,则只需执行此操作。访问它们的值可以正常工作。