Pygame黑屏和添加代码移动播放器时出错

时间:2018-01-15 18:59:42

标签: python pygame

我试图让我的播放器移动一个程序,但我一直收到这个错误,我不认识。 这是错误:

追踪(最近一次通话):   文件“C:\ Users \ 1234 \ AppData \ Local \ Programs \ Python \ Python36-32 \ My First game ERROR.py”,第39行,     游戏()主(屏幕)。   文件“C:\ Users \ 1234 \ AppData \ Local \ Programs \ Python \ Python36-32 \ My First game ERROR.py”,第19行,主要     image_x + = 1 UnboundLocalError:赋值前引用的局部变量'image_x'

以下是代码:

# This just imports all the Pygame modules
import pygame

class Game(object):
def main(self, screen):
    clock = pygame.time.Clock()

    image = pygame.image.load('Sprite-01.png')

    while 1:
        clock.tick(30)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                return

            image_x += 1
            key = pygame.key.get_pressed()
            if key[pygame.K_LEFT]:
                image_x -= 10
            if key[pygame.K_RIGHT]:
                image_x += 10
            if key[pygame.K_UP]:
                image_y -= 10
            if key[pygame.K_DOWN]:
                image_y += 10

        screen.fill((200, 200, 200))
        screen.blit(image, (320, 240))
        pygame.display.flip()



if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    Game().main(screen)

1 个答案:

答案 0 :(得分:2)

那是因为你从未初始化变量。

def main(self, screen):
    clock = pygame.time.Clock()

    image = pygame.image.load('Sprite-01.png')

    # initialize variables
    image_x = 0
    image_y = 0

在使用之前,您需要使用初始值初始化image_ximage_y

另外,为了移动图像,您需要在image_x,image_y坐标处实际显示图像:

所以,而不是:

screen.blit(image, (320, 240))

您需要使用:

screen.blit(image, (image_x, image_y))

最后,在应用上述更改后,您的图像会在每个事件上移动,包括鼠标点击和移动,因为无论事件如何,您总是将image_x增加1。