简体   繁体   English

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

[英]Pygame Black screen and error when adding code to move player

I am trying to get my player to move in a program but I keep receiving this error I'm not recognizing. 我试图让我的播放器进入程序,但是我一直收到我不认识的错误。 Here's the error: 这是错误:

Traceback (most recent call last): File "C:\\Users\\1234\\AppData\\Local\\Programs\\Python\\Python36-32\\My First game ERROR.py", line 39, in Game().main(screen) File "C:\\Users\\1234\\AppData\\Local\\Programs\\Python\\Python36-32\\My First game ERROR.py", line 19, in main image_x += 1 UnboundLocalError: local variable 'image_x' referenced before assignment 追溯(最近一次通话最近):文件“ C:\\ Users \\ 1234 \\ AppData \\ Local \\ Programs \\ Python \\ Python36-32 \\ My First game ERROR.py”,第39行,位于Game()。main(屏幕)文件中主图像_x + = 1中的“ C:\\ Users \\ 1234 \\ AppData \\ Local \\ Programs \\ Python \\ Python36-32 \\我的第一个游戏ERROR.py”,第19行+ UnboundLocalError:分配前引用了局部变量“ image_x”

And Here's the code: 这是代码:

# 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)

That's because you have never initialized the variable. 那是因为您从未初始化变量。

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

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

    # initialize variables
    image_x = 0
    image_y = 0

You need to initialize image_x and image_y with some initial value before using them. 使用它们之前,您需要使用一些初始值初始化image_ximage_y

Also, in order to move the image, you need to actually display the image at the image_x, image_y coordinates: 另外,为了移动图像,您需要实际在image_x,image_y坐标处显示图像:

So, instead of : 因此,代替:

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

You need to use: 您需要使用:

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

Finally, after applying the change above, your image moves on every event, that includes mouse clicks and movements, because you always increase image_x by 1 no matter the event. 最后,应用上述更改后,图像会在每个事件(包括鼠标单击和移动)上移动,因为无论事件如何,您总是将image_x增加1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM