-
Notifications
You must be signed in to change notification settings - Fork 0
/
Grid.js
94 lines (79 loc) · 2.01 KB
/
Grid.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
const GRID_SIZE = 3
const CELL_SIZE = 20
const CELL_GAP = 0
export default class Grid {
#cells
constructor(gridElement) {
gridElement.style.setProperty("--grid-size", GRID_SIZE)
gridElement.style.setProperty("--cell-size", `${CELL_SIZE}vmin`)
gridElement.style.setProperty("--cell-gap", `${CELL_GAP}vmin`)
gridElement.style.setProperty("--cell-size-mark", `${CELL_SIZE * 0.8}vmin`)
gridElement.style.setProperty("--cell-size-o-inner", `${CELL_SIZE * 0.8 * 0.7}vmin`)
this.#cells = createCellElements(gridElement).map((cellElement, index) => {
return new Cell(
cellElement,
index % GRID_SIZE,
Math.floor(index / GRID_SIZE)
)
})
}
get cells() {
return this.#cells
}
get cellsByRow() {
return this.#cells.reduce((cellGrid, cell) => {
cellGrid[cell.y] = cellGrid[cell.y] || []
cellGrid[cell.y][cell.x] = cell
return cellGrid
}, [])
}
get cellsByColumn() {
return this.#cells.reduce((cellGrid, cell) => {
cellGrid[cell.x] = cellGrid[cell.x] || []
cellGrid[cell.x][cell.y] = cell
return cellGrid
}, [])
}
get #emptyCells() {
return this.#cells.filter(cell => cell.tile == null)
}
randomEmptyCell() {
const randomIndex = Math.floor(Math.random() * this.#emptyCells.length)
return this.#emptyCells[randomIndex]
}
getCellByElement(cellElement) {
return this.#cells.find((cell) => {
if(cell.cellElement == cellElement)
return true;
})
}
}
class Cell {
#cellElement
#x
#y
constructor(cellElement, x, y) {
this.#cellElement = cellElement
this.#x = x
this.#y = y
}
get x() {
return this.#x
}
get y() {
return this.#y
}
get cellElement() {
return this.#cellElement
}
}
function createCellElements(gridElement) {
const cells = []
for (let i = 0; i < GRID_SIZE * GRID_SIZE; i++) {
const cell = document.createElement("div")
cell.classList.add("cell")
cells.push(cell)
gridElement.append(cell)
}
return cells
}