Пример #1
0
        /// <summary>
        /// Event that defines what happens on each game tick.
        /// </summary>
        public void tick(Object sender, EventArgs e)
        {
            prevdirectionX = directionX;
            prevdirectionY = directionY;
            int snakeX = snake.getX();
            int snakeY = snake.getY();

            // Check snake collision with borders, food, or itself
            if (snakeX > board.ActualWidth || snakeX < 0 || snakeY < 0 || snakeY > board.ActualHeight)
            {
                // Game over
                timer.Stop();
            }
            if (snakeX == food.getX() && snakeY == food.getY())
            {
                snake.addBody();
                food.newLocation();
            }
            int snakeSize = snake.body.Count;

            for (int i = 0; i < snakeSize; i++)
            {
                int bodyX = snake.body[i].Item1;
                int bodyY = snake.body[i].Item2;
                if (snakeX == bodyX && snakeY == bodyY)
                {
                    // Game over
                    timer.Stop();
                }
            }

            // Update the snake body starting with the tail
            for (int i = snakeSize - 1; i > 0; i--)
            {
                int forwardX = snake.body[i - 1].Item1;
                int forwardY = snake.body[i - 1].Item2;
                snake.body[i] = new Tuple <int, int>(forwardX, forwardY);
            }
            snake.body[0] = new Tuple <int, int>(snakeX, snakeY);

            // Update the snake head
            int newX = snakeX + directionX;
            int newY = snakeY + directionY;

            snake.setX(newX);
            snake.setY(newY);

            render();
        }