【发布时间】:2018-05-30 07:55:14
【问题描述】:
我正在实现一个简单的俄罗斯方块游戏,你有多个形状:
- S形
- 一行
- 一个正方形
- 等
在典型的游戏中,当你按下键盘上的UP时,落下的形状会顺时针旋转。
我在 JavaScript 实现中将形状定义为点坐标数组。例如S形为:
[
{x:0, y:2},
{x:0, y:1},
{x:1, y:1},
{x:1, y:0}
]
按起来,应该把上面的数组转换成下面的数组:
[
{x:0, y:0},
{x:1, y:0},
{x:1, y:1},
{x:2, y:1}
]
为了实现这一点,我... 无耻地将坐标硬编码为 shapeRotationMap 对象:
let shapeRotationMap = {
"line0": [
{x:0, y:0},
{x:0, y:1},
{x:0, y:2},
{x:0, y:3},
],
"line1": [
{x:0, y:0},
{x:1, y:0},
{x:2, y:0},
{x:3, y:0},
],
"leftS0": [
{x:0, y:0},
{x:1, y:0},
{x:1, y:1},
{x:2, y:1},
],
"leftS1": [
{x:0, y:1},
{x:0, y:2},
{x:1, y:0},
{x:1, y:1},
],
"rightS0": [
{x:0, y:1},
{x:1, y:1},
{x:1, y:0},
{x:2, y:0},
],
"rightS1": [
{x:0, y:0},
{x:0, y:1},
{x:1, y:1},
{x:1, y:2},
],
"podium0": [
{x:0, y:1},
{x:1, y:0},
{x:1, y:1},
{x:1, y:2},
],
"podium1": [
{x:0, y:0},
{x:1, y:0},
{x:1, y:1},
{x:2, y:0},
],
"podium2": [
{x:0, y:0},
{x:0, y:1},
{x:0, y:2},
{x:1, y:1},
],
"podium3": [
{x:0, y:1},
{x:1, y:0},
{x:1, y:1},
{x:2, y:1},
]
}
shapeRotationMap["line2"] = shapeRotationMap["line0"];
shapeRotationMap["line3"] = shapeRotationMap["line1"];
shapeRotationMap["leftS2"] = shapeRotationMap["leftS0"];
shapeRotationMap["leftS3"] = shapeRotationMap["leftS1"];
shapeRotationMap["rightS2"] = shapeRotationMap["rightS0"];
shapeRotationMap["rightS3"] = shapeRotationMap["rightS1"];
["square0", "square1", "square2","square3"].forEach(function(key){
shapeRotationMap[key] = [
{x:0, y:0},
{x:0, y:1},
{x:1, y:0},
{x:1, y:1},
];
});
我有一个形状字符串 ("line") 和一个旋转 (0、1、2 或 3),这就是我知道要拍摄哪个对象的方式。
但是,这会使代码复杂化,很难添加新的形状,只是在这里发布它,我觉得我在侮辱一些程序员。
但我找不到旋转此类对象的算法。
我找到了这个算法:How to rotate a matrix in an array in javascript。但是这里 OP 有一个二维数组(矩阵),在我的例子中,我有一个坐标对象。
有谁知道如何将我的对象旋转 90°?
如果不是,我想我会切换逻辑并改用矩阵。
【问题讨论】:
-
这几乎肯定是答案。正如我们所说的那样实施它。我懒得将一个点建模为
Point,但如果我要进行复杂的操作,我别无选择。我可能还需要实现Shape。谢谢@NinaScholz
标签: javascript arrays algorithm rotation points