Moving the player in pygame with key.get_pressed()

A simple example to move a character with pygame.key.get_pressed() in case someone was interested.

This is the image used. Save it as player.png, if you want to try the code with this image, any image can go, just ensure you call the image with the right name.

import pygame

pygame.init()

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

x = 50
y = 50
player = pygame.image.load("player.png")
width = player.get_width()
height = player.get_height()
vel = 1
RED = (255, 0, 0)

run = True
while run:
    
    # RECT = x, y, width, height

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

    keys = pygame.key.get_pressed() #check the key pressed

    if keys[pygame.K_LEFT] and x > vel:
        x -= vel

    if keys[pygame.K_RIGHT] and x < 500 - width - vel:
        x += vel

    if keys[pygame.K_UP] and y > vel:
        y -= vel

    if keys[pygame.K_DOWN] and y < 500 - height - vel:
        y += vel

    win.fill((0, 0, 0))
    # pygame.draw.rect(win, RED, RECT)
    win.blit(player, (x,y))
    pygame.display.update()
    clock.tick(60)

pygame.quit()


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.