Bouncing Image (Python & Pygame)

vegaseat 1 Tallied Votes 861 Views Share

This little program uses Python and it's module pygame to do some sprite type animation. The rectangle that contains the image is moved and bounced within the window's frame. Pretty crude, since the whole screen frame is erased for each move. Actually it works smooth enough, and is relatively flicker free. You could improve the code by keeping track of the image's rectangle, refreshing and updating just it.

# experiments with module pygame
# free from:
# move a rectangle with an image in it
# if you have the image of a ball, you have a bouncing ball
# tested with Python24 and Pygame171    vegaseat   02feb2007

import pygame as pg

# initialize pygame

# download the image from: 
# or use an image you have (.bmp  .jpg  .png  .gif)
# ideally the image should have a black background or
# you have to fill the screen with the matching background
image_file = "ball_r.gif"

# image moves [x, y] at a time
# you can change trajectory, speed and direction
im_dir = [2, 1]

# RGB color tuple for screen background
black = (0,0,0)
# screen width and height
sw = 640
sh = 480
# create a screen
screen = pg.display.set_mode((sw, sh))
# give the screen a title
pg.display.set_caption('bouncing image (press escape to exit)')

    # load an image
    # convert() unifies the pixel format for faster blit
    image = pg.image.load(image_file).convert()

    print "Please supply image file %s" % image_file
    raise SystemExit

# get the rectangle the image occupies
im_rect = image.get_rect()

# the event loop also loops the animation code
while True:
    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 < 0 or im_rect.bottom > sh:
        im_dir[1] = -im_dir[1]
    # this erases the old sreen with black
    # put the image on the screen
    screen.blit(image, im_rect)
    # update screen
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a note:
If you use Python version 2.5, you have to wait for a few more weeks until Pygame version 1.8 is released. There are lots of folks waiting for that one! Keep checking

Be a part of the DaniWeb community

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