""" by Kirby Urner, 4D Solutions Version 0.5 Revised: Feb 12, 2007 2:37 PM -- Gregor Lingl added canvas3 option (Tkinter) Revised: May 10, 2004 9:10 PM -- split into 3 modules, canvas2 uses newer graphics.py by Dr. John Zelle Revised: May 8, 2004 8:00 PM -- changed to rectangles in Tk, other fixes Revised: May 8, 2004 5:48 PM -- added Tk output (see edu-sig of today) Thread on edu-sig: More on graphics with graphics.py (Zelle's) http://mail.python.org/pipermail/edu-sig/2007-February/thread.html Usage: import nks nks.t1(30,200,100,4) or run as a top level process. """ # uncomment one or the other, reload if switching # from canvas1 import Canvas # <-- PIL # from canvas2 import Canvas # <-- graphics.py from canvas3 import Canvas # <-- Tkinter.py def base2(n,pad=8): output = [] while n > 1: digit = n%2 n //= 2 output.append(str(digit)) output.append(str(n)) output.reverse() return (''.join(output)).zfill(pad) def makerule(n): therule = {} output = base2(n) for i in range(8): therule[base2(7-i,3)] = output[i] return therule def sayrule(themap): for i in range(7,-1,-1): thekey = base2(i,3) print "%s --> %s" % (thekey, themap[thekey]) class Pattern(object): def __init__(self, n, width=40, rows=20, pixelsize = 1): self.width = width self.rule = makerule(n) self.therow = ('0' * (width//2) + '1' + '0' * (width - width//2 - 1)) self.rownum = 0 # Canvas imported from either of 2 modules self.canvas = Canvas(width,rows,pixelsize) def next(self): while True: yield self.therow for i in range(len(self.therow)): if self.therow[i]=='1': self.canvas.drawcell((i,self.rownum)) newrow = ['0'] * len(self.therow) for i in range(1,len(self.therow)-1): thekey = (self.therow[i-1] + self.therow[i] + self.therow[i + 1]) newrow[i] = self.rule[thekey] self.therow = ''.join(newrow) self.rownum += 1 # self.canvas.c.update() # comment out for faster raster def showimage(self): self.canvas.showimage() def __iter__(self): return self.next() def t1(rule, width, height, pixelsize=1): p = Pattern(rule ,width, height, pixelsize) g = p.next() for i in range(width/2): g.next() p.showimage() if __name__ == '__main__': t1(30,200,100,4)