Tetris-Tiles are stored as a 4x4 boolean matrix. Each rotation step has it's own matrix, the representation of the T-Block would look like this:
[
0, 0, 0, 0,
0, 1, 1, 1,
0, 0, 1, 0,
0, 0, 0, 0
],
[
0, 0, 1, 0,
0, 0, 1, 1,
0, 0, 1, 0,
0, 0, 0, 0
],
[
0, 0, 1, 0,
0, 1, 1, 1,
0, 0, 0, 0,
0, 0, 0, 0
],
[
0, 0, 1, 0,
0, 1, 1, 0,
0, 0, 1, 0,
0, 0, 0, 0
]
I'm trying to find a way to calculate the position of the block when it's being rotated and collides with the board (the board is also a matrix). The original Tetris would simply not allow rotation of a block when the rotation would result in a collision. Modern variants of the game will resolve the collision and move the block to a valid position.
Here are some situations that should be solved. The board is 6x6, red = active block, grey = placed/occupied blocks. Each time, a counter-clockwise rotation should be performed. The green overlay indicates the matrix for the block. The arrow indicates the resulting correction to resolve the rotation:
- Block is at the left side of the board. Since the block cannot leave the board, it should be moved back inside after a rotation.
- Block hits "ground", but isn't placed/committed yet. In this case, the tile must be moved up to resolve the collision (in case of a "I"-Block, the movement would be 2 cells up).
- Tile would hit occupied blocks, must be moved left to resolve collision.
- Tile cannot be rotated.
What would be the best approach to tackle this problem? Optimally, the solution should be generic, eg. work with arbitrary 4x4 matrix blocks on an arbitrarily sized and populated board.