简体   繁体   中英

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

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.

Also, in order to move the image, you need to actually display the image at the image_x, image_y coordinates:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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