I'm implementing a simple tetris game, where you have multiple shapes:
- S shape
- a line
- a square
- etc
In a typical game, when you press UP on the keyboard, the falling shape will rotate clockwise.
I defined a shape in my JavaScript implementation as an array of point coordinates. For example, the S shape is:
[
{x:0, y:2},
{x:0, y:1},
{x:1, y:1},
{x:1, y:0}
]
This will translate to the following shape:
Pressing up, should convert the array above into the following array:
[
{x:0, y:0},
{x:1, y:0},
{x:1, y:1},
{x:2, y:1}
]
To achieve this I... shamelessly hardcoded the coordinates into a shapeRotationMap
object:
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},
];
});
I have a shape string ("line"
) and a rotation (0
, 1
, 2
or 3
) and that's how I know which object to take.
However, this complicates the code, makes it hard to add a new shape and just by posting it here I feel like I'm insulting a few programmers.
But I cannot find the algorithm to rotate such an object.
I found this algorithm: How to rotate a matrix in an array in javascript . But here OP has a bi-dimensional array (a matrix), and in my case I have an object of coordinates.
Does anyone know how can I rotate my object by 90°?
If not I guess I'll switch my logic and use a matrix instead.