![Pygame Tutorial](/pygame/images/pygame-mini-logo.jpg)
- Pygame Tutorial
- Pygame - Home
- Pygame - Overview
- Pygame - Hello World
- Pygame - Display modes
- Pygame - Locals module
- Pygame - Color object
- Pygame - Event objects
- Pygame - Keyboard events
- Pygame - Mouse events
- Pygame - Drawing shapes
- Pygame - Loading image
- Pygame - Displaying Text in Window
- Pygame - Moving an image
- Pygame - Moving with Numeric pad keys
- Pygame - Moving with mouse
- Pygame - Moving Rectangular objects
- Pygame - Use Text as Buttons
- Pygame - Transforming Images
- Pygame - Sound objects
- Pygame - Mixer channels
- Pygame - Playing music
- Pygame - Playing Movie
- Pygame - Using Camera module
- Pygame - Load cursor
- Pygame - Access CDROM
- Pygame - The Sprite Module
- Pygame - PyOpenGL
- Pygame - Errors and Exception
- Pygame Useful Resources
- Pygame - Quick Guide
- Pygame - Useful Resources
- Pygame - Discussion
Pygame - Moving an Image
Movement of an object is an important aspect of any computer game. A computer game creates illusion of movement by drawing and erasing an object at incremental position. Following code draws an image by incrementing x coordinate position in an event loop and erasing it with the background color.
Example
image_filename = 'pygame.png' import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300), 0, 32) pygame.display.set_caption("Moving Image") img = pygame.image.load(image_filename) x = 0 while True: screen.fill((255,255,255)) for event in pygame.event.get(): if event.type == QUIT: exit() screen.blit(img, (x, 100)) x= x+0.5 if x > 400: x = x-400 pygame.display.update()
Output
The Pygame logo image starts displaying at left border and repeatedly shifts towards right. If it reaches right border, its position is reset to left.
![incremental position](/pygame/images/incremental_position.jpg)
In the following program, the image is displayed at (0,150) position to begin with. When user presses arrow keys (left, right, up, down), the image changes its location by 5 pixels. If a KEYDOWN event occurs, the program checks if the key value is K_LEFT, K_RIGHT, K_UP or K_DOWN. The x coordinate changes by +5 or -5 if it is K_LEFT or K_RIGHT. Value of y coordinate changes by -5 or +5 if key value is K_UP or K_DOWN.
image_filename = 'pygame.png' import pygame from pygame.locals import * from sys import exit pygame.init() screen = pygame.display.set_mode((400,300)) pygame.display.set_caption("Moving with arrows") img = pygame.image.load(image_filename) x = 0 y= 150 while True: screen.fill((255,255,255)) screen.blit(img, (x, y)) for event in pygame.event.get(): if event.type == QUIT: exit() if event.type == KEYDOWN: if event.key == K_RIGHT: x= x+5 if event.key == K_LEFT: x=x-5 if event.key == K_UP: y=y-5 if event.key == K_DOWN: y=y+5 pygame.display.update()