-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (68 loc) · 2.18 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
class Game {
constructor(width= 1024, height = 256) {
this.width = width
this.height = height
this.canvas = document.getElementById("canvas")
this.ctx = canvas.getContext("2d")
this.generateTable()
this.advance = this.advance.bind(this)
this.timer = setInterval(this.advance, 16)
}
generateTable() {
const table = []
for (let i = 0; i < this.height; i++){
const row = []
for (let j = 0; j < this.width; j++){
const isAlive = Math.random() > 0.5
row.push(isAlive ? 1 : 0)
}
table.push(row)
}
this.table = table
}
isAlive(y, x) {
if(y < 0 || y > this.height - 1 || x < 0 || x > this.width - 1) return 0
return this.table[y][x]
}
drawTable() {
for (let i = 0; i < this.height; i++) {
for (let j = 0; j < this.width; j++) {
const isAlive = this.isAlive(i, j)
if (isAlive) {
this.ctx.clearRect(2 * j, 2 * i, 2, 2)
} else {
this.ctx.fillRect(2 * j, 2 * i, 2, 2)
}
}
}
}
cloneTable() {
const newTable = []
for (let i = 0; i < this.height; i++) newTable.push(this.table[i].slice(0))
return newTable
}
advance() {
const newTable = this.cloneTable()
for (let i = 0; i < this.height; i++) {
for (let j = 0; j < this.width; j++) {
const isAlive = this.isAlive(i, j)
let neighbours = 0
if (this.isAlive(i - 1, j - 1)) neighbours++
if (this.isAlive(i + 1, j - 1)) neighbours++
if (this.isAlive(i - 1, j + 1)) neighbours++
if (this.isAlive(i + 1, j + 1)) neighbours++
if (this.isAlive(i, j - 1)) neighbours++
if (this.isAlive(i, j + 1)) neighbours++
if (this.isAlive(i - 1, j)) neighbours++
if (this.isAlive(i + 1, j)) neighbours++
if (this.isAlive(i, j) && neighbours < 2) newTable[i][j] = 0
else if (this.isAlive(i, j) && neighbours >= 2 && neighbours <= 3) newTable[i][j] = 1
else if (this.isAlive(i, j) && neighbours > 3) newTable[i][j] = 0
else if (!this.isAlive(i, j) && neighbours === 3) newTable[i][j] = 1
}
}
this.table = newTable
this.drawTable()
}
}
const g = new Game()