Path: blob/master/languages/python/algorithm_cellauto.py
1240 views
#!/usr/bin/env python1"""2CellularAutomata.py: Wolfram-style cellular automata in Python34Options:5-h # Use a screen of height # for the simulation6-w # Use a screen of width # for the simulation7-r Use a random initial row (rather than the standard single 1 in the middle)8-R # Use rule # for the simulation910Requires python-image (PIL package) installed.11Fills up an initial cell and runs a particular rule of Cellular Automata.1213.. image:: https://lh4.googleusercontent.com/_ny1HYbb2lDw/Tazon5TsgXI/AAAAAAAAKgU/ud6v_XhcHB0/s288/bs.png1415*I can't remember the source, if you claim/know, please inform.*1617"""1819import getopt,sys20from random import randint212223def ca_data(height,width,dorandom,rulenum):24# Create the first row, either randomly, or with a single 125if dorandom:26first_row = [randint(0,1) for i in range(width)]27else:28first_row = [0]*width29first_row[width/2] = 130results = [first_row]3132# Convert the rule number to a list of outcomes.33rule = [(rulenum/pow(2,i)) % 2 for i in range(8)]3435for i in range(height-1):36data = results[-1]37# Determine the new row based on the old data. We first make an38# integer out of the value of the old row and its two neighbors39# and then use that value to get the outcome from the table we40# computed earlier41new = [rule[4*data[(j-1)%width]+2*data[j]+data[(j+1)%width]]42for j in range(width)]43results.append(new)44return results4546def pil_render(data,height,width,fname="bs.png"):47import Image, ImageDraw48img = Image.new("RGB",(width,height),(255,255,255))49draw = ImageDraw.Draw(img)5051for y in range(height):52for x in range(width):53if data[y][x]: draw.point((x,y),(0,0,0))54img.save(fname,"PNG")55return5657def main():58opts,args = getopt.getopt(sys.argv[1:],'h:w:rR:')59height = 50060width = 50061dorandom = 062rule = 2263for key,val in opts:64if key == '-h': height = int(val)65if key == '-w': width = int(val)66if key == '-r': dorandom = 167if key == '-R': rule = int(val)68data = ca_data(height,width,dorandom,rule)69pil_render(data,height,width)70return7172if __name__ == '__main__': main()737475