Rotation check

This commit is contained in:
foglar 2024-11-13 17:01:28 +01:00
parent e6ec2633e1
commit 120c3a90e1
2 changed files with 34 additions and 18 deletions

View File

@ -66,8 +66,7 @@ namespace Tetris
}
}
public class Speed
()
public class Speed()
{
private static int speed = 400;
@ -87,6 +86,7 @@ namespace Tetris
private int x, y;
private Matrix matrix;
public Shape(Matrix matrix)
{
Random random = new Random();
@ -96,7 +96,6 @@ namespace Tetris
current_shape = shape[randomRotation];
this.matrix = matrix;
matrix.IncreaseScore(10);
// TODO: Implement random color
this.x = 0; // Starting position
this.y = 8; // Center of the grid
}
@ -145,19 +144,39 @@ namespace Tetris
public void Rotate()
{
Clear();
randomRotation = (randomRotation + 1) % shape.Count;
// !IMPORTANT: Check if rotation is possible
current_shape = shape[randomRotation];
Draw();
int nextRotation = (randomRotation + 1) % shape.Count;
int[,] nextShape = shape[nextRotation];
if (CanRotate(nextShape))
{
Clear();
current_shape = nextShape;
randomRotation = nextRotation;
Draw();
}
}
private bool CanRotate(int[,] newShape)
{
for (int i = 0; i < newShape.GetLength(0); i++)
{
int newX = x + newShape[i, 0];
int newY = y + newShape[i, 1];
if (newX >= Matrix.HEIGHT || newX < 0 || newY < 0 || newY >= Matrix.WIDTH ||
(matrix.GetBlock(newX, newY) != ' ' && !IsPartOfShape(newX, newY)))
{
return false;
}
}
return true;
}
private bool IsPartOfShape(int matrixX, int matrixY)
{
for (int i = 0; i < current_shape.GetLength(0); i++)
{
if (x + current_shape[i, 0] == matrixX &&
y + current_shape[i, 1] == matrixY)
if (x + current_shape[i, 0] == matrixX && y + current_shape[i, 1] == matrixY)
{
return true;
}
@ -173,12 +192,8 @@ namespace Tetris
int newBlockY = newY + current_shape[i, 1];
if (newBlockX >= Matrix.HEIGHT || newBlockX < 0 || newBlockY < 0 ||
newBlockY >= Matrix.WIDTH)
{
return false;
}
if (matrix.GetBlock(newBlockX, newBlockY) != ' ' &&
!IsPartOfShape(newBlockX, newBlockY))
newBlockY >= Matrix.WIDTH ||
(matrix.GetBlock(newBlockX, newBlockY) != ' ' && !IsPartOfShape(newBlockX, newBlockY)))
{
return false;
}
@ -195,6 +210,7 @@ namespace Tetris
}
}
public class Matrix
{
public const int HEIGHT = 22;

View File

@ -7,7 +7,7 @@
```bash
git clone https://github.com/foglar/Tetris.git
cd Tetris
dotnet run ./
dotnet run
```
> [!NOTE]
@ -17,4 +17,4 @@ dotnet run ./
## Simple tetris game
- [SRS](./TetrominoSRS.md)
- [FS](./TetrominoFS.md) - Not ready yet
- [FS](./TetrominoFS.md)