Search code examples
pythonpygameevent-loop

Why isn't my movement working after I put it in a function?


def playing():
    global in_game
    x = 250
    y = 250
    width = 10
    height = 10
    white = (255, 255, 255)
    black = (0, 0, 0)
    keys = pygame.key.get_pressed()
    while in_game:
        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                in_game = False

        if keys[pygame.K_UP]:
            y -= 1
        elif keys[pygame.K_DOWN]:
            y += 1
        elif keys[pygame.K_LEFT]:
            x -= 1
        elif keys[pygame.K_RIGHT]:
            x += 1

        win.fill(white)
        pygame.draw.rect(win, black, (x, y, width, height))
        pygame.display.flip()

In This code I put x and y as the horizontal and vertical movement. I called my function at the bottom of the screen.


Solution

  • pygame.key.get_pressed() returns a list of boolean values representing the current state of the keys. You have to evaluate the states of the keys continuously in the application loop, rather than once before the loop:

    # keys = pygame.key.get_pressed() <----- DELETE
    while in_game:
        for event in pygame.event.get():
            print(event)
            if event.type == pygame.QUIT:
                in_game = False
    
        keys = pygame.key.get_pressed() # <----- INSERT
    
        if keys[pygame.K_UP]:
            y -= 1
        elif keys[pygame.K_DOWN]:
            y += 1
        elif keys[pygame.K_LEFT]:
            x -= 1
        elif keys[pygame.K_RIGHT]:
            x += 1
    
        # [...]