Search code examples
javascripttetris

How do I rotate a tetris block in p5.js?


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!


Solution

  • 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]
        ));
    }