I'm trying to create a matrix of random integers with a range between 1 and 5. Everything is working great, except it occasionally generates 0 with some consistency.
What I mean is, every time I run the code the first row and last column is always effected. However the only other rows that are effected (which doesn't happen every time the code is ran) is if they're 'connected' like a region.
I'm really not sure how to explain this bug. Also, if I use JSON.stringify() in console.log() it actually contains a value other than 0. I know this isn't true as I've also got an algorithm that counts connected cells and it'll count the region as 0's.
[4,3,4,1,1,1,3,4,0,0]
[4,3,3,3,4,2,1,2,3,0]
[4,3,2,5,1,5,2,2,1,0]
[1,2,1,1,5,5,5,1,4,2]
[1,5,2,2,5,3,2,2,2,1]
[2,5,2,5,3,3,1,1,1,2]
[5,2,4,4,5,5,3,2,5,2]
[3,5,1,1,2,4,3,4,5,1]
[3,4,3,3,3,4,2,4,3,5]
[4,2,5,4,5,2,5,4,2,4]
or
[4,3,4,1,1,1,3,4,1,0]
[4,3,3,3,4,2,1,2,3,4]
[4,3,2,5,1,5,2,2,1,2]
[1,2,1,1,5,5,5,1,4,2]
[1,5,2,2,5,3,2,2,2,1]
[2,5,2,5,3,3,1,1,1,2]
[5,2,4,4,5,5,3,2,5,2]
[3,5,1,1,2,4,3,4,5,1]
[3,4,3,3,3,4,2,4,3,5]
[4,2,5,4,5,2,5,4,2,4]
My code that generates the matrices:
// Create a camera object and define its properties
const camera = {
width: 10,
height: 10,
get totalCells() {
return this.width * this.height;
}
};
function generateMap(mapArray, searchArray) {
// Generate the tilemap for the game
let tempArray = [];
for (let i = 0; i < (camera.totalCells); i++) {
// Generate a random number and push it to an array
// When the array has same count of values as camera.width
// push it to the mapArray and empty the tempArray,
// do this repeatedly until theres a 10x10 mapArray
let randomInt = Math.floor(Math.random() * 5) + 1;
if (camera.totalCells - camera.width === i && mapArray[0][camera.width - 1] === randomInt) {
// Player 1 is already this colour, generate a new random colour
// Repeat this loop again so this if statement is ran to make sure
// player 2 colour is unique
i--;
continue;
}
tempArray.push(randomInt);
if (tempArray.length === camera.width) {
mapArray.push(tempArray);
searchArray.push(tempArray);
tempArray = [];
}
}
}
let mapArray = [];
let searchArray = [];
generateMap(mapArray, searchArray);
Aucun commentaire:
Enregistrer un commentaire