我将俄罗斯方块表示为:
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);
}
但是,当我在俄罗斯方块上运行rotate1(L)时,它不会旋转整个图块,也就是说,其中的一部分会丢失。请帮忙!
答案 0 :(得分:0)
我认为您的索引不匹配。另外,您可以在旋转之前一次性创建新数组。
可逆时针旋转的功能:
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]
));
}