-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid.js
More file actions
79 lines (60 loc) · 1.53 KB
/
grid.js
File metadata and controls
79 lines (60 loc) · 1.53 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
class Grid {
#grid
constructor( width, height) {
this.#grid = new Array( height)
.fill(0)
.map( _ => new Array( width).fill(0))
}
get width() {
return this.#grid[0].length
}
get height() {
return this.#grid.length
}
setCell( x, y, value) {
this.#grid[y][x] = value
}
getCell( x, y) {
return this.#grid[y][x]
}
toString() {
return this.#grid
.map( row => row.join(' '))
.join( "\n")
}
inBoundsX( x) {
return x >= 0 && x < this.width
}
inBoundsY( y) {
return y >= 0 && y < this.height
}
pathExecute( startPosition, direction, func) {
let x = startPosition.x
let y = startPosition.y
if( !this.inBoundsX( x) || !this.inBoundsY( y)) throw "X or Y out of bounds"
while( this.inBoundsX( x) && this.inBoundsY( y)) {
func( x, y, this.getCell( x, y))
x += direction.x
y += direction.y
}
}
clone() {
let grid = new Grid( this.height, this.width)
for(let x=0; x<this.width; x++) {
for(let y=0; y<this.height; y++) {
grid.setCell( x, y, this.getCell( x, y))
}
}
return grid
}
fillFromRows( rows) {
for(let y=0; y<rows.length; y++) {
for(let x=0; x<rows[y].length; x++) {
this.setCell( x,y, rows[y][x])
}
}
}
}
module.exports = {
Grid
}