0

I'm representing tetris pieces as:

var jPiece = [
    [ true, false, false ],
    [ true, true,  true]
    ];

This is the L shaped piece, where false represents emptiness. Once it's rotated, it should look like

var jPiece = [
    [false, true],
    [false, true],
    [true, true],
]

I have a rotate function written like this:

function rotate1(L) {
    var result = [];
    var a;
    for (var col = 1; col < (L[0].length) +1; col++) {
        //print("yeet");
        var result1 = [];
        for (var row = 0; row < L.length; row++) {
            a = L[row][L.length - col];
            result1.push(a);
            print(a);

        }
        result.push(result1);
    }
    return result;
}

function rotateFallingPiece() {
    fallingPiece = rotate1(fallingPiece);

    fallingPieceCols = fallingPiece[0].length;
    if (fallingPieceIsLegal == false) {
        for (var i = 0; i < 3; i ++) {
            fallingPiece = rotate1(fallingPiece);
            fallingPieceCols = fallingPiece[0].length;
        }
    }
    print(fallingPiece);
}

however, when I run the rotate1(L) on a tetris piece, it doesn't rotate the entire piece, i.e, some of it is lost. please help!

Sami Hult
  • 3,052
  • 1
  • 12
  • 17
  • Looking at your JS, I don't see anything that rotates an object... ie no new CSS or class being applied. You're using p5.js, and here's it's [doc on rotate()](https://p5js.org/reference/#/p5/rotate), but I don't see that line in your code. Is there more code you should be sharing? – Kalnode Jan 29 '19 at 04:34
  • @MarsAndBack The block is logically rotated in `rotate1`. Rendering must happen somewhere else. Since p5 has nothing to do with the question, I removed the tag. – Sami Hult Jan 29 '19 at 04:51

1 Answers1

0

I think your indices don't match. Also, you could create the new array in a one go before rotating.

A functioning rotate counter-clockwise:

function rotate1(L) {
  let result = Array.from(L[0], x => Array.from(L, y => false));
  for (let col = 0; col < L[0].length; col++) {
    for (let row = 0; row < L.length; row++) {
      result[col][row] = L[row][L[0].length - col - 1];
    }
  }
  return result;
}

And a matching clockwise:

function rotate1(L) {
  let result = Array.from(L[0], x => Array.from(L, y => false));
  for (let col = 0; col < L[0].length; col++) {
    for (let row = 0; row < L.length; row++) {
      result[col][row] = L[L.length - row - 1][col];
    }
  }
  return result;
}

Even more concise:

function rotate1(L) {
  return Array.from(L[0], (x, col) => 
    Array.from(L, (y, row) =>
      L[row][L[0].length - col - 1]
    ));
}

and

function rotate1(L) {
  return Array.from(L[0], (x, col) => 
    Array.from(L, (y, row) =>
      L[L.length - row - 1][col]
    ));
}
Sami Hult
  • 3,052
  • 1
  • 12
  • 17