Exemplo n.º 1
0
 public static bool CanBeRotated(Figure figure, int[,] field, int currX, int currY)
 {
     var CheckingFigure = GenerateFigure.getFigure(Indexes.currIndex);
     for (int i = 0; i < CheckingFigure.size; i++)
     {
         for (int j = 0; j < CheckingFigure.size; j++)
         {
             CheckingFigure.matrix[i, j] = figure.matrix[i, j];
         }
     }
     CheckingFigure.rotate();
     if (Validator.IsInRange(CheckingFigure, field, Indexes.currX, Indexes.currY))
     {
         for (int i = 0; i < CheckingFigure.size; i++)
         {
             for (int j = 0; j < CheckingFigure.size; j++)
             {
                 if (CheckingFigure.matrix[i, j] != 0 && field[i + Indexes.currX, j + Indexes.currY] != 0)
                 {
                     return false;
                 }
             }
         }
         return true;
     }
     else
     {
         return false;
     }
 }
Exemplo n.º 2
0
 /// <summary>
 /// Constructor for a figure.
 /// </summary>
 /// <param name="figure">The figure to clone.</param>
 public Figure(Figure figure)
 {
     IsSleeping = figure.IsSleeping;
     Color = figure.Color;
     Blocks = new List<Block>();
     foreach (var block in figure.Blocks) { Blocks.Add(new Block(block)); }
     CenterBlock = figure.CenterBlock == null ? null : Blocks[figure.Blocks.IndexOf(figure.CenterBlock)];
     Action = figure.Action;
     ElapsedMovementTime = figure.ElapsedMovementTime;
     ActionBuffer = figure.ActionBuffer;
 }
Exemplo n.º 3
0
        public static void printField(Figure myFigure, int[,] field, int currX, int currY)
        {
            Console.BackgroundColor = ConsoleColor.White;
            for (int k = 0; k < CONSTANTS.FIELD_WIDTH + 2; k++)
            {

                Console.Write("  ");
            }
            Console.BackgroundColor = ConsoleColor.Black;
            Console.WriteLine();
            for (int i = 0; i < CONSTANTS.FIELD_HEIGHT; i++)
            {
                for (int j = 0; j < CONSTANTS.FIELD_WIDTH; j++)
                {
                    if (j == 0)
                    {
                        Console.BackgroundColor = ConsoleColor.White;
                        Console.Write("  ");
                    }
                    if (i < currX + myFigure.size && i >= currX && j < currY + myFigure.size && j >= currY)
                    {
                        if (myFigure.matrix[i - currX, j - currY] == 0 || field[i, j] == 0)
                        {
                            Colors.ChangeColor(myFigure.matrix[i - currX, j - currY] | field[i, j]);
                            Console.Write("  ");
                        }
                        else
                        {
                            Colors.ChangeColor(field[i, j]);
                            Console.Write("  ");
                        }
                    }
                    else
                    {
                        Colors.ChangeColor(field[i, j]);
                        Console.Write("  ");
                    }
                    if (j == CONSTANTS.FIELD_WIDTH - 1)
                    {
                        Console.BackgroundColor = ConsoleColor.White;
                        Console.Write("  ");
                    }
                }
                Console.BackgroundColor = ConsoleColor.Black;
                Console.WriteLine();
            }
            for (int k = 0; k < CONSTANTS.FIELD_WIDTH + 2; k++)
            {
                Console.BackgroundColor = ConsoleColor.White;
                Console.Write("  ");
            }
            Console.BackgroundColor = ConsoleColor.Black;
            Console.WriteLine();
        }
Exemplo n.º 4
0
 public static int getLastRowOfFigure(Figure figure)
 {
     for (int i = figure.size - 1; i >= 0; i--)
     {
         for (int j = 0; j < figure.size; j++)
         {
             if (figure.matrix[i, j] != 0)
             {
                 return i;
             }
         }
     }
     return -1;
 }
Exemplo n.º 5
0
 public static int getFirstRowOfFigure(Figure figure)
 {
     for (int i = 0; i < figure.size; i++)
     {
         for (int j = 0; j < figure.size; j++)
         {
             if (figure.matrix[i, j] != 0)
             {
                 return i;
             }
         }
     }
     return -1;
 }
Exemplo n.º 6
0
 public static void Print(Figure myFigure, int[,] field, int currX, int currY)
 {
     while (true)
     {
         if (!ImportantGameVariables.amIPrinting)
         {
             ImportantGameVariables.amIPrinting = true;
             Console.Clear();
             Console.WriteLine("Score:{0}", ScoreCounter.GetScore());
             printField(myFigure, field, currX, currY);
             ImportantGameVariables.amIPrinting = false;
             break;
         }
     }
 }
Exemplo n.º 7
0
 public static void MakeAMove(Figure figure, int[,] field, int currX, int currY)
 {
     if (ImportantGameVariables.gameOver)
     {
         return;
     }
     else
     {
         var key = Console.ReadKey(true);
         switch (key.Key)
         {
             case ConsoleKey.RightArrow:
                 if (Moves.canBeMoved("right", figure, field, currX, currY))
                 {
                     Indexes.currY++;
                 }
                 break;
             case ConsoleKey.LeftArrow:
                 if (Moves.canBeMoved("left", figure, field, currX, currY))
                 {
                     currY--;
                     Indexes.currY--;
                 }
                 break;
             case ConsoleKey.UpArrow:
                 if (CanBeRotated(figure, field, currX, currY))
                 {
                     figure.rotate();
                 }
                 break;
             case ConsoleKey.DownArrow:
                 if (Moves.canBeMoved("down", figure, field, currX, currY))
                 {
                     currX++;
                     Indexes.currX++;
                 }
                 break;
             case ConsoleKey.Spacebar:
                 while (Moves.canBeMoved("down", figure, field, currX, currY))
                 {
                     currX++;
                     Indexes.currX++;
                 }
                 break;
         }
         Printer.Print(figure, field, currX, currY);
     }
 }
Exemplo n.º 8
0
 public bool IsHit(Direction direction, Figure figure)
 {
     bool result = false;
     foreach (Point point in figure.pList)
     {
         foreach(Point p in pList)
         {
             Point p1 = GetNextPoint(p, direction);
             if(p1.x == point.x && p1.y == point.y && result != true)
             {
                 result = true;
             }
         }
     }
     return result;
 }
Exemplo n.º 9
0
        public static bool IsInRange(Figure figure, int[,] field, int currX, int currY)
        {
            if (currX >= CONSTANTS.FIELD_HEIGHT - GetFigureInfo.getLastRowOfFigure(figure))
            {
                return false;
            }
            if (currY < -GetFigureInfo.getFirsColonOfFigure(figure))
            {
                return false;
            }
            if (currY + GetFigureInfo.getLastColonOfFigure(figure) + 1 > CONSTANTS.FIELD_WIDTH)
            {
                return false;
            }

            return true;
        }
Exemplo n.º 10
0
        /// <summary>
        /// Create an arrow figure.
        /// </summary>
        /// <returns>The arrow figure.</returns>
        public static Figure Arrow()
        {
            //Create the figure.
            Figure figure = new Figure();

            //Set some attributes.
            figure.Color = Color.Purple;

            //Add and create the blocks.
            figure.AddBlock(new Block() { Position = new Vector2(0, 0) });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, 0) });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH * 2, 0) });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, HEIGHT) });

            figure.CenterBlock = figure.Blocks[1];

            //Return the figure.
            return figure;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Create a left hook figure.
        /// </summary>
        /// <returns>The left hook figure.</returns>
        public static Figure HookLeft()
        {
            //Create the figure.
            Figure figure = new Figure();

            //Set some attributes.
            figure.Color = Color.Yellow;

            //Add and create the blocks.
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, 0) });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, HEIGHT) });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, HEIGHT * 2) });
            figure.AddBlock(new Block() { Position = new Vector2(0, HEIGHT * 2) });

            figure.CenterBlock = figure.Blocks[2];

            //Return the figure.
            return figure;
        }
Exemplo n.º 12
0
 public static bool canBeMoved(string where, Figure figure, int[,] field, int currX, int currY)
 {
     if (Validator.IsInRange(figure, field, currX, currY))
     {
         for (int i = 0; i < figure.size; i++)
         {
             for (int j = 0; j < figure.size; j++)
             {
                 if (figure.matrix[i, j] != 0)
                 {
                     switch (where)
                     {
                         case "right":
                             if ((j + currY + 1 >= CONSTANTS.FIELD_WIDTH) || (field[i + currX, j + currY + 1] != 0))
                             {
                                 return false;
                             }
                             break;
                         case "left":
                             if ((j + currY - 1 < 0) || (field[i + currX, j + currY - 1] != 0))
                             {
                                 return false;
                             }
                             break;
                         case "down":
                             if ((i + currX + 1 >= CONSTANTS.FIELD_HEIGHT) || (field[i + currX + 1, j + currY] != 0))
                             {
                                 return false;
                             }
                             break;
                     }
                 }
             }
         }
         return true;
     }
     else
     {
         return false;
     }
 }
Exemplo n.º 13
0
        public static void saveField(Figure figure, int[,] field, int currX, int currY)
        {
            for (int i = 0; i < CONSTANTS.FIELD_HEIGHT; i++)
            {
                for (int j = 0; j < CONSTANTS.FIELD_WIDTH; j++)
                {

                    if (i < Indexes.currX + figure.size && i >= Indexes.currX && j < Indexes.currY + figure.size && j >= Indexes.currY)
                    {
                        if (figure.matrix[i - Indexes.currX, j - Indexes.currY] == 0 || field[i, j] == 0)
                        {
                            field[i, j] = figure.matrix[i - Indexes.currX, j - Indexes.currY] | field[i, j];
                        }
                        else
                        {
                            ImportantGameVariables.gameOver = true;
                        }
                    }

                }
            }
        }
        /// <summary>
        /// Prints the next figure on the console
        /// </summary>
        /// <param name="nextFigure">The next figure object</param>
        public void PrintNextFigure(Figure nextFigure)
        {
            int left = this.Width + 5;
            int top = 3;

            for (int i = 0; i < 6; i++)
            {
                Console.SetCursorPosition(left, top);
                for (int j = 0; j < 6; j++)
                {
                    Console.Write(new String(' ', 6));
                }

                top++;
            }

            top = 3;
            char[,] image = nextFigure.GetImage();
            for (int i = 0; i < image.GetLength(0); i++)
            {
                Console.SetCursorPosition(left, top);
                for (int j = 0; j < image.GetLength(1); j++)
                {
                    Console.Write(image[i, j]);
                }

                top++;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here.
            this.IsMouseVisible = true;

            // Window size.
            _graphics.PreferredBackBufferWidth = (int)Helper.WIDTH * 10;
            _graphics.PreferredBackBufferHeight = (int)Helper.HEIGHT * 18;
            _graphics.ApplyChanges();

            //Initialize the game.
            _input = new InputState();
            _blocks = new List<Block>();
            _gravity = Helper.GRAVITY;
            _gameOver = false;

            //Add the first figure.
            _currentFigure = Helper.RandomFigure();
            _currentFigure.Move(new Vector2(Helper.WIDTH * 15, 0));
            _blocks.AddRange(_currentFigure.Blocks);

            //Set the debug figure.
            _debugFigure = _currentFigure;

            base.Initialize();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            //Handle input.
            HandleInput();

            //Quit the cycle if game over.
            if (_gameOver) { return; }

            //Check if a new figure block should be launched.
            if (_currentFigure.IsSleeping)
            {
                //Check for game over.
                if (_blocks.Exists(b => b.Parent.IsSleeping && b.Position.Y <= 0))
                {
                    _gameOver = true;
                    return;
                }
                else
                {
                    _currentFigure = _debugFigure = Helper.RandomFigure();
                    _currentFigure.Move(new Vector2(Helper.WIDTH * 15, 0));
                    _blocks.AddRange(_currentFigure.Blocks);
                }
            }

            //Update the current figure.
            _currentFigure.Update(gameTime, _blocks, _gravity, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

            //Remove all completed rows.
            if (_currentFigure.IsSleeping) { RemoveCompletedRows(); }

            //Call the base method.
            base.Update(gameTime);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Create a left twix figure.
        /// </summary>
        /// <returns>The left twix figure.</returns>
        public static Figure TwixLeft()
        {
            //Create the figure.
            Figure figure = new Figure();

            //Set some attributes.
            figure.Color = Color.Green;

            //Add and create the blocks.
            figure.AddBlock(new Block() { Position = Vector2.Zero });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, 0) });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, HEIGHT) });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH * 2, HEIGHT) });

            figure.CenterBlock = figure.Blocks[1];

            //Return the figure.
            return figure;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Create a straight figure.
        /// </summary>
        /// <returns>The straight figure.</returns>
        public static Figure Straight()
        {
            //Create the figure.
            Figure figure = new Figure();

            //Set some attributes.
            figure.Color = Color.Red;

            //Add and create the blocks.
            figure.AddBlock(new Block() { Position = Vector2.Zero });
            figure.AddBlock(new Block() { Position = new Vector2(0, HEIGHT) });
            figure.AddBlock(new Block() { Position = new Vector2(0, HEIGHT * 2) });
            figure.AddBlock(new Block() { Position = new Vector2(0, HEIGHT * 3) });

            figure.CenterBlock = figure.Blocks[1];

            //Return the figure.
            return figure;
        }
Exemplo n.º 19
0
        public static bool CanRotateRight(Figure figure, Canvas canvas)
        {
            int id = GetNextRightRotationId(figure, canvas);

            return(RotatedFigureIntersectsWithOtherBlocks(id, figure, canvas));
        }
Exemplo n.º 20
0
        private void StartGameButton_Click(object sender, EventArgs e)
        {
            bmp = new Bitmap(PANEL_WIDTH, PANEL_HEIGHT);
            gamefieldPanel.BackgroundImage = bmp;
            gr = Graphics.FromImage(bmp);

            gamefieldArray = new Cell[GAMEFIELD_HEIGHT, GAMEFIELD_WIDTH];
            for (int i = 0; i < GAMEFIELD_HEIGHT; i++)
            {
                for (int j = 0; j < GAMEFIELD_WIDTH; j++)
                {
                    gamefieldArray[i, j] = new Cell(j * CELL_SIZE, i * CELL_SIZE, TAKE_VALUE_0);
                }
            }

            tempCellArray = new Cell[GAMEFIELD_WIDTH];
            for (int i = 0; i < GAMEFIELD_WIDTH; i++)
            {
                tempCellArray[i] = new Cell(0, 0, TAKE_VALUE_0);
            }

            messageTextBox.Visible    = false;
            descriptionLabel1.Visible = true;
            currentScoreLabel.Visible = true;
            currentScoreLabel.Text    = "0";
            rowCount = 0;

            figureList            = new List <Figure>();
            coordList_1_Position1 = new List <Coord>();
            coordList_2_Position1 = new List <Coord>();
            coordList_3_Position1 = new List <Coord>();
            coordList_4_Position1 = new List <Coord>();
            coordList_5_Position1 = new List <Coord>();
            coordList_6_Position1 = new List <Coord>();
            coordList_7_Position1 = new List <Coord>();

            coordListListsPosition1 = new List <List <Coord> >();

            figure = new Figure(new Coord(START_COORD_X1, START_COORD_Y1), new Coord(START_COORD_X2, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y1), new Coord(START_COORD_X4, START_COORD_Y1), "iFigure");//I - фигура
            figureList.Add(figure);
            coordList_1_Position1.Add(new Coord(START_COORD_X1, START_COORD_Y1));
            coordList_1_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y1));
            coordList_1_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y1));
            coordList_1_Position1.Add(new Coord(START_COORD_X4, START_COORD_Y1));
            coordListListsPosition1.Add(coordList_1_Position1);

            figure = new Figure(new Coord(START_COORD_X2, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y1), new Coord(START_COORD_X2, START_COORD_Y2), new Coord(START_COORD_X3, START_COORD_Y2), "oFigure");//O - фигура
            figureList.Add(figure);
            coordList_2_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y1));
            coordList_2_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y1));
            coordList_2_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y2));
            coordList_2_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y2));
            coordListListsPosition1.Add(coordList_2_Position1);

            figure = new Figure(new Coord(START_COORD_X2, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y1), new Coord(START_COORD_X4, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y2), "tFigure");//T - фигура
            figureList.Add(figure);
            coordList_3_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y1));
            coordList_3_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y1));
            coordList_3_Position1.Add(new Coord(START_COORD_X4, START_COORD_Y1));
            coordList_3_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y2));
            coordListListsPosition1.Add(coordList_3_Position1);

            figure = new Figure(new Coord(START_COORD_X2, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y2), new Coord(START_COORD_X4, START_COORD_Y2), "zFigure");//Z - фигура
            figureList.Add(figure);
            coordList_4_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y1));
            coordList_4_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y1));
            coordList_4_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y2));
            coordList_4_Position1.Add(new Coord(START_COORD_X4, START_COORD_Y2));
            coordListListsPosition1.Add(coordList_4_Position1);

            figure = new Figure(new Coord(START_COORD_X4, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y2), new Coord(START_COORD_X2, START_COORD_Y2), "sFigure");//S - фигура
            figureList.Add(figure);
            coordList_5_Position1.Add(new Coord(START_COORD_X4, START_COORD_Y1));
            coordList_5_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y1));
            coordList_5_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y2));
            coordList_5_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y2));
            coordListListsPosition1.Add(coordList_5_Position1);

            figure = new Figure(new Coord(START_COORD_X2, START_COORD_Y2), new Coord(START_COORD_X2, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y1), new Coord(START_COORD_X4, START_COORD_Y1), "lFigure");//L - фигура
            figureList.Add(figure);
            coordList_6_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y2));
            coordList_6_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y1));
            coordList_6_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y1));
            coordList_6_Position1.Add(new Coord(START_COORD_X4, START_COORD_Y1));
            coordListListsPosition1.Add(coordList_6_Position1);

            figure = new Figure(new Coord(START_COORD_X2, START_COORD_Y1), new Coord(START_COORD_X3, START_COORD_Y1), new Coord(START_COORD_X4, START_COORD_Y1), new Coord(START_COORD_X4, START_COORD_Y2), "jFigure");//J - фигура
            figureList.Add(figure);
            coordList_7_Position1.Add(new Coord(START_COORD_X2, START_COORD_Y1));
            coordList_7_Position1.Add(new Coord(START_COORD_X3, START_COORD_Y1));
            coordList_7_Position1.Add(new Coord(START_COORD_X4, START_COORD_Y1));
            coordList_7_Position1.Add(new Coord(START_COORD_X4, START_COORD_Y2));
            coordListListsPosition1.Add(coordList_7_Position1);

            rnd          = new Random();
            randomResult = rnd.Next(0, figureList.Count);
            figureList[randomResult].DrawFigure(gr, pen, CELL_SIZE);
            timerForTetris.Start();
        }
Exemplo n.º 21
0
        /// <summary>
        /// See if a move is allowed by a figure.
        /// </summary>
        /// <param name="figure">The figure to move.</param>
        /// <param name="move">The desired move amount.</param>
        /// <returns>Whether the move is valid.</returns>
        public static bool IsMoveAllowed(Figure figure, Vector2 move, List<Block> blocks)
        {
            //Set some startup variables.
            bool valid = false;

            //Project the current figure to the new position and see whether the move was valid.
            figure.Move(move);
            valid = !blocks.Exists(block => figure.Intersects(block));
            figure.Move(-move);

            //Return the result.
            return valid;
        }
Exemplo n.º 22
0
        void timeRefrash_Tick(object sender, EventArgs e)
        {
            if (flag)
            {
                fig = null;
                for (int i = 0; i < 20; i++)
                    for (int j = 0; j < 10; j++)
                        this.myCanvas1.background[i, j] += this.myCanvas1.matrix[i, j];
                delLine();
                flag = false;
            }
            if (fig == null)
            {
                createFig();

                if (!canStep())
                {
                    figToCanv();
                    figureStep();
                }
            }
            else
            {
                if (!canStep())
                {
                    for (int i = 0; i < 20; i++)
                        for (int j = 0; j < 10; j++)
                            this.myCanvas1.matrix[i, j] = 0;
                    figToCanv();
                    figureStep();
                }
            }

            this.myCanvas1.Refresh();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Let the game handle user input.
        /// </summary>
        protected void HandleInput()
        {
            //Read the keyboard and gamepad.
            _input.Update();

            // Allows the game to exit.
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); }
            if (_input.IsKeyDown(Keys.Escape)) { this.Exit(); }

            //Let the current figure handle input.
            _currentFigure.HandleInput(_input);

            #region Debug
            //Select a figure.
            if (_input.IsNewLeftMouseClick())
            {
                Block debug = _blocks.Find(item => item.Contains(new Vector2(Mouse.GetState().X, Mouse.GetState().Y)));
                _debugFigure = debug == null || debug.Parent == null ? _currentFigure : (Figure)debug.Parent;
            }
            //Pause the game, ie. stop the gravity.
            if (_input.IsNewKeyPress(Keys.P)) { _gravity = _gravity == 0 ? Helper.GRAVITY : 0; }
            #endregion
        }
Exemplo n.º 24
0
        public void Paint(Graphics g)
        {
            Pen        border = new Pen(BorderColor, 2F);
            SolidBrush fone   = new SolidBrush(BackColor);

            g.DrawRectangle(border, 4, 4, TilesWidth * TileSide + 2, TilesHeight * TileSide + 2);
            g.FillRectangle(fone, 5, 5, TilesWidth * TileSide, TilesHeight * TileSide);

            for (int row = 0; row < TilesHeight; row++)
            {
                for (int col = 0; col < TilesWidth; col++)
                {
                    Rectangle tile = new Rectangle(5 + col * TileSide, 5 + row * TileSide, TileSide, TileSide);
                    switch (Tiles[row, col])
                    {
                    case TileType.IBlock:
                        if (MainForm.Blue == null)
                        {
                            g.FillRectangle(Brushes.Blue, tile);
                        }
                        else
                        {
                            g.DrawImage(MainForm.Blue, tile);
                        }
                        break;

                    case TileType.ZBlock:
                        if (MainForm.Green == null)
                        {
                            g.FillRectangle(Brushes.Green, tile);
                        }
                        else
                        {
                            g.DrawImage(MainForm.Green, tile);
                        }
                        break;

                    case TileType.SquareBlock:
                        if (MainForm.Yellow == null)
                        {
                            g.FillRectangle(Brushes.Yellow, tile);
                        }
                        else
                        {
                            g.DrawImage(MainForm.Yellow, tile);
                        }
                        break;

                    case TileType.TBlock:
                        if (MainForm.Purple == null)
                        {
                            g.FillRectangle(Brushes.Purple, tile);
                        }
                        else
                        {
                            g.DrawImage(MainForm.Purple, tile);
                        }
                        break;

                    case TileType.ReverseLBlock:
                        if (MainForm.Orange == null)
                        {
                            g.FillRectangle(Brushes.Orange, tile);
                        }
                        else
                        {
                            g.DrawImage(MainForm.Orange, tile);
                        }
                        break;

                    case TileType.SBlock:
                        if (MainForm.Red == null)
                        {
                            g.FillRectangle(Brushes.Red, tile);
                        }
                        else
                        {
                            g.DrawImage(MainForm.Red, tile);
                        }
                        break;

                    case TileType.LBlock:
                        if (MainForm.LightBlue == null)
                        {
                            g.FillRectangle(Brushes.LightBlue, tile);
                        }
                        else
                        {
                            g.DrawImage(MainForm.LightBlue, tile);
                        }
                        break;
                    }
                }
            }

            if (ShowTips && IsFigureFalling)
            {
                Figure tip = Current;
                EraseFigure(Current);

                while (IsEmpty(tip))
                {
                    tip = tip.MoveDown();
                }
                tip = tip.MoveUp();

                SetFigure(Current, false);

                Point[] cells = new Point[]
                {
                    new Point(tip.XC, tip.YC), new Point(tip.X1, tip.Y1),
                    new Point(tip.X2, tip.Y2), new Point(tip.X3, tip.Y3)
                };

                SolidBrush b = new SolidBrush(Color.FromArgb(32, 192, 0, 0));
                Pen        p = new Pen(Color.FromArgb(128, 192, 0, 0), 1);

                foreach (Point cell in cells)
                {
                    if (!IsEmpty(cell.Y, cell.X))
                    {
                        continue;
                    }
                    Rectangle tile = new Rectangle(6 + cell.X * TileSide, 6 + cell.Y * TileSide, TileSide - 2,
                                                   TileSide - 2);
                    g.FillRectangle(b, tile);
                }
            }
        }
Exemplo n.º 25
0
 //новая игра
 private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
 {
     timer.Stop();
     labelPause.Text = @"PAUSE";
     labelPause.Visible = false;
     enter = true;
     //очищаем поле
     InitializeField();
     labelLevel.Text = @"Level: 1";
     labelLines.Text = @"Lines: 0";
     lines = 0;
     figure = nextFigure.GetNext(this);
     pictureBox1.Invalidate();
     //таймер запускающий игру
     timer.Start();
     PictureNextFigure.Invalidate();
 }
Exemplo n.º 26
0
 public static int GetNextRightRotationId(Figure figure, Canvas canvas)
 {
     return(figure.RotationId == 0 ? 3 : figure.RotationId - 1);
 }
Exemplo n.º 27
0
 public static int GetNextLeftRotationId(Figure figure, Canvas canvas)
 {
     return(figure.RotationId == 3 ? 0 : figure.RotationId + 1);
 }
Exemplo n.º 28
0
 public void save_backup()
 {
     this.backup = null;
     this.backup = new Figure(this);
 }
Exemplo n.º 29
0
        /// <summary>
        /// See if a rotation is allowed by a figure.
        /// </summary>
        /// <returns>Whether the rotation is valid.</returns>
        public static bool IsRotationAllowed(Figure figure, List<Block> blocks)
        {
            //Project the current figure to the new position.
            var proj = new Figure(figure) { Left = figure.Left, Bottom = figure.Bottom };
            proj.Rotate();

            //Return whether the movement is valid.
            return !blocks.Exists(block => !figure.Blocks.Contains(block) && proj.Intersects(block));
        }
Exemplo n.º 30
0
        /// <summary>
        /// Create a square figure.
        /// </summary>
        /// <returns>The square figure.</returns>
        public static Figure Square()
        {
            //Create the figure.
            Figure figure = new Figure();

            //Set some attributes.
            figure.Color = Color.Blue;

            //Add and create the blocks.
            figure.AddBlock(new Block() { Position = Vector2.Zero });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, 0) });
            figure.AddBlock(new Block() { Position = new Vector2(0, HEIGHT) });
            figure.AddBlock(new Block() { Position = new Vector2(WIDTH, HEIGHT) });

            //Return the figure.
            return figure;
        }
Exemplo n.º 31
0
 /// <summary>
 /// Makes one step in the game and calls the Update() method of every non-static object in the game
 /// </summary>
 private void MakeStep()
 {
     this.currentFigure.MoveDown();
     this.currentFigure.Update();
     if (!this.isOnValidPosition(this.currentFigure))
     {
         this.currentFigure.MoveUp();
         this.staticObjects.Add(currentFigure);
         this.currentFigure = this.nextFigure;
         this.nextFigure = this.figureGenerator.GenerateFigure(new Position(this.renderer.Width / 2, 0));
         renderer.PrintNextFigure(this.nextFigure);
         this.RemoveFullLines();
         this.Speed = this.NormalSpeed;
         if (this.staticObjects[this.staticObjects.Count - 1].Y <= 0)
         {
             this.gameOver = true;
             renderer.PrintGameOver();
         }
     }
 }
Exemplo n.º 32
0
        //конструктор
        public Form1()
        {
            InitializeComponent();

            nextFigure = new NextFigure(this);

            //инициализация таймера
            timer = new Timer {
                Interval = speed
            };
            timer.Tick += (sender, args) =>
            {
                if (figure.Down())
                {
                    ;
                }
                else
                {
                    HorizontalRow();
                    GameOver();
                    figure = nextFigure.GetNext(this);
                }
                pictureBox1.Invalidate();
                PictureNextFigure.Invalidate();
            };

            //инициализация цвета отрисовки подквадрата
            myPen = new Pen(Color.Black)
            {
                LineJoin = LineJoin.Miter,
                Width    = 2.0F
            };

            //отрисовка стакана и сетки
            pictureBox1.Image = (Image) new Bitmap(pictureBox1.Width, pictureBox1.Height);
            var g = Graphics.FromImage(pictureBox1.Image);
            var p = new Pen(Color.DarkSlateGray);

            for (var i = 0; i < 10; i++)
            {
                g.DrawLine(p, pictureBox1.Width / 10 * (i + 1), 0, pictureBox1.Width / 10 * (i + 1), pictureBox1.Height);
            }
            for (var i = 0; i < 20; i++)
            {
                g.DrawLine(p, 0, pictureBox1.Height / 20 * (i + 1), pictureBox1.Width, pictureBox1.Height / 20 * (i + 1));
            }

            //красная линия
            g.DrawLine(Pens.Red, 0, pictureBox1.Height / 20 * 3, pictureBox1.Width, pictureBox1.Height / 20 * 3);

            //инициализация массива/поля
            InitializeField();

            //текущий уровень сложности
            labelLevel.Text = $"Level: {level}";

            //инициализация массива координат следущей фигуры
            for (var i = 0; i < 3; i++)
            {
                for (var j = 0; j < 4; j++)
                {
                    smallField[i, j] = new Component((j * width) + 1, (i * width) + 1, Brushes.Black);
                }
            }

            //pictureBox на котором будет отображаться следущая фигура
            PictureNextFigure = new PictureBox
            {
                Location  = new Point(324, 91),
                Size      = new Size(101, 76),
                BackColor = Color.Black
            };

            //добавляем контрол к форме
            this.Controls.Add(PictureNextFigure);

            //обработчик перерисовки поля
            PictureNextFigure.Paint += (s, e) =>
            {
                for (var i = 0; i < 3; i++)
                {
                    for (var j = 0; j < 4; j++)
                    {
                        //если в текущей клетке стоит фигура рисуем квадрат
                        if (smallField[i, j].brush != Brushes.Black)
                        {
                            e.Graphics.FillRectangle(smallField[i, j].brush
                                                     , smallField[i, j].x, smallField[i, j].y, width - 1, width - 1);
                            //и подквадрат
                            e.Graphics.DrawRectangle(myPen, smallField[i, j].x + 3, smallField[i, j].y + 3,
                                                     width - 7, width - 7);
                        }
                    }
                }
            };

            labelPause.Text    = @"TETRIS";
            labelPause.Visible = true;
            soundControl.playMain();
        }
Exemplo n.º 33
0
        //конструктор
        public Form1()
        {
            
            InitializeComponent();

            nextFigure = new NextFigure(this);

            //инициализация таймера
            timer = new Timer {Interval = speed};
            timer.Tick += (sender, args) =>
            {
                if (figure.Down()) ;
                else
                {
                    HorizontalRow();
                    GameOver();
                    figure = nextFigure.GetNext(this);
                }
                pictureBox1.Invalidate();
                PictureNextFigure.Invalidate();
            };

            //инициализация цвета отрисовки подквадрата
            myPen = new Pen(Color.Black)
            {
                LineJoin = LineJoin.Miter,
                Width = 2.0F
            };

            //отрисовка стакана и сетки
            pictureBox1.Image = (Image) new Bitmap(pictureBox1.Width, pictureBox1.Height);
            var g = Graphics.FromImage(pictureBox1.Image);
            var p = new Pen(Color.DarkSlateGray);
            for (var i = 0; i < 10; i++)
                g.DrawLine(p, pictureBox1.Width/10*(i + 1), 0, pictureBox1.Width/10*(i + 1), pictureBox1.Height);
            for (var i = 0; i < 20; i++)
                g.DrawLine(p, 0, pictureBox1.Height/20*(i + 1), pictureBox1.Width, pictureBox1.Height/20*(i + 1));

            //красная линия
            g.DrawLine(Pens.Red, 0, pictureBox1.Height/20*3, pictureBox1.Width, pictureBox1.Height/20*3);

            //инициализация массива/поля
            InitializeField();

            //текущий уровень сложности
            labelLevel.Text = $"Level: {level}";

            //инициализация массива координат следущей фигуры
            for (var i = 0; i < 3; i++)
                for (var j = 0; j < 4; j++)
                    smallField[i, j] = new Component((j * width) + 1, (i * width) + 1, Brushes.Black);

            //pictureBox на котором будет отображаться следущая фигура
            PictureNextFigure = new PictureBox
            {
                Location = new Point(324, 91),
                Size = new Size(101, 76),
                BackColor = Color.Black
            };

            //добавляем контрол к форме
            this.Controls.Add(PictureNextFigure);

            //обработчик перерисовки поля
            PictureNextFigure.Paint += (s, e) =>
            {
                for (var i = 0; i < 3; i++)
                    for (var j = 0; j < 4; j++)
                    {
                        //если в текущей клетке стоит фигура рисуем квадрат
                        if (smallField[i, j].brush != Brushes.Black)
                        {
                            e.Graphics.FillRectangle(smallField[i, j].brush
                            , smallField[i, j].x, smallField[i, j].y, width - 1, width - 1);
                            //и подквадрат
                            e.Graphics.DrawRectangle(myPen, smallField[i, j].x + 3, smallField[i, j].y + 3, 
                                width - 7, width - 7);
                        }
                    }
            };

            labelPause.Text = @"TETRIS";
            labelPause.Visible = true;
            soundControl.playMain();
        }
Exemplo n.º 34
0
 public void InitFigure()
 {
     _figure = (Figure) Activator.CreateInstance(_figures[_rand.Next(_figures.Length)]);
     _figure.position.x = (_width / 2) - (_figure.FigureWidht() / 2);
     _figure.color = _rand.Next(14) + 1;
 }
Exemplo n.º 35
0
 public Figure_move(Figure figure) : base(figure)
 {
 }
Exemplo n.º 36
0
        /// <summary>
        /// See if a move is allowed by a figure.
        /// </summary>
        /// <param name="figure">The figure to move.</param>
        /// <param name="move">The desired move amount.</param>
        /// <param name="assist">The move assist.</param>
        /// <param name="allowNegativeY">Whether to allow the figure to find a position above the current one.</param>
        /// <returns>Whether the move is valid.</returns>
        public static bool IsMoveAllowed(Figure figure, Vector2 move, List<Block> blocks, out Vector2 assist, bool allowNegativeY)
        {
            //Set some startup variables.
            bool valid = false;
            assist = move;

            //Try to find an acceptable position by granting the figure some leeway.
            for (int x = 0; x <= WIDTH / 2; x++)
            {
                for (int y = 0; y <= HEIGHT / 2; y++)
                {
                    //Do four tests; (x, y), (x, -y), (-x, y), (-x, -y).
                    for (int n = 0; n < 4; n++)
                    {
                        //Decide upon the x, y configuration.
                        Vector2 config = Vector2.Zero;
                        switch (n)
                        {
                            case 0: { config = new Vector2(x, y); break; }
                            case 1: { config = allowNegativeY ? new Vector2(x, -y) : new Vector2(x, y); break; }
                            case 2: { config = new Vector2(-x, y); break; }
                            case 3: { config = allowNegativeY ? new Vector2(-x, -y) : new Vector2(-x, y); break; }
                        }

                        //Project the current figure to the new position and see whether the move was valid.
                        figure.Move(move + config);
                        valid = !blocks.Exists(block => figure.Intersects(block));
                        figure.Move(-(move + config));

                        //If the move was valid, stop here.
                        if (valid) { assist = move + config; return valid; }
                    }
                }
            }

            //Return the result (Hint: fail).
            return valid;
        }
Exemplo n.º 37
0
        /// <summary>
        /// Constructs the engine with custom figure generator
        /// </summary>
        /// <param name="renderer">An IRenderer object</param>
        /// <param name="userInterface">An IUserInterface object</param>
        /// <param name="figureGenerator">An IFigureGenerator</param>
        public Engine(IRenderer renderer, IUserInterface userInterface, IFigureGenerator figureGenerator)
        {
            if (renderer == null)
            {
                throw new IncorrectParametersException("The renderer can not be null.");
            }

            if (userInterface == null)
            {
                throw new IncorrectParametersException("The user interface can not be null.");
            }

            if (figureGenerator == null)
            {
                throw new IncorrectParametersException("The figure generator can not be null.");
            }

            this.renderer = renderer;
            this.userInterface = userInterface;
            this.figureGenerator = figureGenerator;

            this.currentFigure = this.figureGenerator.GenerateFigure(new Position(this.renderer.Width / 2, 0));
            this.nextFigure = this.figureGenerator.GenerateFigure(new Position(this.renderer.Width / 2, 0));
            this.staticObjects = new List<Figure>();
            this.speed = this.normalSpeed;
        }
Exemplo n.º 38
0
 private void createFig()
 {
     Random rand = new Random();
     int rn = rand.Next(0, 4);
     //int rn = 0;
     switch (rn)
     {
         case 0:
             fig = new Line();
             break;
         case 1:
             fig = new Square();
             break;
         case 2:
             fig = new Crane();
             break;
         case 3:
             fig = new Lightning();
             break;
     }
 }