我如何修复 UnboundLocalError: 分配错误之前引用的局部变量“moving_right” [PYGAME]

时间:2021-04-03 17:53:53

标签: python python-3.x pygame

我正在尝试让 pygame 进行测试,但在无缘无故地运行它时收到错误消息。对于我试图通过添加代码快捷方式来促进游戏创建的混乱代码,我深表歉意。我在演示中使用了 pygame、sys、os 库。

代码:

from GGD import *

pygame.display.set_icon(pygame.image.load('Sprites/Icon.png'))
pygame.display.set_caption("Knock Knight")

screen = pygame.display.set_mode((226, 318))
player1 = pygame.image.load('Sprites/Player.png').convert()

while True:
    screen.fill((0, 0, 0))

    spriteMovement(player1, player_pos=[0,0])

    pygame.display.update()
    clock.tick(60)

pygame.quit()

GGD:

from pygame.locals import *
import pygame
import sys
import os

print('Loading[*]')

moving_right = False
moving_left = False
moving_up = False
moving_down = False

def spriteMovement(player1, player_pos=[0,0]):

if moving_right == True:
    player_pos[0] += 4
if moving_left == True:
    player_pos[0] -= 4
if moving_up == True:
    player_pos[1] -=4
if moving_down == True:
    player_pos[1] +=4

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()

    if event.type == KEYDOWN:
        if event.key == K_RIGHT:
            moving_right = True
        if event.key == K_LEFT:
            moving_left = True
        if event.key == K_UP:
            moving_up = True
        if event.key == K_DOWN:
            moving_down = True
    if event.type == KEYUP:
        if event.key == K_RIGHT:
            moving_right = False
        if event.key == K_LEFT:
            moving_left = False
        if event.key == K_UP:
            moving_up = False
        if event.key == K_DOWN:
            moving_down = False

0 个答案:

没有答案