-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20181117.ts
More file actions
100 lines (86 loc) · 2.34 KB
/
20181117.ts
File metadata and controls
100 lines (86 loc) · 2.34 KB
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
import Doodle from "./Doodle";
import { Colors } from "./Colors";
const screenSize = 128;
const gridCount = 32;
const gridSize = screenSize / gridCount;
const frameCount = 5;
const resetIterations = 10;
export class DailyDoodle implements Doodle {
private cells: boolean[];
private frame: number;
private iterationCount: number;
public init() {
this.reset();
}
public update() {
this.frame++;
if (this.frame >= frameCount) {
this.applyRules();
this.frame = 0;
}
}
public draw(ctx: CanvasRenderingContext2D) {
ctx.clearRect(0, 0, screenSize, screenSize);
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < this.cells.length; i++) {
if (!this.cells[i]) {
continue;
}
const x = i % gridCount;
const y = Math.floor(i / gridCount);
ctx.fillStyle = Colors.darkGreen;
ctx.fillRect(x * gridSize, y * gridSize, gridSize, gridSize);
}
}
private reset() {
this.cells = [];
this.frame = 0;
this.iterationCount = 0;
for (let i = 0; i < gridCount * gridCount; i++) {
const dice = Math.floor(Math.random() * 10);
this.cells.push(dice > 7);
}
}
private applyRules() {
if (this.iterationCount >= resetIterations) {
this.reset();
return;
}
const neighborScore = (idx: number): number => {
const x = idx % gridCount;
const y = Math.floor(idx / gridCount);
let score = 0;
const neighborIdxes: number[] = [
/* NW */ x - 1 + (y - 1) * gridCount,
/* N */ x + (y - 1) * gridCount,
/* NE */ x + 1 + (y - 1) * gridCount,
/* W */ x - 1 + y * gridCount,
/* E */ x + 1 + y * gridCount,
/* SW */ x - 1 + (y + 1) * gridCount,
/* S */ x + (y + 1) * gridCount,
/* SE */ x + 1 + (y + 1) * gridCount
];
for (const i of neighborIdxes) {
if (i < 0 || i > this.cells.length) {
continue;
}
score += this.cells[i] ? 1 : 0;
}
return score;
};
for (let i = 0; i < this.cells.length; i++) {
const score = neighborScore(i);
const alive = this.cells[i];
if (alive) {
if (score < 2 || score > 3) {
this.cells[i] = false;
}
} else {
if (score === 3) {
this.cells[i] = true;
}
}
}
this.iterationCount++;
}
}