Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/algorithm_cellauto.py
1240 views
1
#!/usr/bin/env python
2
"""
3
CellularAutomata.py: Wolfram-style cellular automata in Python
4
5
Options:
6
-h # Use a screen of height # for the simulation
7
-w # Use a screen of width # for the simulation
8
-r Use a random initial row (rather than the standard single 1 in the middle)
9
-R # Use rule # for the simulation
10
11
Requires python-image (PIL package) installed.
12
Fills up an initial cell and runs a particular rule of Cellular Automata.
13
14
.. image:: https://lh4.googleusercontent.com/_ny1HYbb2lDw/Tazon5TsgXI/AAAAAAAAKgU/ud6v_XhcHB0/s288/bs.png
15
16
*I can't remember the source, if you claim/know, please inform.*
17
18
"""
19
20
import getopt,sys
21
from random import randint
22
23
24
def ca_data(height,width,dorandom,rulenum):
25
# Create the first row, either randomly, or with a single 1
26
if dorandom:
27
first_row = [randint(0,1) for i in range(width)]
28
else:
29
first_row = [0]*width
30
first_row[width/2] = 1
31
results = [first_row]
32
33
# Convert the rule number to a list of outcomes.
34
rule = [(rulenum/pow(2,i)) % 2 for i in range(8)]
35
36
for i in range(height-1):
37
data = results[-1]
38
# Determine the new row based on the old data. We first make an
39
# integer out of the value of the old row and its two neighbors
40
# and then use that value to get the outcome from the table we
41
# computed earlier
42
new = [rule[4*data[(j-1)%width]+2*data[j]+data[(j+1)%width]]
43
for j in range(width)]
44
results.append(new)
45
return results
46
47
def pil_render(data,height,width,fname="bs.png"):
48
import Image, ImageDraw
49
img = Image.new("RGB",(width,height),(255,255,255))
50
draw = ImageDraw.Draw(img)
51
52
for y in range(height):
53
for x in range(width):
54
if data[y][x]: draw.point((x,y),(0,0,0))
55
img.save(fname,"PNG")
56
return
57
58
def main():
59
opts,args = getopt.getopt(sys.argv[1:],'h:w:rR:')
60
height = 500
61
width = 500
62
dorandom = 0
63
rule = 22
64
for key,val in opts:
65
if key == '-h': height = int(val)
66
if key == '-w': width = int(val)
67
if key == '-r': dorandom = 1
68
if key == '-R': rule = int(val)
69
data = ca_data(height,width,dorandom,rule)
70
pil_render(data,height,width)
71
return
72
73
if __name__ == '__main__': main()
74
75