# Select Neighboring X or Y Tiles

I have a randomly generated set of tiles, and I am trying to select neighboring x or y tiles to perform functions on them based on if they are a certain value of tile, like so:

var IsometricMap = new Object();

IsometricMap.tiles = [
// "images/dirt.png",
"images/dirtHigh.png",      // 0
"images/grass.png",         // 1
"images/water.png",         // 2
"images/waterBeachCornerEast.png",  // 3
"images/waterBeachCornerNorth.png", // 4
"images/waterBeachCornerSouth.png", // 5
"images/waterBeachCornerWest.png",  // 6
"images/waterBeachEast.png",    // 7
"images/waterBeachNorth.png",   // 8
"images/waterBeachSouth.png",   // 9
"images/waterBeachWest.png"]

var blockcount = 10;

let generate_row = _=> Array(blockcount).fill().map(_=>Math.floor(Math.random()*3));
IsometricMap.map = Array(blockcount).fill().map(generate_row);

console.log(IsometricMap.map);

for(let x = 0; x < IsometricMap.map.length; x++){

for(let y = 0; y < IsometricMap.map.length; y++){

if ((IsometricMap.map[x-1][y]) == 2) {
//IF THE TILE IS WATER, DO ALL THIS:

alert("SUCCESSFULLY SELECTED THE " + IsometricMap.map[x-1][y] + " TILE");

//DONE WITH WATER TILES
}

}

}


So far this is not yielding any results, its as if it cant find the tile I am trying to specify. Is there something wrong with my scope here?

Could it be that the program is throwing an exception for an out of range index? On the first pass of the loop, x-1 evaluates to -1.

Also I think Math.Random() returns values less than 1.0, so if you multiply by 3 you may only get values 0..2 out.

• Which is fine, because 0..2 is exactly 3 possible values. Which is also a very handy since arrays are zero-based and 0..2 are indices of items in an array of length 3. – badunius Nov 14 '19 at 7:14

Yea, this can be very annoying at times, but you have to check that the [x - 1] position exists. So your if statement becomes:

    if (!!IsometricMap.map[x - 1] && IsometricMap.map[x - 1][y] == 2) {
}

• Btw, don't test this, there are a hundred positions you are creating. This means that you can possibly have 100 alerts! Super annoying to test XD – Kitanga Nday Jun 17 '19 at 3:59
• This is the first time I see someone use a double exclamation mark instead of no exclamation marks at all. Is it considered good practice? Is it some kind of coding standard? I'm curious. – Peethor Jun 17 '19 at 9:16
• Well in truth, it will work without it. I just run into a bug once where I had to use double exclamation marks to make sure that an item already exists. JS can be weird at times. – Kitanga Nday Jun 17 '19 at 13:10