0

I have a matrix as arena and a small matrix as player. With keys user can move around. move(pos) takes argument and inside checks

if(pos=="down")
    if (!collide(pos)) player.pos.y++;

And collide works like

if(pos=="down")
    for (i = 0; i < player.matrix.length; i++)
    {
        for (j = 0; j < player.matrix[i].length; j++)
        {
            if ((player.matrix[i][j] && arena[player.pos.y + i + 1][player.pos.x + j]) != 0) result = true;
        }
    }

This woks perfect till you come edge to the arena. When you come to edge, because there is no lenght+1 index, if detection gives you Cannot read property of "" undefined. I tried first checking if typeof index out of bound == undefined however even this gave me the same error. Then I tried try catch but the next function inside the catch stuck between first one and itself. Any ideas to find an easy solution for checking out of bonds?

2
  • Your first condition of the if statement could check whether the item with the index in question even exists. for example: if(item[index] && ... ). What will happen is any non-existent item will immediately be false on this first condition. Commented Oct 22, 2017 at 21:10
  • @snapjs How can I get undefined rather than Cannot read property 'number' of undefined? I need to force it return something rather than throwing error Commented Oct 22, 2017 at 21:13

1 Answer 1

2

My suggestion is just to protect arena[player.pos.y + i + 1][player.pos.x + j] call by length comparisons:

for (i = 0; i < player.matrix.length; i++)
{
  for (j = 0; j < player.matrix[i].length; j++)
  { // here we have an additional protection of arena dimensions
    if(player.pos.y + i + 1 < arena.length && player.pos.x + j < arena[player.pos.y + i + 1].length)
    {
      if ((player.matrix[i][j] && arena[player.pos.y + i + 1][player.pos.x + j]) != 0)
        result = true;
    }
  }
}

Also you may implement an additional method on arena object:

arena.isValid = function(a, b) {
  // check for dimensions
  if(a >= arena.length || b >= arena[a].length) {
    return false;
  }
  // check if the value is undefined/null/0/false/""
  if(!arena[a][b]) {
    return false;
  }
  return true;
};

And so

for (i = 0; i < player.matrix.length; i++)
  for (j = 0; j < player.matrix[i].length; j++)
    if(player.matrix[i][j] && arena.isValid(player.pos.y + i + 1, player.pos.x + j))
      result = true;
Sign up to request clarification or add additional context in comments.

1 Comment

@hello_guys I updated the answer to provide more functionality on the arena protection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.