Snake game: lengthen the snake (in Xammarin Android)

29 Views Asked by At

I am developing snake game using canvas.
I succeeded to move the snake (which is at start one circle) by sliding and for it to collide in apples shaped rectangle, while the apples disapear from the screen and the score goes up in one point.

So the problem I faced was that even though I managed to lengthen the snake by attaching to the circle at the begining another circle each time it collides in red rectangle, The lengthening is very slow.

I know that the problem is with my approach. I have made a list of circles as an attribute of the class Snake. Every call of the method Ondraw I gave the circle's cordinates to the circle that follows it and the cordinates of the circle of the start I changed according to the direction in which the snake was moving. Then, I draw all of the circles.

I have tried looking online for a solution but I didn't find anything. here is an example of the direction right:
if (direction == "right")
            {
                for (int i = snake.lsnake.Count - 1; i > 0; i--)
                { 
                    snake.lsnake[i].y = snake.lsnake[i - 1].y;
                    snake.lsnake[i].x = snake.lsnake[i - 1].x;
                }
                x += deltax;
                snake.lsnake[0].x = x;
                for (int i = 0; i < snake.lsnake.Count; i++)
                {
                    canvas.DrawCircle(snake.lsnake[i].x, snake.lsnake[i].y, snake.lsnake[i].radius, p);
                }
            }

The class Snake:

class Snake
    {
        public const int radius = 50;
        public List<Circle> lsnake;

        public Snake()
        {
            lsnake = new List<Circle>();
        }
        public void Add(int x, int y)
        {
            lsnake.Add(new Circle(x, y, radius));
        }
    }

The class Circle:

class Circle
    {
        public int x { get; set; }
        public int y { get; set; }
        public int radius { get; set; }
        public Circle(int x,int y,int radius)
        {
            this.x = x;
            this.y = y;
            this.radius = radius;
        }
    }
0

There are 0 best solutions below