-
Notifications
You must be signed in to change notification settings - Fork 0
/
sketch.js
119 lines (93 loc) · 1.79 KB
/
sketch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// makes an empty 2d array
function make2dArray(cols, rows)
{
let arr = new Array(cols);
for(let i = 0; i < arr.length; i++)
{
arr[i] = new Array(rows);
}
return arr;
}
let count_generations = 1
let grid;
let cols;
let rows;
let scale =20;
function setup()
{
var canvas = createCanvas(500,500);
canvas.parent("canvas")
grid = make2dArray(40,40)
cols = width/scale;
rows = width/scale;
for(let i = 0; i < cols; i++)
{
for(let j = 0; j < rows; j++)
{
grid[i][j] = floor(random(2));
}
}
console.log(grid);
}
function draw()
{
background (0);
for(let i = 0; i < cols; i++)
{
for(let j = 0; j < rows; j++)
{
let x = i*scale;
let y = j*scale;
if(grid[i][j]==1)
{
fill (3,252,65)
}
else
{
fill (0)
}
rect(x,y,scale,scale,5)
}
}
count_generations += 1
document.getElementById("gen-num").innerText = "Generations: " + count_generations.toString()
let nextGen = make2dArray(cols,rows)
for(let i = 0; i < cols; i++)
{
for(let j = 0; j < rows; j++)
{
let state = grid[i][j];
// count the live neighbours!!
let neighbours = count(grid,i,j);
if(state == 0 && neighbours==3)//overpopulation
{
nextGen[i][j] = 1;
}
else if(state==1 && neighbours<2||neighbours>3)
{
nextGen[i][j] = 0;
}
else
{
nextGen[i][j] = grid[i][j]
}
}
}
grid = nextGen;
}
// function to count the live neighbours
function count(grid,x,y)
{
let sum=0
for(let i=-1 ; i<2 ; i++)
{
for(let j=-1; j<2 ; j++)
{
let Ecol = (x+i + cols)%cols;
let Erow = (y+j + rows)%rows;
sum+= grid[Ecol][Erow];
}
}
sum-=grid[x][y];
return sum;
}