-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
99 lines (77 loc) · 2.16 KB
/
index.html
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
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
}
</style>
<canvas></canvas>
<script>
const colors = {
alive: 'salmon',
dead: 'papayawhip',
}
const viewport = {
height: window.innerHeight,
width: window.innerWidth,
}
const canvas = document.querySelector('canvas')
canvas.setAttribute('height', viewport.height);
canvas.setAttribute('width', viewport.width);
const context = canvas.getContext('2d')
const cellSize = 10;
let state = (() => {
const totalRows = viewport.height / cellSize
const perRow = viewport.width / cellSize
const state = []
for (let r = 0; r < totalRows; r++) {
const row = []
for (let i = 0; i < perRow; i++) {
row.push({ alive: (Math.floor(Math.random() * 5) === 1) })
}
state.push(row)
}
return state
})()
const render = () => {
state.forEach((row, rowIndex) => {
row.forEach((cell, cellIndex) => {
context.fillStyle = cell.alive ? colors.alive : colors.dead
context.fillRect(cellIndex * cellSize, rowIndex * cellSize, cellSize, cellSize)
})
})
}
render()
const isAlive = (cell, aliveNeighbors) => {
if (cell.alive) {
return (aliveNeighbors.length === 2 || aliveNeighbors.length === 3)
}
return (aliveNeighbors.length === 3)
}
const nextGeneration = () => {
const newState = []
state.forEach((row, rowIndex) => {
const newRow = []
row.forEach((cell, cellIndex) => {
const lastRow = state[rowIndex - 1] || state[state.length - 1]
const nextRow = state[rowIndex + 1] || state[0]
const aliveNeighbors = [
lastRow[cellIndex - 1] || lastRow[lastRow.length - 1],
lastRow[cellIndex],
lastRow[cellIndex + 1] || lastRow[0],
row[cellIndex - 1] || row[row.length - 1],
row[cellIndex + 1] || row[0],
nextRow[cellIndex - 1] || nextRow[nextRow.length - 1],
nextRow[cellIndex],
nextRow[cellIndex + 1] || nextRow[0],
].filter(cell => cell.alive)
newRow.push({ alive: isAlive(cell, aliveNeighbors) })
})
newState.push(newRow)
})
return newState
}
setInterval(() => {
state = nextGeneration()
render()
}, (1000 / 24))
</script>