【发布时间】:2022-06-15 01:18:09
【问题描述】:
您好,我正在尝试在 js 中进行路径查找。我有一个寻路算法,但它在 javascript 中并且它永远存在。你能告诉我这里有什么问题吗?
虽然循环应该在给定点停止。但它会永远持续下去。
1,6 是要搜索的点。 从 10,7 开始
你能帮我解决这个问题吗?我认为这是因为重新加载 javascirpt 代码的问题。
var example = document.getElementById('my_Canvas');
var context = example.getContext('2d');
var w = 570,
h = 570;
var rect = 35;
var startx = 10,
starty = 7;
var points = [
[3, 7],
[6, 2]
];
var xy = [];
var accessible = [];
var found = false;
for (var i = 0; i < h / rect; i++) {
let width = [];
for (var j = 0; j < w / rect; j++) {
width[j] = 1;
}
xy[i] = width;
}
var que = [];
que.push([startx - 1, starty]);
que.push([startx, starty - 1]);
que.push([startx + 1, starty]);
var loops = 0;
function asd() {
if (found == false) {
while (true) {
var queEl = que.shift();
if (queEl[0] == 1 && queEl[1] == 6) {
found = true;
break;
}
if (xy[queEl[1]][queEl[0]] == null) {
continue;
}
accessible.push([queEl[0], queEl[1]]);
points.push([queEl[0], queEl[1]]);
if (queEl[0] - 1 > 0) {
que.push([queEl[0] - 1, queEl[1]]);
}
if (queEl[1] - 1 > 0) {
que.push([queEl[0], queEl[1] - 1]);
}
if (queEl[0] + 1 < xy[0].length) {
que.push([queEl[0] + 1, queEl[1]]);
}
if (queEl[1] + 1 < xy.length) {
que.push([queEl[0], queEl[1] + 1]);
}
if (que.length == 0) {
found = true;
}
}
}
}
for (var i = 0; i < h / rect; i++) {
for (var j = 0; j < w / rect; j++) {
context.fillStyle = "rgb(255,0,0)";
context.fillRect(j * 30, i * 30, 50, 50);
context.fillStyle = "rgb(0,0,0)";
context.fillRect(j * 30 + 5, i * 30 + 5, 40, 40);
for (var x = 0; x < points.length; x++) {
if (j == points[x][0] && i == points[x][1]) {
context.fillStyle = "rgb(255,0,0)";
context.fillRect(j * 30, i * 30, 50, 50);
context.fillStyle = "rgb(150,0,0)";
context.fillRect(j * 30 + 5, i * 30 + 5, 40, 40);
}
}
}
}
asd();
<!doctype html>
<html>
<body>
<canvas width="570" height="570" id="my_Canvas"></canvas>
</body>
</html>
【问题讨论】:
标签: javascript html