如何在 p5.js 中旋转俄罗斯方块?

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

我将俄罗斯方块表示为:

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

这是L形的一块,false代表空。旋转后,它应该看起来像

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

我有一个这样写的旋转函数:

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

然而,当我 运行 在俄罗斯方块块上旋转 1(L) 时,它不会旋转整个块,即其中一些丢失了。请帮忙!

我认为您的索引不匹配。此外,您可以在旋转之前一次性创建新数组。

功能逆时针旋转:

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;
}

顺时针匹配:

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;
}

更简洁:

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

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