Esempio n. 1
0
        public void MoveSnake()
        {
            // Remove the last part of the snake, in preparation of the new part added below
            while (snakeParts.Count >= snakeLength)
            {
                mw.GameArea.Children.Remove(snakeParts[0].UiElement);
                snakeParts.RemoveAt(0);
            }

            // Next up, we'll add a new element to the snake, which will be the (new) head
            // Therefore, we mark all existing parts as non-head (body) elements and then
            // we make sure that they use the body brush
            foreach (SnakePart snakePart in snakeParts)
            {
                (snakePart.UiElement as Rectangle).Fill = snakeBodyBrush;
                snakePart.IsHead = false;
            }

            // Determine in which direction to expand the snake, based on the current direction
            SnakePart snakeHead = snakeParts[snakeParts.Count - 1];
            double    nextX     = snakeHead.Position.X;
            double    nextY     = snakeHead.Position.Y;

            switch (snakeDirection)
            {
            case MainWindow.SnakeDirection.Left:
                nextX -= vm.SnakeSquareSize;
                break;

            case MainWindow.SnakeDirection.Right:
                nextX += vm.SnakeSquareSize;
                break;

            case MainWindow.SnakeDirection.Up:
                nextY -= vm.SnakeSquareSize;
                break;

            case MainWindow.SnakeDirection.Down:
                nextY += vm.SnakeSquareSize;
                break;
            }

            // Now add the new head part to our list of snake parts...
            snakeParts.Add(new SnakePart(mw, vm)
            {
                Position = new Point(nextX, nextY),
                IsHead   = true
            });
            //... and then have it drawn!
            DrawSnake();

            DoCollisionCheck();
        }
Esempio n. 2
0
        private void DoCollisionCheck()
        {
            SnakePart snakeHead = snakeParts[snakeParts.Count - 1];

            if ((snakeHead.Position.X == Canvas.GetLeft(snakeFood)) && (snakeHead.Position.Y == Canvas.GetTop(snakeFood)))
            {
                EatSnakeFood();
                return;
            }

            if ((snakeHead.Position.Y < 0) || (snakeHead.Position.Y >= mw.GameArea.ActualHeight) ||
                (snakeHead.Position.X < 0) || (snakeHead.Position.X >= mw.GameArea.ActualWidth))
            {
                EndGame();
            }

            foreach (SnakePart snakeBodyPart in snakeParts.Take(snakeParts.Count - 1))
            {
                if ((snakeHead.Position.X == snakeBodyPart.Position.X) && (snakeHead.Position.Y == snakeBodyPart.Position.Y))
                {
                    EndGame();
                }
            }
        }
Esempio n. 3
0
 public MainViewModel(MainWindow mainWindow)
 {
     mw        = mainWindow;
     snakePart = new SnakePart(mw, this);
 }