Debian Codegraph @

docs/examples/CellularAutomata.py

raw symbols SCIP
1 from SimPy.Simulation import *
2 """CellularAutomata.py
3 Simulation of two-dimensional cellular automata. Plays game of Life.
4 """
5
6 class Autom(Process):
7 def __init__(self,coords):
8 Process.__init__(self)
9 self.x=coords[0]
10 self.y=coords[1]
11 self.state=False
12
13 def nrActiveNeighbours(self,x,y):
14 nr=0
15 coords=[(xco+x,yco+y) for xco in (-1,0,1) for yco in (-1,0,1) if not (xco==0 and yco==0)]
16
17 for a_coord in coords:
18 try:
19 if cells[a_coord].state:
20 nr += 1
21 except KeyError:
22 ## wrap around
23 nux=divmod(a_coord[0],size)[1]
24 nuy=divmod(a_coord[1],size)[1]
25 if cells[(nux,nuy)].state: nr += 1
26 return nr
27
28 def decide(self,nrActive):
29 return (self.state and (nrActive == 2 or nrActive == 3) or (nrActive==3))
30
31 def celllife(self):
32 while True:
33 #calculate next state
34 temp=self.decide(self.nrActiveNeighbours(self.x,self.y))
35 yield hold,self,0.5
36 #set next state
37 self.state=temp
38 yield hold,self,0.5
39
40 class Show(Process):
41 def __init__(self):
42 Process.__init__(self)
43
44 def picture(self):
45 while True:
46 print "Generation %s" %now()
47 for i in range(size):
48 for j in range(size):
49 if cells[(i,j)].state:
50 print "*",
51 else:
52 print ".",
53 print
54 print
55 yield hold,self,1
56
57 size=20
58 cells={}
59 initialize()
60 for i in range(size):
61 for j in range(size):
62 a=cells[(i,j)]=Autom((i,j))
63 activate(a,a.celllife())
64
65 ##R-pentomino
66 cells[(9,3)].state=True
67 cells[(10,3)].state=True
68 cells[(9,4)].state=True
69 cells[(8,4)].state=True
70 cells[(9,5)].state=True
71
72 cells[(5,5)].state=True
73 cells[(5,6)].state=True
74 cells[(4,5)].state=True
75 cells[(4,6)].state=True
76 cells[(4,7)].state=True
77 cells[(10,10)].state=True
78 cells[(10,11)].state=True
79 cells[(10,12)].state=True
80 cells[(10,13)].state=True
81 cells[(11,10)].state=True
82 cells[(11,11)].state=True
83 cells[(11,12)].state=True
84 cells[(11,13)].state=True
85
86 print 'CellularAutomata'
87 s=Show()
88 whenToStartShowing=10
89 activate(s,s.picture(),delay=whenToStartShowing)
90 nrGenerations=30
91 simulate(until=nrGenerations)