Search code examples
javascriptarraystetris

Function changing global variable


I have this array that I pass into a function that's suppose to rotate the array 90 deg and return the result. I then want to check whether the new array is colliding with other things on the canvas.

let newArray = [
[0,0,1],
[1,1,1],   
[0,0,0]
];

let test = rotate(newArray);

if ( collision(test) ){
  draw(newArray);
} else {
  draw(test);
}

Here's the problem. I think rotate() is changing the newArray-variable so it doesn't matter what the if-statement evaluate to, the draw() function will always do the same thing.

I want to select the array to draw after checking if the rotated matrix collides with other stuff.

function rotate(matrix) {

matrix = matrix.reverse();

for (var i = 0; i < matrix.length; i++) {
 for (var j = 0; j < i; j++) {
  var temp = matrix[i][j];
  matrix[i][j] = matrix[j][i];
  matrix[j][i] = temp;
 }
}
return matrix
}


function collision(mat){

let collision = false;

for ( let i = 0; i < mat.length; i++){
for ( let j = 0; j < mat.length; j++){
  if (mat[i][j] == 1){
    let test = ctx.getImageData(x + 10*j +10, y + 10*i, 1, 1);
      if (test.data != "255,255,255,255" && test.data != "0,0,0,0"){
        collision = true;
      }
  }
 }
 }
return collision;
}

Solution

  • So you are correct - the Array.reverse() method used in the rotate function does not return a new array, it modifies the same one (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse);

    I'd suggest changing the rotate function to first clone the array that's passed to it and only then perform Array.reverse() etc..

    You can clone this simple array passed into the rotate function in your example using let newMatrix = JSON.parse(JSON.stringify(matrix)); Then perform the remaining actions on the newMatrix and return that instead.

    If you don't like this approach you could also create a new empty array and using a double for loop (a loop within a loop as you're working with 2D grids) populate the new array with values from the original one.