Title: Fractal Example

Author: Pete Shinners (pete at shinners.org)
Submission date: April 19, 2001

Description: An example of animated colormaps

Download: fractal.zip

pygame version required: Any
SDL version required: Any
Python version required: 2.0

Comments: Palette cycling or shifting is one of the oldest computer animation techniques. When hardware speeds didn't permit large blits in real time, a developer would often simulate movement by changing a display's underlying palette. Pete's example demonstrates the principle - first you blit a multicoloured (even grayscale, in this case) image once, then cycle the display's palette. As Pete notes, no subsequent blits are necessary; you don't even need to call update() or flip(). Simply calling set_palette() in a tight loop creates the illusion of motion. This technique is suitable for many static sprite-like animation effects - flowing waterfalls, rolling waves, etc.

Messages: 0

#!/usr/bin/env python

Palette animation example

Pete Shinners
April 19, 2001

In this example we are loading a greyscale fractal like
image. We then create an animated colormap and apply it to
the display. Note we could probably use Numeric or something
to create the color palette a bit quicker and easier, but in
this case it's fast enough to do it with python.

One thing I noticed is that on windows, the "windib" video
device runs over twice as fast as the "directx" one. Go figure.

import pygame, pygame.image
from pygame.locals import *

def build_palette(step):
    "build a palette. that is a list with 256 RGB triplets"
    loop = range(256)
    #first we create a 256-element array. it goes from 0, to 255, and back to 0
    ramp = [abs((x+step*3)%511-255) for x in loop]
    #using the previous ramp and some other crude math, we make some different
    #values for each R, G, and B color planes
    return [(ramp[x], ramp[(x+32)%256], (x+step)%256) for x in loop]

def main():
    "run the example"

    #initialize, note we want an 8bit display here
    screen = pygame.display.set_mode((640, 480), HWSURFACE|HWPALETTE, 8)

    #create a basic palette to start with

    #print a little information
    print 'SCREEN: hardware=%d, depth=%d' % \
          (screen.get_flags()&HWSURFACE, screen.get_bitsize())

    #load our image and put it on the screen
    img = pygame.image.load('fractal.gif')
    screen.blit(img, (0, 0))

    #loop, simply create a new colormap with a different input value
    step = 0
    while pygame.event.poll().type not in showstoppers:
        palette = build_palette(step)
        #note that we needn't flip() or update() the
        #display when only changing the palette
        step += 1

if __name__ == '__main__':main()    

Main - Repository - Submit - News