Zelkins
Zelkins

Reputation: 759

Recursion Ending Too Soon in Javascript Function

I am currently learning JavaScript through remaking games from scratch, and my current project is Minesweeper. While trying to create the recursive function that reveals the spaces surrounding a clicked space I have run into the issue of it ending too soon for seemingly no reason.

You can read the whole code (so far) here: pastebin.com

or refer to just the stand-alone function below:

function showAdjacent(block) {

  if(block.minesNextTo != 0)
    return;

  console.log(block.row+','+block.col);
  block.uncovered = true;
  block.hidden = false;

  console.log(block.adjacentBlocks.length);

  for(i = 0; i < block.adjacentBlocks.length; i++)
      block.adjacentBlocks[i].hidden = false;

  for(i = 0; i < block.adjacentBlocks.length; i++) {
    if(!block.adjacentBlocks[i].uncovered)
        showAdjacent(block.adjacentBlocks[i]);
  }

}

(and yes I know that this function shouldn't only be triggered if a block has zero mines next to it, this is just easier for testing purposes)

Upvotes: 4

Views: 170

Answers (1)

Pointy
Pointy

Reputation: 413737

You need to declare i as a local variable:

var i;

at the top of the function would do it. As it is, it's implicitly global, so the recursive calls mess up the value of i in the parent contexts.

Upvotes: 2

Related Questions