From 120c3a90e1f531c8704e9f55755caf894309ae5c Mon Sep 17 00:00:00 2001 From: foglar Date: Wed, 13 Nov 2024 17:01:28 +0100 Subject: [PATCH] Rotation check --- Program.cs | 48 ++++++++++++++++++++++++++++++++---------------- README.md | 4 ++-- 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/Program.cs b/Program.cs index a6b6271..9bd646f 100755 --- a/Program.cs +++ b/Program.cs @@ -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; diff --git a/README.md b/README.md index a6e490c..ea93bde 100755 --- a/README.md +++ b/README.md @@ -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)