ThePythonGameBook

learn Python. Create Games

User Tools

Site Tools


en:part2:pygame:step008

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
en:part2:pygame:step008 [2010/01/15 19:56]
Horst JENS
en:part2:pygame:step008 [2011/11/04 06:43]
imapiekindaguy
Line 1: Line 1:
-^ [[:​en:​part2:​step007| ← previous]] ^ [[en:​part2:​start| ↑ Overview]] ^ [[:​en:​part2:​step009| → next ]] ^ +^ [[:en:part2:pygame:step007| ← previous]] ^ [[en:part2:pygame:start| ↑ Overview]] ^ [[:en:part2:pygame:step009| → next ]] ^ 
-====== ​step 008 - loading images ​====== +====== ​Step 008 - Animation ​======
-==== discussion ==== +
-=== loading images === +
-Using pre-fabricated images instead of painting all images yourself with the [[http://​www.pygame.org/​docs/​ref/​draw.html|pygame.draw - functions]] comes very handy. This example shows you how to load images into pygame. Note that in this example, the images must be in the same folder as the python program ! In this example, if pygame can not find the images, it will print an error message and use the image-drawing methods from the previous code example.+
  
 +Remember the Subsurfaces from the last step? And remember that the snake had always the same grinning facial expression? Now, let's make some animated **sprites**((a 2d-object moving around is referred as a [[wp>​Sprite_(computer_graphics)]])) - not pygame sprites, but surfaces that show different images of an animation cycle, like a bird flapping its wings.
  
 +{{ :​en:​part2:​spritesheet008.jpg?​300|}}
 +Instead of painting all the single pictures of an animation cycle myself, I prefer to use ready-made sprite sheets.
  
-=== catching ​file not found error ====+In the data folder, you will find a spritesheet((a graphic ​file with lots of sprites)) from Ari Feldmann'​s Spritelib ( http://​www.flyingyogi.com ) showing several pictures of an animal. If you use Ari's sprite'​s,​ make sure to include his [[:​en:​resources:​glossary:​s:​spritelib_license|license information]] in your program.
  
-This is done using the **try:** **except:** method. See the official documentation:​ +With the help of pygame'​s subsurface command, I will show you how to extract single images from the sprite sheet and use them.
-^  python 2.x  ^  python 3.x  ^ +
-| [[http://​docs.python.org/​reference/​compound_stmts.html#​the-try-statement|try except]] ​ |  [[http://​docs.python.org/​3.1/​reference/​compound_stmts.html#​the-try-statement|try except]] ​ | +
-==== additional resources ==== +
-Put those 2 graphic files in the same folder as **part2step008-loading-image.py** ​to make the program run correctly. If one or both of those files are not found you will see a brown and a blue circle instead: +
-^ filename ^ preview ​ ^ +
-| babytux.png | {{:​en:​part2:​babytux.png|Babytux graphic file (.png) with transparent border}} | +
-| background640x480_a.jpg | {{:​en:​part2:​background640x480_a.jpg?​400|background.jpg file}} \\ left-click to zoom to original size, then right-click to download | +
-| part2step008.py | {{:​en:​part2:​part2step008-loading-image.py|source code}} |  +
-| part2step008.tar.gz | {{:​en:​part2:​part2step008.tar.gz|part2step008 all files zipped package}} |+
  
-==== source code ==== 
  
-<code python| part2step008-loading-image.py>​ +==== Code Discussion ====
-# -*- coding: utf-8 -*- +
-"""​ +
-part2step008-loading-image.py+
  
-loading images from harddisk and using convert_alpha() + 
-This program try to load 2 image files from the harddisk. Both files must be in the + 
-same folder as the program itself. If the image files are not found, images are + 
-created by code instead and an error message is printed. + 
-Note that convert_alpha() is only necessary when the loaded image had + 
-a transparent color. Some .png and .gif files have this, but never .jpg files. + 
-"""​ +===== Source Code on Github ===== 
-import pygame + 
-pygame.init() +To run this example you need
-screen=pygame.display.set_mode((640,​480)) # try out larger values and see what happens ! + 
-try: +^  file  ^  ​in folder ​ ​^ ​ download ​ ^ 
-    background ​pygame.image.load("​background640x480_a.jpg"​) +|  [[https://​github.com/​horstjens/​ThePythonGameBook/​raw/​master/​pygame/​008_animation.py|008_animation.py]]   ''​pygame'' ​ |  Download ​the whole Archive with all files from Github ​\\ ​ https://​github.com/​horstjens/​ThePythonGameBook/​archives/​master ​ | 
-except: +|  [[https://github.com/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/data/char9.bmp|char9.bmp]] \\ [[https://github.com/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/data/char9.bmp|{{:en:part2:pygame:char9_150.jpg|Sprite sheet by Ari Feldman}}]]  |  ''​pygame/​data'' ​ |  ​:::  | 
-    ​print("​Error:​ the image background640x480_a.jpg is not in this folder"​) + 
-    background = pygame.Surface(screen.get_size()) # create a pygame Surface + 
-    background.fill((255,​255,​255)) ​                # fill the background white  +View/Edit/​Download the file directly in Githubhttps://github.com/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/​008_animation.py 
-    pygame.draw.circle(background,​ (50,50,0), (300,250), 200)   # draw circle + 
-try+//click reload in your browser if you see no code here:// 
-    ball = pygame.image.load("​babytux.png"​) +<​html>​ 
-except: + <​script src="​http://​gist-it.appspot.com/​github/​horstjens/​ThePythonGameBook/​blob/​master/​pygame/​008_animation.py">​ 
-    print("​Error:​ the image babytux.png is not in this folder") + </​script></​html>​ 
-    ball = pygame.Surface((50,​50)) ​    #​create a new black surface  + 
-    ball.set_colorkey((0,​0,​0)) ​         + 
-    ​pygame.draw.circle(ball,​ (0,0,255), (25,25),25) # paint blue circle +====== ​Comment this Page ====== 
-#finally: +~~DISQUS~~ 
-background = background.convert() ​ # jpg can not have transparency + 
-ball = ball.convert_alpha() ​       # png image has transparent color  +^ [[:en:part2:pygame:step007| ← previous]] ^ [[en:part2:pygame:start| ↑ Overview]] ^ [[:en:part2:pygame:step009| → next ]] ^
-ballx, bally = 550, 240            # start position of ball surface +
-dx, dy  = 60, 60                   # ball speed in pixel per second ! +
-screen.blit(background,​ (0,​0)) ​    # blit background on screen (overwriting all) +
-screen.blit(ball,​ (ballx, bally)) ​ # blit the ball shape  +
-clock = pygame.time.Clock() ​       # create pygame clock object  +
-mainloop = True +
-FPS = 60                           # desired max. framerate in frames per second.  +
-while mainloop: +
-    milliseconds = clock.tick(FPS) ​ # milliseconds passed since last frame +
-    ​seconds = milliseconds ​1000.0 # seconds passed since last frame +
-    for event in pygame.event.get(): +
-        if event.type == pygame.QUIT: +
-            mainloop = False # pygame window closed by user +
-        elif event.type == pygame.KEYDOWN: +
-            if event.key == pygame.K_ESCAPE: +
-                mainloop = False # user pressed ESC +
-    pygame.display.set_caption("​[FPS]: %.2f X:%.1f Y:%.1f Speed" +
-    "​ [pixel/sec] dx:%.2f dy:%.2f" % (clock.get_fps(), ballx, bally, dx, dy)) +
-    # only blit the part of the background where the ball was (cleanrect) +
-    ​dirtyrect ​background.subsurface((round(ballx,​0),​  +
-                round(bally,​0),​ ball.get_width(),​ ball.get_height())) +
-    # comment out the next line for a funny effect ! +
-    ​screen.blit(dirtyrect,​ (round(ballx,​0),​ round(bally,​0))) ​ +
-    #​calculate new center of ball  +
-    ballx +dx * seconds # time based movement +
-    bally +dy * seconds +
-    # bounce ball if out of screen +
-    if ballx < 0: +
-        ballx +
-        dx *-1  +
-    elif ballx + ball.get_width() > screen.get_width():​ +
-        ballx screen.get_width() - ball.get_width() +
-        dx *-1 +
-    if bally < 0: +
-        bally +
-        dy *-1 +
-    elif bally + ball.get_height() > screen.get_height():​ +
-        bally screen.get_height() - ball.get_height() +
-        dy *-1 +
-    # paint the ball    ​ +
-    ​screen.blit(ball,​ (round(ballx,​0),​ round(bally,​0))) ​    +
-    pygame.display.flip() ​         # flip the screen 30 times a second ​               # flip the screen 30 (or FPS) times a second +
-</​code>​ +
-^ [[:​en:​part2:​step007| ← previous]] ^ [[en:​part2:​start| ↑ Overview]] ^ [[:​en:​part2:​step009| → next ]] ^+