Pygame Characther Doens't Move

Viewed 39

Nice day for y'all, peoples

after learning python i'm starting to learn pygame, and for thaat i've been tried to make my first step by doing a rect to move. I did draw the rect and did the following code:

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
clock = pygame.time.Clock()

rectx = 100
recty = 250

run = True
player = pygame.draw.rect(win, (255, 255, 255), pygame.Rect(rectx, recty, 100, 60))
pygame.display.flip()


while run:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        key_pressed_is = pygame.key.get_pressed()

        if pygame.K_LEFT:
            rectx -= 8
        if pygame.K_RIGHT:
            rectx += 8
        if pygame.K_UP:
            recty -= 8
        if pygame.K_DOWN:
            recty += 8

    pygame.display.update()

but when i run the program, everything is okay except that the rect doens't move. Even when i press any move button, it doens't move and i don't get eny error message, the rect just stay still

what should i do? and if it is possible, could you explain me why i get that error?

1 Answers

See How can I make a sprite move when key is held down.
pygame.key.get_pressed() is not an event. You have to call it in the application loop instead of the event loop. pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is 1, otherwise 0 e.g. if key_pressed_is[pygame.K_LEFT]:.
Furthermore you need to redraw the entire scene in ever frame. The typical PyGame application loop has to:

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
clock = pygame.time.Clock()

player = pygame.Rect(100, 250, 100, 60)

# applicatiion loop
run = True
while run:

    # limit frames per second
    clock.tick(60)

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # update objects

    # INDENTATION
    #<--|
    key_pressed_is = pygame.key.get_pressed()
    if key_pressed_is[pygame.K_LEFT]:
        player.x -= 8
    if key_pressed_is[pygame.K_RIGHT]:
        player.x += 8
    if key_pressed_is[pygame.K_UP]:
        player.y -= 8
    if key_pressed_is[pygame.K_DOWN]:
        player.y += 8

    # clear display
    win.fill(0)

    # draw scene   
    pygame.draw.rect(win, (255, 255, 255), player)

    # update display
    pygame.display.flip()
Related