In PyGame Images are stored as Surface. Also display can be treated as ordinary image. It simplify screen management.
PyGame uses odd coordinate system. top left corner is (0,0) top right (640,0) bottom left (0,480) and bottom right is (640,480) if window is (640,480) of course values can be different and you set them when calling pygame.display.set_mode().
Drawing on the screen
To draw something on the screen we must first load image from file. Then blit it on display surface and at the end order PyGame to draw everything on the screen.
Blitting is a process of putting one image onto another e.g. we will put our hero on the screen every frame in a bit different positions to create illusion of motion.
It will paint image_to_paint in (0,0) point but you can paint it everywhere inside display_surf.
For loading images PyGame have pygame.image module. To load a particular image use:
image_surf = pygame.image.load("myimage.bmp").convert()
This line means load "myimage.bmp" and put it in new Surface "pygame.image.load("myimage.bmp")", than take
this Surface and convert to new with best pixel&color format and assign it to image_surf.
If you wan't to make your games os independent use os.path.join("folder_where_your_data_are", "file_name_of_image") to create os specific path to file e.g uder linux it will be "folder_where_your_data_are/file_name_of_image"
import pygame from pygame.locals import * class App: def __init__(self): self._running = True self._display_surf = None self._image_surf = None def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode((350,350), pygame.HWSURFACE) self._running = True self._image_surf = pygame.image.load("myimage.jpg").convert() def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): pass def on_render(self): self._display_surf.blit(self._image_surf,(0,0)) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while( self._running ): for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.on_cleanup() if __name__ == "__main__" : theApp = App() theApp.on_execute()
I've changed only on_init and on_render.
If you like you can use this file. Which btw show glider from Conawy's Game of Life.
Multiple images in one file
Imagine that in our game we have 100 types of ground is this mean that we have to create 100 files?
NO!! just put therm together and order PyGame to cut out only those you need at the moment.
image_surf = pygame.image.load("one_big_file.bmp").convert() # ........ # and for drawing only part of it: display_surf.blit(image_surf, (0,0) , rect_containing_coordinates_to_draw)
Zipped source code:
Big thx for catching bugs and voicing their propositions to:
- Douglas Rae