Frage

I have a maze drawing function that isn't working as I'd like. Currently, it works by taking a mid point, then finding positions above, below, left and right of it - and putting them in an array. It then checks if any of these are outside the maze grid, and removes them from the array. Then it checks if any have already been visited (this will be a maze function, but right now it just draws a long dotted wiggly line) and removes those from the array.

Then, if there are no options left it quits, or returns, otherwise it will draw a coloured square and run the function again.

You can see it here, currently I have the grid very small to amplify the 2 issues I'm getting:

  1. it very often thinks that negative coordinates are OK. Which leads me to think something is very wrong with the lines:

    if(options[i][0]<0 || options[i][1]<0 || options[i][0]>size-1 || options[i][1]>size-1){
      // ... let us know that you're removing them...
      console.log("splicing: out of bounds "+options[i][0]+","+options[i][1]);
      // ... then remove them
      options.splice(i, 1);
    
  2. it also very often doesn't notice that a square has already been visited, and will write over them, which makes me think that this line isn't working as expected:

    if(options.length > 0){
    

If you fire up the console there is lots of output that explains some of what is happening, if it seems to work OK, just hit refresh a few times and it will go wrong - especially if it ends up in the top right corner early on.

My current code is here: http://djave.co.uk/hosted/maze/js/script.js but if it helps there is also a zip file of everything at http://djave.co.uk/hosted/maze/maze.zip

If you want me to clarify anything just comment.

NB its supposed to skip a square at the moment, so it won't be a continuous line.

War es hilfreich?

Lösung

The problem is you are splicing the same array that you are iterating over. So in the second iteration of the loop when x=4, y=0 you have the following:

i=1, options[[2,0],[6,0],[4,-2],[4,2]]

After you splice the second option the array will change and you will have the following for the third iteration:

i=2, options[[2,0],[4,-2],[4,2]]

Notice that [4,-2] gets skipped. The easiest fix for this would be to use $.grep

options = $.grep(options, function(option, index) { 
    return option[0]>=0 && option[0]<size && option[1]>=0 && option[1]<size;
});

This will iterate over the array and return an array of objects where grep returns true. You should also do the same general thing for when you iterate over the already visited squares.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top