-
Notifications
You must be signed in to change notification settings - Fork 0
/
sketch.js
127 lines (109 loc) · 2.45 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
120
121
122
123
124
125
126
127
// Daniel Shiffman
// http://codingtra.in
// http://patreon.com/codingtrain
// Game of Life
// Video: https://youtu.be/FWSR_7kZuYg
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 grid;
let cols;
let rows;
let resolution = 10;
function setup() {
createCanvas(600, 400);
cols = width / resolution;
rows = height / resolution;
grid = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
grid[i][j] = floor(random(3));
}
}
}
function draw() {
background(0);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let x = i * resolution;
let y = j * resolution;
if (grid[i][j] == 1) {
fill(255);
stroke(0);
rect(x, y, resolution - 1, resolution - 1);
}
if (grid[i][j] == 2) {
fill("#FF0000");
stroke(0);
rect(x, y, resolution - 1, resolution - 1);
}
}
}
let next = make2DArray(cols, rows);
// Compute next based on grid
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j];
// Count live neighbors!
let sum = 0;
let neighbors1 = countNeighbors(grid, i, j,1);
let neighbors2 = countNeighbors(grid, i, j, 2);
let rand = floor(random(50))
/*
if(rand == 2){
state = 2;
}
else if(rand > 47){
state = 1;
}*/
if (state == 0 && (neighbors1 == 3 || neighbors2 == 3)) {
if(neighbors1 > neighbors2){
next[i][j] = 1;
}else if (neighbors1 < neighbors2){
next[i][j] = 2;
}else{
next[i][j] = floor(random(3));
}
//White are good at attacking, red at invading and converting
} else if (state == 1 && (neighbors1 < 2 || neighbors1 > 3||neighbors2 > 1)) {
if((neighbors2 > 3)){
next[i][j] = 2;
}else{
//Die stochastically
next[i][j] = 0;
}
}else if (state == 2 && (neighbors2 < 2 || neighbors2 > 3|| neighbors1 > 1)) {
if((neighbors1 > 3)){
next[i][j] = 1;
}else{
next[i][j] = 0;
}
}else {
next[i][j] = state;
}
}
}
grid = next;
}
function countNeighbors(grid, x, y, type) {
let sum = 0;
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
let col = (x + i + cols) % cols;
let row = (y + j + rows) % rows;
if(grid[col][row]==type){
sum += grid[col][row]/type;
}
}
}
if(grid[x][y] == type){
sum -= grid[x][y]/type;
}else{
sum -grid[x][y];
}
return sum;
}