Как бы я вернуть массив измененных объектов без возврата исходных объектов? - PullRequest
0 голосов
/ 24 сентября 2019

Я делаю генератор случайных лабиринтов, и у меня все работает, кроме оператора return.В конце концов, мой первоначальный план для этого состоит в том, чтобы иметь возможность протестировать некоторые алгоритмы решения лабиринта, так что показывать это приятно, что и происходит, но наличие доступа к лабиринту в качестве кода является необходимостью.Сама функция изменяет объекты в массиве и работает, но при возврате все объекты находятся в исходном состоянии.

//This is the code with the irrelevant stuff removed
function generate() {
  var maze = []
  for(let y = 0; y < tiles[1]; y++) {
    let tempArr = [];
    for(let x = 0; x < tiles[0]; x++) {
      //l,u,r,and d are all whether or not you can pass through that side of the tile, v is whether or not the tile has been visited by the actual generation
      tempArr.push([{l:true,u:true,r:true,d:true,v:false}]);
    }
    maze.push(tempArr);
    //After this point, the array that is returned does not change
  }

  //Builds the walls on the edge of the square
  for(let y = 0; y < maze.length; y++) {
    for(let x = 0; x < maze[y].length; x++) {
      if(y == 0) {
        maze[y][x].u = false;
      }
      if(x == 0) {
        maze[y][x].l = false;
      }
      if(y == tiles[1]-1) {
        maze[y][x].r = false;
      }
      if(x == tiles[0]-1) {
        maze[y][x].d = false
      }
    }
  }

  let _x = 0;
  let _y = 0;

  for(let i = 0; i < tiles[0]*tiles[1]; i++) {
    //None of these changes are visible in the returned array
    maze[_y][_x].v = true;
    let running = true;
    while(running) {
      maze[_y][_x].v = true;
      let random = Math.floor(Math.random()*4)+1;
      if(random == 1) {//This is repeated for 2, 3, and 4
        if(maze[_y][_x-1] && !maze[_y][_x-1].v) {
          maze[_y][_x].l = true;
          maze[_y][_x-1].r = true;
          _x -= 1;
          continue;
        } else if(maze[_y][_x+1] && !maze[_y][_x+1].v) {
          maze[_y][_x].r = true;
          maze[_y][_x+1].l = true;
          _x += 1;
          continue;
        } else {
          random++
        }
      }
    }
  }

  return maze; //This returns the original array, regardless of any changes made
}

Это не вызывает у меня никаких ошибок, но в случае 3 x3 лабиринта Я ожидаю результата:

[[{u:false,l:false,d:false,r:true,v:true}],[{u:false,l:true,d:false,r:true,v:true}],[{u:false,l:true,d:true,r:false,v:true}]],
[[{u:false,l:false,d:true,r:true,v:true}],[{u:false,l:true,d:false,r:true,v:true}],[{u:true,l:true,d:false,r:false,v:true}]],
[[{u:true,l:false,d:false,r:true,v:true}],[{u:false,l:true,d:false,r:true,v:true}],[{u:false,l:true,d:false,r:false,v:true}]]

, но получу массив, состоящий только из:

{d:true,l:true,r:true,u:true,v:false} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...