-1

This is my first time asking a Q so I'm not sure if I put the question correctly, but I'm trying to rewrite open source code of a snake game I found online. The idea of the snake movement is passing the position (x, y) of the head to an array of the tail where each element represents a tail segment. So, the position of the head is passed to the first segment which is in turn passed to the second, third,..., n - 1th segment. Here's the code that was used in the original source code

    int prevX = tailX[0];
    int prevY = tailY[0];
    int prev2X, prev2Y;
    tailX[0] = x;
    tailY[0] = y;
    for (int i = 1; i < lenTail; i++)
    {
        prev2X = tailX[i];
        prev2Y = tailY[i];
        tailX[i] = prevX;
        tailY[i] = prevY;
        prevX = prev2X;
        prevY = prev2Y;
    } 

And here's what my brain who's three months into C++ wants to replicate it with

//tail algorithm
    tailX[0] = x; tailY[0] = y;
    for(int i = 0; i< lenTail; i++){
        
        tailX[i + 1] = tailX[i];
        tailY[i + 1] = tailY[i];
    }

It works when the snake is moving either right or left but has a bug in the up or down movement. Help me

SultanOrazbayev
  • 8,817
  • 3
  • 9
  • 37
  • You'll go out of bounds of the array for the last iteration leading to undefined behavior. As you've used `tailX[i + 1]` – Anoop Rana Jun 04 '22 at 07:22

0 Answers0