Diqosh
Diqosh

Reputation: 43

Cannot move player on pygame

i am learning pygame.I get a little problem with moving and i dont know how to make so that player move.i cannot understand where my mistake.Can you help me on this problem.And i will so appriciate if you give me some advice on pygame.I'm such a newbie

import pygame

widthSurface = 640
heightSurface = 480
keys = [False, False, False, False]
playerpos = [100, 100]
vel = 5

# images
player = pygame.image.load('resources/images/dude.png')
grass = pygame.image.load('resources/images/grass.png')
castle = pygame.image.load('resources/images/castle.png')


def blitGrassAndCastle():
    for x in range(widthSurface // grass.get_width() + 1):
        for y in range(heightSurface // grass.get_height() + 1):
            surface.blit(grass, (x * grass.get_width(), y * grass.get_height()))
    surface.blit(castle, (0, 30))
    surface.blit(castle, (0, 135))
    surface.blit(castle, (0, 240))
    surface.blit(castle, (0, 345))


if __name__ == '__main__':

    pygame.init()
    pressed = pygame.key.get_pressed()
    surface = pygame.display.set_mode((widthSurface, heightSurface))
    while True:
        pygame.time.delay(10)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)
                
        if pressed[pygame.K_LEFT]:
            playerpos[0] -= vel

        if pressed[pygame.K_RIGHT]:
            playerpos[0] += vel

        if pressed[pygame.K_UP]:
            playerpos[1] -= vel

        if pressed[pygame.K_DOWN]:
            playerpos[1] += vel

        blitGrassAndCastle()
        surface.blit(player, playerpos)

        pygame.display.update()

Thank you in advanced!

Upvotes: 2

Views: 46

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

pygame.key.get_pressed() returns a list with the current state of all keyboard buttons. You need to get the state of the keys ** in ** the application loop every frame, rather than once before the loop. The states you get before the loop will never change.

if __name__ == '__main__':

    pygame.init()

    # pressed = pygame.key.get_pressed() # <-- DELETE

    surface = pygame.display.set_mode((widthSurface, heightSurface))
    while True:
        pygame.time.delay(10)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)

        pressed = pygame.key.get_pressed() # <--- INSERT
                
        if pressed[pygame.K_LEFT]:
            playerpos[0] -= vel

        if pressed[pygame.K_RIGHT]:
            playerpos[0] += vel

        if pressed[pygame.K_UP]:
            playerpos[1] -= vel

        if pressed[pygame.K_DOWN]:
            playerpos[1] += vel

        blitGrassAndCastle()
        surface.blit(player, playerpos)

        pygame.display.update()

Upvotes: 2

Related Questions