-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
146 lines (114 loc) · 3.26 KB
/
index.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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;
let clr;
let vi;
let cnt;
let dxy = [[1, 0], [1, 1], [1, -1], [0, 1], [0, -1], [-1, 1], [-1, 0], [-1, -1]]
function setup() {
createCanvas(800, 600);
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] = new Cell(round(Math.random()),0);
}
}
}
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;
cur = grid[i][j]
strokeWeight(9);
if (grid[i][j].state == 1) {
// <5 blue
if ( cur.size < 5) {
clr = color(100, 100, 255);
stroke(clr);
point(x, y)
}
// 10 ~ 20 red
else if (cur.size >= 5 && cur.size < 20) {
clr = color(255, 100,100 );
stroke(clr);
point(x,y)
}
// >30 green
else {
clr = color(100, 255,100);
stroke(clr);
point(x,y)
}
}
}
}
let next = make2DArray(cols, rows);
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
let state = grid[i][j].state;
let sum = 0;
for (let k = 0; k < 8; k++) {
let col = (i + dxy[k][0] +cols) % cols
let row = (j + dxy[k][1] + rows) % rows;
sum += grid[col][row].state
}
let neighbors = sum;
if (state === 0 && neighbors === 3) {
next[i][j] = new Cell(1,grid[i][j].size);
} else if (state === 1 && (neighbors < 2 || neighbors > 3)) {
next[i][j] = new Cell(0,grid[i][j].size);
} else {
next[i][j] = new Cell(state,grid[i][j].size);
}
}
}
grid = next;
vi = make2DArray(cols, rows);
for (let i = 0; i < cols; i++){
for (let j = 0; j < rows; j++){
resetVi(vi);
cnt=0
dfs(i, j)
grid[i][j].size = cnt;
}
}
}
const dfs = (y,x) => {
if (y < 0 || x < 0 || y >= cols || x >= rows) return;
if (vi[y][x] ===1) return;
if (grid[y][x].state === 0) return;
vi[y][x] = 1;
cnt++;
dfs(y + 1, x);
dfs(y - 1, x);
dfs(y, x + 1);
dfs(y, x - 1);
dfs(y+1, x + 1);
dfs(y+1, x - 1);
dfs(y-1, x + 1);
dfs(y-1, x - 1);
}
const resetVi = (x) => {
for (let i = 0; i < cols; i++){
for (let j = 0; j < rows; j++) {
x[i][j] = 0;
}
}
}
function mouseClicked(e) {
console.log(e.target)
stroke(255);
}
const a = document.appendChild()