Pygame Computer Art (Python)

vegaseat 0 Tallied Votes 218 Views Share

Sometime in my childhood biology class I heard that the fancy colors of butterfly wings aren't really true colors, but interference patterns. This program claims to create interference patterns using a series of 3d sine waves using Python's popular pygame module. The whole contrivance is pretty to look at, and you can easily change the patterns. I am just a softy for this kind of thingamajig.

# Python/Pygame computer art using interference patterns
# tested with Python24 and Pygame171   vegaseat    02feb2007

# give pygame an abbreviated namespace
import pygame as pg
import math

# initialize pygame
pg.init()

# width and height of screen
w = 500
h = 350
# pg.display.set_mode(size, [flags, [depth]]) -> Surface
# create a screen/window and give it a title
screen = pg.display.set_mode((w, h), pg.DOUBLEBUF, 32)
pg.display.set_caption('elaborate calculations in progress ...')

# pg.surfarray.array3d(Surface) -> Array 
pixels = pg.surfarray.pixels3d(screen)
width = len(pixels)-1
height = len(pixels[0])-1

# modify these values for different patterns ...
# (integer size gives triangle patterns)
size = 50.0       # 50.0  
slant1 = 1.7      # 1.7
slant2 = 0.5      # 1.5
melt = 0.1        # 0.1

for y in xrange(height):
    for x in xrange(width):
        z1 = math.sin(x/size*slant1*math.pi)
        z2 = math.sin((x/3+y)/size*slant2*math.pi)
        z3 = math.sin(y/size*melt*math.pi)
        z = abs(z1+z2+z3)*255
        # build the 3d image array
        pixels[x,y] = (z, z/4, z*4)

# now the 3d image will show
pg.display.update()
pg.display.set_caption('interference patterns')

# run event loop and provide exit conditions
while True:
    for event in pg.event.get():
        # exit on window title 'x' click
        if event.type == pg.QUIT:
            raise SystemExit