Live Coding in pygame

Julian Snitow jsnitow at gmail.com
Sat Aug 26 11:04:18 EDT 2006


Here is a more visual example of the technique presented in Logan
Koester's article, "Live Coding in Python"
(http://www.logankoester.com/mt/2006/07/live_coding_with_python_1.html).

It's very quick-and-dirty in style, partly because half of the program
was written in a moment of inspiration, and the other half was written
and rewritten in real-time... :-D

I've only tested this on Linux, using python 2.4.3. Reports of working
or non-working on other platforms are very welcome. You will of course
need pygame installed. :-)

Paste the following snippets into live.py and livetest.py respectively.
 Run  python live.py.  Edit livetest.py while the program is running,
and save livetest.py to see your results unfold.

Other fun misuses include:
  (1) running multiple instances at once (slow!) and watching your
changes affect them all;
  (2) nested live coding [live.py reloads live-prime.py, which in turn
reloads livetest.py on each iteration]; and
  (3) having livetest.run() return data, and making live.py cache
non-null data received... and pass it back as an argument to
livetest.run().  You could then have reachable, usable data (say, a
bitmap picture) floating around in your program's running instance, yet
no longer mentioned in the program's source code. Ephemeral
programming!

Enjoy. :-)

Julian

################ live.py ####################
import pygame
from pygame.locals import *
from pygame import display

try:
    import livetest
except ImportError:
    livetest = None

pygame.init()

screen = display.set_mode((800, 600))
step = 0

while 1:
    try:
        reload(livetest)
    except:
        print "Failed to reload livetest.py"
    livetest.run(screen, step)
    step += 1
    if step > 2400:    # just a nice, round number ;-)
        step = 0


################ livetest.py ################
import pygame
from pygame.locals import *
from pygame import display

def run(screen, step):
    background = 0x00, 0x00, 0x00
    textcolor = 0x00, 0xcc, 0xff
    text = "Live coding rocks!"
    myfont = pygame.font.SysFont("Arial" , 50)
    textimg = myfont.render(text, 1, textcolor)

    x = step % 800
    y = step % 600

    screen.fill(background)
    screen.blit(textimg, (x, y))
    display.flip()

#########################################




More information about the Python-list mailing list