Search code examples
pythonpython-3.xpygame2dgame-physics

Why isn't my sprite moving when i press a specific key in pygame


I was building a simple rocket game and it required moving some sprites. In the code below cloud1 is supposed to move -30 pixels towards the bottom each time i press the K_DOWN key. I have been trying to figure out what is wrong with the code for 3 days but haven't progressed even a little bit. Help would be much appreciated.

import pygame
pygame.init()

DISPLAY_HEIGHT = 700
DISPLAY_WIDTH = 900

screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption('Rocket Game')

clock = pygame.time.Clock()
FPS = 60


#colors
WHITE = (255,255,255)
BLACK = (0,0,0)
SKY_BLUE = (102,178,255)

cloud1 = pygame.image.load('cloud.png')
cloud1_X, cloud1_Y = 100, 50
cloud1_Y_change = 30


def cloud1_display(x, y):
    screen.blit(cloud1, (x, y))

running = True
while running:
    screen.fill(SKY_BLUE)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                cloud1_Y += cloud1_Y_change

    cloud1_display(cloud1_X, cloud1_X)
    clock.tick(FPS)
    pygame.display.update()


    
    

Solution

  • There are two problems. The first is that your code is not checking the event.key for the pygame.K_UP. But your code is also painting the cloud at (x, x), not (x, y).

    Corrected code:

    while running:
        screen.fill(SKY_BLUE)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:       # <<-- HERE
                    cloud1_Y += cloud1_Y_change
    
        cloud1_display(cloud1_X, cloud1_Y)         # <<-- AND HERE
        clock.tick(FPS)
        pygame.display.update()