The Python Game Book

code games. learn Python.

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 20:46]
horst
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. +With the help of pygame's subsurface command, I will show you how to extract single images from the sprite sheet and use them.
-<code python> +
-try: +
-   #do something risky that may not work like loading files +
-   #... +
-except: +
-   #do that if an error occurs inside the try block +
-   #... +
-# continue here if no error +
-</code>+
  
- Also see the official documentation: 
-==== documentation ==== 
-^  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 ==== +==== Code Discussion ====
-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> 
-# -*- 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 +===== Source Code on Github ===== 
-a transparent color. Some .png and .gif files have this, but never .jpg files. + 
-""" +To run this example you need
-import pygame + 
-pygame.init() +^  file  ^  in folder   download  ^ 
-screen=pygame.display.set_mode((640,480)) # try out larger values and see what happens ! +|  [[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  | 
-try: +|  [[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''  |  :::  | 
-    background pygame.image.load("background640x480_a.jpg") + 
-except: + 
-    print("Error: the image background640x480_a.jpg is not in this folder"+View/Edit/Download the file directly in Githubhttps://github.com/horstjens/ThePythonGameBook/blob/master/pygame/008_animation.py 
-    background = pygame.Surface(screen.get_size()) # create a pygame Surface + 
-    background.fill((255,255,255))                 # fill the background white  +//click reload in your browser if you see no code here:// 
-    pygame.draw.circle(background, (50,50,0), (300,250), 200)   # draw circle +<html> 
-try+ <script src="http://gist-it.appspot.com/github/horstjens/ThePythonGameBook/blob/master/pygame/008_animation.py"> 
-    ball = pygame.image.load("babytux.png") + </script></html> 
-except: + 
-    print("Error: the image babytux.png is not in this folder") + 
-    ball = pygame.Surface((50,50))     #create a new black surface  +====== Comment this Page ====== 
-    ball.set_colorkey((0,0,0))          +~~DISQUS~~ 
-    pygame.draw.circle(ball, (0,0,255), (25,25),25) # paint blue circle + 
-#finally: +^ [[:en:part2:pygame:step007| ← previous]] ^ [[en:part2:pygame:start| ↑ Overview]] ^ [[:en:part2:pygame:step009| → next ]] ^
-background = background.convert()  # jpg can not have transparency +
-ball = ball.convert_alpha()        # png image has transparent color  +
-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 ]] ^+