Пример #1
0
        private void MoveSnake()
        {
            // Remove the last part of the snake, in preparation of the new part added below
            while (snakeParts.Count >= snakeLength)
            {
                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 SnakeDirection.Left:
                nextX -= SnakeSquareSize;
                break;

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

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

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

            // Now add the new head part to our list of snake parts...
            snakeParts.Add(new SnakePart()
            {
                Position = new Point(nextX, nextY),
                IsHead   = true
            });
            //... and then have it drawn!
            DrawSnake();
            // Finally: Check if it just hit something!
            DoCollisionCheck();
        }
Пример #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 >= GameArea.ActualHeight) ||
                (snakeHead.Position.X < 0) || (snakeHead.Position.X >= 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();
                }
            }
        }