i'm having a difficulties with javascript, im trying to create a function to generate a map in a game, As you can see below. The basic pattern is [9, 3, 4, 4, 4, 4, 4, 4, 5, 9] as the tile image frame.
I want to change some of the 4 tile into 12 tile, But as the result, all 4 tile change to 12,
Here is the Code :
function addMap(stage)
{
var map = new Map(32, 32);
map.image = game.assets['img/terrain.png'];
var mapArray = [9, 3, 4, 4, 4, 4, 4, 4, 5, 9]; // per 50m
var selectedMap = [];
for (var i = 0; i < (2 + (stage - 1)) * 10; i++) {
selectedMap.push(mapArray);
}
for(var row = 0; row < selectedMap.length; row++) {
for(var col = 0; col < selectedMap[row].length; col++) {
if (selectedMap[row][col] === 4) {
var probability = rand(100);
if (probability < 15) {
selectedMap[row][col] = 12;
}
}
}
}
map.loadData(selectedMap);
return map;
}
NOTE : ASSUME STAGE IS = 1
Can you see what is wrong with this array system ? Thank you very much
You have pushed a reference to the exact same set of columns into every row. Thus, when you change the one copy of the array, all the other references see the change too. You need to make a copy of the mapArray
before pushing it into your selectedMap
array.
for (var i = 0; i < (2 + (stage - 1)) * 10; i++) {
selectedMap.push(mapArray.slice(0));
}
.slice(0)
will make a copy so each row will have a separate, independent copy of the array and you can modify each copy separately.
Objects in Javascript (an array is an object) are assigned by reference (not by copy) in Javascript. So, when you do selectedMap.push(mapArray);
you're just putting a pointer to mapArray
into selectedMap
and all the elements of selectedMap
pointed to the same copy of mapArray
. So, if you changed one, they all changed.