Падение фигурки вниз - C#

Узнай цену своей работы

Формулировка задачи:

Добрый день! Подскажите, пожалуйста, у меня имеется тетрис, написанный мною, нужно в приведенном ниже фрагменте изменить что-то так, чтобы фигурка тетриса падала вниз сразу (при нажатии кнопки Backspace), так как при зажатии на клавишу стрелочки вниз, она падает быстро, но хотелось бы, чтобы это происходило мигом. Спасибо большое!
public void CurrTetraminoMovDown() // реализация сдвига фигуры вниз
        {
            Point Position = currTetramino.getCurrPosition();
            Point[] Shape = currTetramino.getCurrShape();
            bool move = true;
            currTetraminoErase();
            foreach (Point S in Shape)
            {
                if (((int)(S.Y + Position.Y) + 2 + 1) >= Rows)
                {
                    move = false;
                }
                else if (BlockControls[((int)(S.X + Position.X) + ((Cols / 2) - 1)),
                    (int)(S.Y + Position.Y) + 2 + 1].Background != NoBrush)
                {
                    move = false;
                }
            }
            if (move)
            {
                currTetramino.movDown();
                currTetraminoDraw();
            }
            else
            {
                currTetraminoDraw();
                CheckRows();
                currTetramino = new Tetramino();
            }
        }

Решение задачи: «Падение фигурки вниз»

textual
Листинг программы
namespace Tetris
{
    
    public class Board
    {
        private int Rows;
        private int Cols;
        private int Score;
        private int LinesFilled;
        private Tetramino currTetramino;
        private Label[,] BlockControls;
        static private Brush NoBrush = Brushes.Transparent;
        static private Brush SilverBrush = Brushes.Snow;
        public Board(Grid TetrisGrid)
        {
            Rows = TetrisGrid.RowDefinitions.Count;
            Cols = TetrisGrid.ColumnDefinitions.Count;
            Score = 0;
            LinesFilled = 0;
            BlockControls = new Label[Cols, Rows];
            for (int i = 0; i < Cols; i++)
            {
                for (int j = 0; j < Rows; j++)
                {
                    BlockControls[i, j] = new Label();
                    BlockControls[i, j].Background = NoBrush;
                    BlockControls[i, j].BorderBrush = SilverBrush;
                    BlockControls[i, j].BorderThickness = new Thickness(1, 1, 1, 1);
                    Grid.SetRow(BlockControls[i, j], j);
                    Grid.SetColumn(BlockControls[i, j], i);
                    TetrisGrid.Children.Add(BlockControls[i, j]);
                }
            }
            currTetramino = new Tetramino();
            currTetraminoDraw();
        }
        public int getScore()
        {
            return Score;
        }
        public int getLines()
        {
            return LinesFilled;
        }
 
        private void currTetraminoDraw()
        {
            Point Position = currTetramino.getCurrPosition();
            Point[] Shape = currTetramino.getCurrShape();
            Brush Color = currTetramino.getCurrColor();
            foreach (Point S in Shape)
            {
                BlockControls[(int)(S.X + Position.X) + ((Cols / 2) - 1),
                    (int)(S.Y + Position.Y) + 2].Background = Color;
            }
        }
 
        private void currTetraminoErase()
        {
            Point Position = currTetramino.getCurrPosition();
            Point[] Shape = currTetramino.getCurrShape();
            foreach (Point S in Shape)
            {
                BlockControls[(int)(S.X + Position.X) + ((Cols / 2) - 1),
                    (int)(S.Y + Position.Y) + 2].Background = NoBrush;
            }
        }
 
        private void CheckRows() // проверка ячеек на полноту
        {
            bool full;
            for (int i = Rows - 1; i > 0; i--)
            {
                full = true;
                for (int j = 0; j < Cols; j++)
                {
                    if (BlockControls[j, i].Background == NoBrush)
                    {
                        full = false;
                    }
                    if (BlockControls[j, 1].Background != NoBrush) // конец игры
                    {
                        MessageBox.Show(LinesFilled.ToString("Вы проиграли! \n\nОчки: " + Score.ToString() + "\nЛиний: " + LinesFilled.ToString() + "\n\n Нажмите ОК, чтобы начать по-новой" ));
                        MainWindow.bGameOver = true;
                        MainWindow.GamePause();
                        return;
                    }
                }
                if (full) // убирается строчка из фигур, если она полная
                {
                    RemoveRow(i);
                    Score += 100; // добавляется сто очков, если строчка из фигур - полная
                    LinesFilled += 1; // очищенных строк из фигур
                    i++;
                }
            }
        }
 
        private void RemoveRow(int row)
        {
            for (int i = row; i > 2; i--)
            {
                for (int j = 0; j < Cols; j++)
                {
                    BlockControls[j, i].Background = BlockControls[j, i - 1].Background;
                }
            }
        }
 
        public void CurrTetraminoMovLeft() // реализация сдвига фигуры влево
        {
            Point Position = currTetramino.getCurrPosition();
            Point[] Shape = currTetramino.getCurrShape();
            bool move = true;
            currTetraminoErase();
            foreach (Point S in Shape)
            {
                if (((int)(S.X + Position.X) + ((Cols / 2) - 1) - 1) < 0)
                {
                    move = false;
                }
                else if (BlockControls[((int)(S.X + Position.X) + ((Cols / 2) - 1) - 1),
                    (int)(S.Y + Position.Y) + 2].Background != NoBrush)
                {
                    move = false;
                }
            }
            if (move)
            {
                currTetramino.movLeft();
                currTetraminoDraw();
            }
            else
            {
                currTetraminoDraw();
            }
        }
 
        public void CurrTetraminoMovRight() // реализация сдвига фигуры вправо
        {
            Point Position = currTetramino.getCurrPosition();
            Point[] Shape = currTetramino.getCurrShape();
            bool move = true;
            currTetraminoErase();
            foreach (Point S in Shape)
            {
                if (((int)(S.X + Position.X) + ((Cols / 2) - 1) + 1) >= Cols)
                {
                    move = false;
                }
                else if (BlockControls[((int)(S.X + Position.X) + ((Cols / 2) - 1) + 1),
                    (int)(S.Y + Position.Y) + 2].Background != NoBrush)
                {
                    move = false;
                }
            }
            if (move)
            {
                currTetramino.movRight();
                currTetraminoDraw();
            }
            else
            {
                currTetraminoDraw();
            }
        }
 
        public void CurrTetraminoMovDown() // реализация сдвига фигуры вниз
        {
            Point Position = currTetramino.getCurrPosition();
            Point[] Shape = currTetramino.getCurrShape();
            bool move = true;
            currTetraminoErase();
            foreach (Point S in Shape)
            {
                if (((int)(S.Y + Position.Y) + 2 + 1) >= Rows)
                {
                    move = false;
                }
                else if (BlockControls[((int)(S.X + Position.X) + ((Cols / 2) - 1)),
                    (int)(S.Y + Position.Y) + 2 + 1].Background != NoBrush)
                {
                    move = false;
                }
            }
            if (move)
            {
                currTetramino.movDown();
                currTetraminoDraw();
            }
            else
            {
                currTetraminoDraw();
                CheckRows();
                currTetramino = new Tetramino();
            }
        }
 
        public void CurrTetraminoMovRotate() // реализация вращения фигуры
        {
            Point Position = currTetramino.getCurrPosition();
            Point[] S = new Point[4];
            Point[] Shape = currTetramino.getCurrShape();
            bool move = true;
            Shape.CopyTo(S, 0);
            currTetraminoErase();
            for (int i = 0; i < S.Length; i++)
            {
                double x = S[i].X;
                S[i].X = S[i].Y * -1;
                S[i].Y = x;
                if (((int)((S[i].Y + Position.Y) + 2)) >= Rows)
                {
                    move = false;
                }
                else if (((int)(S[i].X + Position.X) + ((Cols / 2) - 1)) < 0)
                {
                    move = false;
                }
                else if (((int)(S[i].X + Position.X) + ((Cols / 2) - 1)) >= Cols)
                {
                    move = false;
                }
                else if (BlockControls[((int)(S[i].X + Position.X) + ((Cols / 2) - 1)),
                    (int)(S[i].Y + Position.Y) + 2].Background != NoBrush)
                {
                    move = false;
                }
            }
            if (move)
            {
                currTetramino.movRotate();
                currTetraminoDraw();
            }
            else
            {
                currTetraminoDraw();
            }
        }
    }
 
    public class Tetramino
    {
        private Point currPosition;
        private Point[] currShape;
        private Brush currColor;
        private bool rotate;
        public Tetramino()
        {
            currPosition = new Point(0, 0);
            currColor = Brushes.Transparent;
            currShape = setRandomShape();
        }
        public Brush getCurrColor() // получение цвета фигуры
        {
            return currColor;
        }
        public Point getCurrPosition() // позиция фигуры
        {
            return currPosition;
        }
        public Point[] getCurrShape() // получение фигуры
        {
            return currShape;
        }
        public void movLeft()
        {
            currPosition.X -= 1; // сдвиг фигуры влево на одну ячейку
        }
        public void movRight()
        {
            currPosition.X += 1; // сдвиг фигуры вправо на одну ячейку
        }
        public void movDown()
        {
            currPosition.Y += 1; // сдвиг фигуры вниз на одну ячейку
        }
        public void movRotate() // вращение фигуры
        {
            if (rotate)
            {
                for (int i = 0; i < currShape.Length; i++)
                {
                    double x = currShape[i].X;
                    currShape[i].X = currShape[i].Y * -1;
                    currShape[i].Y = x;
                }
            }
        }
 
        private Point[] setRandomShape()
        {
            Random rand = new Random(); // появление случайных фигурок, описанных ниже (case)
            switch (rand.Next() % 7)
            {
                case 0:
                    rotate = true;
                    currColor = Brushes.Pink;
                    return new Point[] {
                        new Point(0,0), // здесь и дальше Point(Х,Х), где Х - позиция, - это позиции "элементиков" тетриса
                        new Point(-1,0),
                        new Point(1,0),
                        new Point(2,0)
                    };
                case 1: // голубая фигура
                    rotate = true;
                    currColor = Brushes.Blue;
                    return new Point[] {
                        new Point(-1,-1),
                        new Point(-1,0),
                        new Point(0,0),
                        new Point(1,0)
                    };
                case 2: // оранжевая фигура
                    rotate = true;
                    currColor = Brushes.Orange;
                    return new Point[] {
                        new Point(0,0),
                        new Point(-1,0),
                        new Point(1,0),
                        new Point(1,-1)
                    };
                case 3: // коричневая фигура, квадрат
                    rotate = false;
                    currColor = Brushes.Peru;
                    return new Point[] {
                        new Point(0,0),
                        new Point(0,1),
                        new Point(1,0),
                        new Point(1,1)
                    };
                case 4: // зеленая фигура
                    rotate = true;
                    currColor = Brushes.Lime;
                    return new Point[] {
                        new Point(0,0),
                        new Point(-1,0),
                        new Point(0,-1),
                        new Point(1,0)
                    };
                case 5: // фиолетовая фигура
                    rotate = true;
                    currColor = Brushes.MediumPurple;
                    return new Point[] {
                        new Point(0,0),
                        new Point(-1,0),
                        new Point(0,-1),
                        new Point(1,-1)
                    };
                case 6: // красная фигура
                    rotate = true;
                    currColor = Brushes.Red;
                    return new Point[] {
                        new Point(0,0),
                        new Point(-1,0),
                        new Point(0,1),
                        new Point(1,1)
                    };
                case 7: // темно-красная фигура
                    rotate = true;
                    currColor = Brushes.DarkRed;
                    return new Point[] {
                        new Point(0,0),
                        new Point(-1,0),
                        new Point(0,1),
                        new Point(1,1)
                    };
                default:
                    return null;
            }
        }
    }
 
 
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static bool bGameOver = false;
        static DispatcherTimer Timer;
        Board myBoard;
        public MainWindow()
        {
            InitializeComponent();
        }
        void MainWindow_Initialized(object sender, EventArgs e)
        {
            Timer = new DispatcherTimer();
            Timer.Tick += new EventHandler(GameTick);
            Timer.Interval = new TimeSpan(0, 0, 0, 0, 400);
            GameStart();
        }
        private void GameStart() // старт игры
        {
            MainGrid.Children.Clear(); // очистка игрового поля
            myBoard = new Board(MainGrid);
            bGameOver = false;
            Timer.Start();
        }
        void GameTick(object sender, EventArgs e)
        {
            Score.Content = myBoard.getScore().ToString("0000000000"); // очки 
            Lines.Content = myBoard.getLines().ToString("0000000000"); // количество очищенных строк
            myBoard.CurrTetraminoMovDown();
        }
        public static void GamePause() // пауза игры
        {
                if (Timer.IsEnabled) Timer.Stop();
                else Timer.Start();
 
        }
        private void GameOver()
        {
            GamePause();
        }
        private void HandleKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Left: // клавиша "стрелка влево" 
                    if (Timer.IsEnabled) myBoard.CurrTetraminoMovLeft();
                    break;
                case Key.Right: // клавиша "стрелка вправо"
                    if (Timer.IsEnabled) myBoard.CurrTetraminoMovRight();
                    break;
                case Key.Back: // клавиша "стрелка вниз"
                    if (Timer.IsEnabled) myBoard.CurrTetraminoMovDown();
                    break;
                case Key.Down: // клавиша вращения
                    if (Timer.IsEnabled) myBoard.CurrTetraminoMovRotate();
                    break;
            }
        }
 
        private void CloseApp(object sender, RoutedEventArgs e) // закрыть приложение
        {
            this.Close();
        }
 
        private void Pause(object sender, RoutedEventArgs e) // пауза
        {
            GamePause();
        }
 
        private void StartAgain(object sender, RoutedEventArgs e) // начать заново
        {
            GameStart();
        }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

9   голосов , оценка 4.111 из 5
Похожие ответы