[Edu-sig] re: new graphics.py etc.
Gregor Lingl
glingl at aon.at
Mon May 10 15:43:20 EDT 2004
Thanks, too, John!
By changing 2 or 3 lines in Kirbys code I arrived
at a tiny animation. (attachment). It's intended to
run from the command line.
Question: The raw_input() in line 70 seems to be
indispensable. It doesn't work without it. Why is
this the case?
Regards, Gregor
>
>
-------------- next part --------------
"""
Kirby Urners nks.py using Tkinter with
tiny animation
"""
# uncomment one or the other, reload if switching
from graphics import GraphWin, Point, Rectangle
class Canvas(object):
def __init__(self, width, rows, pixelsize):
self.pixelsize = pixelsize
self.c = GraphWin('NKS',width*pixelsize, rows*pixelsize, False)
self.c.setBackground('black')
def drawcell(self, thepoint):
therow = thepoint[0]*self.pixelsize
thecol = thepoint[1]*self.pixelsize
therect = Rectangle(Point(therow, thecol),
Point(therow + self.pixelsize-1,
thecol + self.pixelsize-1))
therect.setFill('yellow')
therect.setOutline('yellow')
therect.draw(self.c)
def showimage(self):
self.c.flush()
g = raw_input("Hit Enter on this line to close window")
self.c.close()
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)
self.canvas.c.flush() # <===
raw_input("Hit Enter to start automaton!") # <===
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
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.canvas.c.flush()
p.showimage()
if __name__ == '__main__':
t1(30,200,100,4)
More information about the Edu-sig
mailing list