-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid.js
More file actions
113 lines (102 loc) · 2.52 KB
/
grid.js
File metadata and controls
113 lines (102 loc) · 2.52 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
101
102
103
104
105
106
107
108
109
110
111
112
113
const Grid_size=4;
const Cell_size=20;
const Cell_gap=2;
export default class Grid{
#cells
constructor(gridelement){
gridelement.style.setProperty('--cell-size',`${Cell_size}vmin`)
gridelement.style.setProperty('--grid-size',`${Grid_size}`)
gridelement.style.setProperty('--gap',`${Cell_gap}vmin`)
this.#cells=createCellElements(gridelement).map((cellelement,index)=>{
return new Cell(cellelement,index%Grid_size,Math.floor(index/Grid_size))
})
}
get cellsbyColumn(){
/* return this.#cells.reduce((cellsgrid,cell)=>{
cellsgrid[cell.x] =cellsgrid[cell.x] ||[]
cellsgrid[cell.y][cell.x] =cell
return cellsgrid
},[])*/
return this.#cells.reduce((cellgrid,cell)=>{
cellgrid[cell.x][cell.y]=cell
return cellgrid
},[[],[],[],[]])
}
get cellsbyRow(){
/* return this.#cells.reduce((cellsgrid,cell)=>{
cellsgrid[cell.y] =cellsgrid[cell.y] ||[]
cellsgrid[cell.y][cell.x] =cell
return cellsgrid
},[])*/
return this.#cells.reduce((cellgrid,cell)=>{
cellgrid[cell.y][cell.x]=cell
return cellgrid
},[[],[],[],[]])
}
get cells(){
return this.#cells
}
get #emptyCells(){
return this.#cells.filter(cell => cell.tile == null)
}
randomEmptyCell(){
const randomIndex=Math.floor(Math.random()* this.#emptyCells.length)
return this.#emptyCells[randomIndex]
}
}
class Cell{
#cellElement
#x
#y
#tile
#mergetile
constructor(cellElement,x,y){
this.#x=x
this.#y=y
this.#cellElement=cellElement
}
get x(){
return this.#x
}
get y(){
return this.#y
}
get tile(){
return this.#tile
}
set tile(value){
this.#tile =value
if (this.#tile==null) return
this.#tile.x=this.#x
this.#tile.y=this.#y
}
get mergetile(){
return this.#mergetile
}
set mergetile(value){
this.#mergetile=value
if(value ==null ) return
this.#mergetile.x=this.#x
this.#mergetile.y=this.#y
}
canaccept(tiles){
if (this.tile === null || this.tile == undefined) return true
return (this.mergetile==null && this.#tile.value==tiles.value)
}
mergeTiles(){
if(this.tile==null ||this.mergetile == null) return
this.tile.value =this.tile.value *2
this.mergetile.remove()
this.mergetile=null
}
}
function createCellElements(gridelement){
let arr=[]
for(let i=0;i<Grid_size * Grid_size;i++){
const elem=document.createElement('div')
elem.classList.add('cell')
gridelement.appendChild(elem)
arr.push(elem)
}
return arr
}