Live Coding in pygame

J

Julian Snitow

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()

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top