Skip to content

Commit 76db99d

Browse files
authored
Add files via upload
1 parent d14f1a6 commit 76db99d

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

ex11_1ManuallyGrowingCA.pyde

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Using the keyPressed() function (for reference, see Chapter 10) to manually grow the CA.
2+
3+
GRID_H=60 #grid height
4+
GRID_W=60 #grid width
5+
SZ=18 #size of cell
6+
7+
def createCellList():
8+
'''Creates a big list of OFF cells with
9+
one ON Cell in the center'''
10+
newList=[]#empty list for cells
11+
#populate the initial cell list
12+
for j in range(GRID_H):
13+
newList.append([]) #add empty row
14+
for i in range(GRID_W):
15+
newList [j].append(Cell(i,j,0)) #add off Cells or zeroes
16+
#center cell is set to on
17+
newList [GRID_H//2][GRID_W//2].state = 1
18+
return newList
19+
20+
class Cell:
21+
def __init__(self,c,r,state=0): #initially, cell's state is OFF
22+
self.c = c
23+
self.r = r
24+
self.state = state
25+
26+
def display(self):
27+
if self.state == 1:
28+
fill(0) #black
29+
else:
30+
fill(255) #white
31+
rect(SZ*self.r,SZ*self.c,SZ,SZ)
32+
33+
def checkNeighbors(self):
34+
if self.state == 1:
35+
return 1 #on Cells stay on
36+
37+
neighbs = 0 #check the neighbors
38+
# check neighbors on left, right, down, up of the current cell
39+
for dr,dc in [[-1,0],[1,0],[0,-1],[0,1]]:
40+
try:
41+
if cellList[self.r + dr][self.c + dc].state == 1:
42+
neighbs += 1
43+
except IndexError:
44+
continue
45+
if neighbs in [1,4]:
46+
return 1
47+
else:
48+
return 0
49+
50+
def setup():
51+
global SZ,cellList
52+
size(600,600)
53+
noStroke()
54+
SZ=width // GRID_W
55+
cellList = createCellList()
56+
57+
def draw():
58+
global generation,cellList
59+
for row in cellList:
60+
for cell in row:
61+
cell.display()
62+
63+
def update(cellList):
64+
newList = []
65+
for r,row in enumerate(cellList):
66+
newList.append([])
67+
for c,cell in enumerate(row):
68+
newList[r].append(Cell(c,r,cell.checkNeighbors()))
69+
return newList[::]
70+
71+
#as the mouse clicks, update the cellList
72+
def mouseClicked():
73+
global cellList
74+
cellList = update(cellList)

0 commit comments

Comments
 (0)