【发布时间】:2014-06-13 00:34:29
【问题描述】:
您好,我正在尝试编写一款塔防游戏。 我目前正在尝试构建小怪将遵循的路径。
但我的道路总是蜷缩起来。
路径的工作方式是使用二维数组,即网格。由包含 isPath 属性的单元格对象组成的 40 行和 40 列。
我创建路径的方式是选择一个随机方向,然后检查我们尝试访问的单元格是否还不是路径的一部分,并且它不会与多个单元格(即它来自的单元格)。我还看看我是否在我们不想向左走的第一个列,因为下一个单元格最终会出现在最后一个列的上排。到最后也一样。
这是我迄今为止为路径算法写的内容:
function createPath(){
var indexesOfCellsInLastCol = new Array();
for(var o = NumberOfRow; o < (NumberOfRow * NumberOfRow); o+= NumberOfRow)
indexesOfCellsInLastCol.push(o);
var indexesOfCellsInFirstCol = new Array();
for(var k = 1; k < (NumberOfRow * NumberOfRow); k+= NumberOfRow)
indexesOfCellsInFirstCol.push(k);
var usedDirection = [];
var x = 0;
var y = 0;
// random walk without crossing
for(var i = 0; i < 50000; i++){
var direction = Math.floor((Math.random()*4));
//always start the same way
if(i < 10){
if(i == 9){
grid[2][i].isPath = true;
grid[1][i].isPath = true;
x = i;
y = 2;
}
grid[0][i].isPath = true;
}
else
{
switch(direction){
//left
case 0:
if(!contains(usedDirection, 0)){
if(collideDirection(y,x - 1) == 1){
//check if you are not in first col, because if you go left while you're in first col you go back to last row.
if(!contains(indexesOfCellsInFirstCol, x) && !grid[y][x - 1].isPath){
grid[y][x - 1].isPath = true;
x--;
usedDirection = [];
}
else
usedDirection.push(0);
}
}
break;
//up
case 1:
if(!contains(usedDirection, 1)){
if(collideDirection(y - 1,x) == 1){
if(y - 1 > 1 && !grid[y - 1][x].isPath){
grid[y - 1][x].isPath = true;
y--;
usedDirection = [];
}
else
usedDirection.push(1);
}
}
break;
//right
case 2:
if(!contains(usedDirection, 2)){
if(collideDirection(y,x + 1) == 1){
//same as going left whil you're on the first col
if(!contains(indexesOfCellsInLastCol, x) && !grid[y][x + 1].isPath){
grid[y][x + 1].isPath = true;
x++;
usedDirection = [];
}
//don't be no fool and try to repeat your self
else
usedDirection.push(2);
}
}
break
//down
case 3:
if(!contains(usedDirection, 3)){
if(collideDirection(y + 1,x) == 1 ){
if((y + 1 < (NumberOfRow - 1)) && !grid[y + 1][x].isPath){
grid[y + 1][x].isPath = true;
y++;
usedDirection = [];
}
else
usedDirection.push(3);
}
}
break;
}
}
}
}
我已将所有其余代码放入 js fiddle http://jsfiddle.net/xZ7tH/
我不一定想要代码anwser,也许只是提示我应该去哪里或应该做什么。
我考虑过看看这条路如果左转超过 3 次,那么它必须向右转。但我认为它会在一条太多的线性路径中上升。
有什么想法吗??
感谢您的回答!
【问题讨论】:
-
你能补充更多关于职位系统的信息吗?路径是由网格上的单元格组成的吗?平面上的任意向量?
标签: javascript algorithm path grid