-
Notifications
You must be signed in to change notification settings - Fork 0
/
pattern.js
80 lines (67 loc) · 2.52 KB
/
pattern.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
const wrapper = document.querySelector('.wrapper')
const goButton = document.querySelector('.go')
const rangeSlider = document.getElementById('tiles-width')
const widthValue = document.getElementById('width')
let columns = Math.floor(document.body.clientWidth / 50)
let rows = Math.floor(document.body.clientHeight / 50)
const createTile = () => {
const tile = document.createElement('div')
tile.classList.add('tile')
return tile
}
const createTiles = quantity => {
for (let i = 0; i < quantity; i++) {
wrapper.appendChild(createTile())
}
}
const createGrid = (widthPerTile) => {
widthValue.textContent = `${widthPerTile} px`
wrapper.innerHTML = ""
columns = Math.floor(document.body.clientWidth / widthPerTile)
rows = Math.floor(document.body.clientHeight / widthPerTile)
wrapper.style.setProperty('--columns', columns)
wrapper.style.setProperty('--rows', rows)
createTiles(columns * rows)
createInitialPattern(columns)
}
const createInitialPattern = (columns) => {
for(let i = 0; i < columns; i++) {
const rand = Math.floor(Math.random() * 2)
const tile = wrapper.childNodes.item(i)
if (rand === 1) {
tile.classList.add('blue')
}
}
}
const go = (rows, columns) => {
for (let i = columns; i < rows * columns; i++) {
const thisTile = wrapper.childNodes.item(i)
const upLeftTile = wrapper.childNodes.item(i - columns - 1)
const upTile = wrapper.childNodes.item(i - columns)
const upRightTile = wrapper.childNodes.item(i - columns + 1)
let blueTilesCount = 0
if (i % columns === 0) {
if (upTile.classList.contains('blue') || upRightTile.classList.contains('blue')) {
thisTile.classList.add('blue')
}
}
else {
if (i % (columns - 1) === 0 && (upTile.classList.contains('blue') || upLeftTile.classList.contains('blue'))) {
thisTile.classList.add('blue')
} else {
[upLeftTile, upTile, upRightTile].map((tile) => {
if (tile.classList.contains('blue')) {
blueTilesCount++;
}
})
if (blueTilesCount === 1 || blueTilesCount === 2) {
thisTile.classList.add('blue')
}
}
}
}
}
createGrid(50)
window.onresize = () => createGrid(rangeSlider.value)
goButton.onclick = () => go(rows, columns)
rangeSlider.oninput = () => createGrid(rangeSlider.value)