-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgrid.js
103 lines (92 loc) · 2.73 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
95
96
97
98
99
100
101
102
103
// function Viafunc(){
// let div = document.getElementById('ViaInfo');
// div.style.display = "inline";
// return false;
// }
// function Viafunc_collapse() {
// let div = document.getElementById('tutorial');
// div.style.display = "none";
// return false;
// }
function drawRect(x, y, width, height, state, colour = null) {
if(colour){
ctx.fillStyle = colour;
} else {
if (state == STATE.START)
ctx.fillStyle = "#1fd613";
else if (state == STATE.XSTART)
ctx.fillStyle = "greenyellow";
else if (state == STATE.FINISH)
ctx.fillStyle = 'red';
else if (state == STATE.XFINISH)
ctx.fillStyle = "#d83c60";
else if (state == STATE.TERRAIN)
ctx.fillStyle = "#8B0000";
else if (state == STATE.WALL)
ctx.fillStyle = "#696969";
else if (state == STATE.VIA)
ctx.fillStyle = "#146c91";
else if (state == STATE.PATH)
ctx.fillStyle = "#ebeb2a";
else if (state == STATE.VISITED)
ctx.fillStyle = "#58c4b7";
else if (state == STATE.VISITED_TERRAIN)
ctx.fillStyle = "#8A2BE2";
else if (state == STATE.TERRAIN_PATH)
ctx.fillStyle = "#FF8C00";
else
ctx.fillStyle = "#ffcc99";
}
ctx.beginPath();
ctx.rect(x, y, width, height);
ctx.closePath();
ctx.fill();
}
//Creates a 2d grid of nodes and stores them in the global nodes[] array
function createGrid() {
for(let row = 0; row < num_rows; row++) {
nodes[row] = [];
for(let col = 0; col < num_cols; col++) {
nodes[row][col] = {
x: col *(rectWidth + 1),
y: row * (rectHeight + 1),
state: STATE.EMPTY,
prevState: STATE.EMPTY, // used for when the start/end nodes are being moved
weight: 0
};
}
}
nodes[startNode.row][startNode.col].state = STATE.START;
nodes[finishNode.row][finishNode.col].state = STATE.FINISH;
}
//renders grid by drawing the rectangles
function drawGrid(){
clear();
for(row = 0; row < num_rows; row++){
for(col = 0; col < num_cols; col++){
cell = nodes[row][col];
drawRect(cell.x, cell.y, rectWidth, rectHeight, cell.state);
}
}
}
/* Helper Functions */
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
}
function sleep(ms){
return new Promise(r => setTimeout(r, ms));
}
function getX(e){
return e.clientX - canvas.getBoundingClientRect().left;
}
function getY(e){
return e.clientY - canvas.getBoundingClientRect().top;
}
function getCol(x){
// 2nd term's numerator changes based on the constant value that separates cells in createGrid()
return parseInt((x - (x / rectHeight)) / rectHeight);
}
function getRow(y){
// 2nd term's numerator changes based on the constant value that separates cells in createGrid()
return parseInt((y - (y / rectWidth)) / rectWidth);
}