Last Updated : 12 Jul, 2025
To make a game or animation in Python using PyGame, moving an object on the screen is one of the first things to learn. We will see how to move an object such that it moves horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves vertically when pressing up arrow key or down arrow key. We’ll create a game window, draw an object and update its position based on user input.
Change in Co-ordinates for respective keys pressed:
Setting Up PyGameLeft arrow key: Decrement in x co-ordinate
Right arrow key: Increment in x co-ordinate
Up arrow key: Decrement in y co-ordinate
Down arrow key: Increment in y co-ordinate
Before starting, make sure PyGame is installed. We can install it using:
Example: Moving a Rectanglepip install pygame
In this code, we create a window using PyGame and draw a rectangle on the screen. The rectangle can be moved using the arrow keys and its position updates as we press the keys. This helps in learning how to handle movement and user input in PyGame.
Python
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("Moving rectangle")
x = 200
y = 200
width = 20
height = 20
vel = 10
run = True
# infinite loop
while run:
pygame.time.delay(10)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x>0:
x -= vel
if keys[pygame.K_RIGHT] and x<500-width:
x += vel
if keys[pygame.K_UP] and y>0:
y -= vel
if keys[pygame.K_DOWN] and y<500-height:
y += vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
Output
Explanation: This code -
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4