Animation using PyGame

vegaseat 2 Tallied Votes 364 Views Share

Just bouncing a red ball within the frame of a window, the twist here is that the image is stored within the code as a base64 encoded string of the gif image. This way you only have to distribute one file. The Python code is heavily commented, so you can follow what is going on.

# bounce a red ball whose image is stored within the code
# experiments with module pygame from: http://www.pygame.org/
# tested with Python25 and PyGame171    vegaseat     02sep2007

import pygame as pg
import base64

"""
# use this short program to create the base64 encoded image string
# (base64 encoding simply produces a readable string from a binary image)
# then copy and paste the result into your pygame program ...
import base64
gif_file = "ball_r.gif"
print "gif64='''\\\n" + base64.encodestring(open(gif_file, 'rb').read()) + "'''"
"""

gif64='''\
R0lGODlhQABAAPcAACEBAY8DA9wQILcED1ECAqMECOsaL8oKGTgBAXADA5kEBeQVJ8EIFK0EC+wg
NS8BAWUCAtMOH0gCAoQDAykBAZkEBNwSJsEGEFsCAq0ECOwdNdMMGkABAXoDA6MEBuUXLsoJFbcE
DPIgNQAAAJ0FBAAAAAAAAAAAAAAABQAAAAAAAAAAAPEGCt0FBQQAAAAAAF4CBAkAAN8FBVUCAgAA
AgAAAAAAAAAAAAEBgAAAAQUAAwIC7gAAKt0FBQUBZgAAAAAABgAAAAAAAAAAAAsAAN4FBQQAAAAA
AOgPDmoCAu8GBlUCAmoDBwgAAOsFBVUCAvIGRfIGDfMHz/IGOhgGZXUDA+sFBVUCAugMoQoCwuEH
0VYCNgACBQAAAAUAAAAAAAACAwAAAAAAAAAAAF2IVdsGDAgFygz4PwssCD0CHwpqGQAAAAII4AAA
AAAAHQAAAF4CAwAAHgAAFbEEBAIL6gAABgICygAANPMLavIGBvIGBvIGBvMHofQH2vIGJvIGBgAB
AAAAAAAAAAAAAAID4AAAAAAAHQAAAAECZAAAAAAAAAAAAEtDBQV1BQnOCQRXBD9CBAAAAArVCgRX
BA1KBESeCA7PCQRXBBsoBRGdherW9lpaWgaQBgeUBwnSCQI2AgsfAkflDAAEAAAAAAvvCwEOAQ/k
CgRXBE0CAt0FBQQAAAAAAAAAAAAAAAAAAA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xIa5dfDoQiY/1tpxxpv+KpQQYcJCWBhor6F1oFTKLa5YgpASAmrJZu
GGCyMDqwgWAAYFAVdw5ime5/dlmr7AIYnGXuoq8mN1oFB0ToroRBCgRBtEjWW9dW+6YZVgL+Hksm
rPfmWzCMHyAMwL9XphvtcgyI8LCTQEpa7nr21ruhXeCqaQEGAomJLrfuAViyhBqMO9CzKu44Z20h
vOykCCG4BsCw6DZ4cwMbD+hABggMliuDWB7J3qxFgxhsghSvXObNPOosH5AQLGRkzeqGHF/U4pHY
FgdW0tXdn8ltQLDWqYkQgM8CJXqlyKM9SjZvQQ7/qa2GQavdYQVEw71mCFKytLR3a7v3wd6n5bXn
cEaOqm6HYxuuF5slPrW4pdsFQDLkeu35VEKVG0vvch+S3tsAh1oEVXZKkmppfJp3vBJHDklgZeC7
6m24Bp6qBdFAfjKtOuQOXLCqTGjduF60ozYXNYUWym7QfiCvXlsDWtd3X41T/kw73h4E8GLBIlhw
33DHV4Q24GaK5muM4OEl7vgW5QfAfou5WFVGtzXe5IUBBjrPawozmwQsyF7tydxzDLAXvvgmAJZZ
oP8y0hnkoKsC9wuPvrSigQu0RjjwQ1BEErOYI31HX6ihoGo0AIIAmGWB5NsgleBile5QK4Z86YoG
Wj5QGfNskEgqNEhHpEKVDoXgAyLQGFd64wADLOAAHijLWXBYGB02pSZSyclO8LUAoAjlAkU5ikq8
yLskMuUgHgGJSBJAkpOkZCVu5CIbL6KSBxgxLWvco0sCAgA7
'''

# convert back to a binary image to save to a file in the working directory
ball = base64.b64decode(gif64)
fout = open("ball_r.gif","wb")
fout.write(ball)
fout.close()

# initialize pygame
pg.init()

# now you can use the gif file you just saved
image_file = "ball_r.gif"

# image moves [x, y] at a time
im_dir = [2, 1]

# pygame uses an RGB color tuple
black = (0,0,0)
# screen width and height
sw = 600
sh = 480
# create a screen
screen = pg.display.set_mode((sw, sh))
# give the screen a title
pg.display.set_caption('bouncing ball (press escape to exit)')

# load the ball image file
image = pg.image.load(image_file).convert()
# get the rectangle that the image occupies
im_rect = image.get_rect()

# the event loop also loops the animation code
while True:
    pg.event.pump()
    keyinput = pg.key.get_pressed()
    # exit on corner 'x' click or escape key press
    if keyinput[pg.K_ESCAPE] or pg.event.peek(pg.QUIT):
        raise SystemExit

    # set the move
    im_rect = im_rect.move(im_dir)
    # detect the boundaries and change directions
    # left/right boundaries are 0 to sreen width
    if im_rect.left < 0 or im_rect.right > sw:
        im_dir[0] = -im_dir[0]
    # top/bottom boundaries are 0 to screen height
    if im_rect.top < 0 or im_rect.bottom > sh:
        im_dir[1] = -im_dir[1]
    # this erases the old sreen with black
    screen.fill(black)
    # put the image on the screen
    screen.blit(image, im_rect)
    # update screen
    pg.display.flip()
Shadow14l 0 Light Poster

I have a question!!!!!

Whenever you put your mouse over something, that makes one of those floating labels appear when you hover over something something interesting happens.

What happens is the ball speeeeeeeeeeeeeds UP!

Any explanation :O?

tomtetlaw -1 Posting Pro

Nice work, i will definitley try this is the future

Arkapravo 0 Newbie Poster

Excellent code ! Vegaseat you are the Guru !

If there was to be a clock item and a limit to clock tick (ie : time_passed = clock.tick(30) ) then the motion of the ball is lot more in control. Without which it gets very quick and difficult to observe on a fast processor.

Arkapravo 0 Newbie Poster

Hi Vegaseat !

A bit of revision and a newer animation of your code. I have also made the ball to stop after some time.

http://programming-unlimited.blogspot.com/2009/06/21-pounds.html

Thanks once again !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.