How do I make the snake's tail add on when i hit the apple?

ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();

int gridSize = 20;
int h = height;
int w = height;
int xdir = 0;
int ydir = 0;
boolean eaten = false;
int applex;
int appley;

void setup() {
  size(400, 400);
  frameRate(8);
  x.add(width - gridSize*12);
  y.add(height - gridSize*12);
  x.add(width - gridSize*13);
  y.add(height - gridSize*12);
  
  appley = int(random(0, w/gridSize));
  applex = int(random(0, w/gridSize));
}

void draw() {
  background(0);
  grid();
  testMovement();
  fill(255, 0, 0);
  rect(applex*gridSize, appley*gridSize, gridSize, gridSize);
  
  for (int i = 0; i < x.size(); i++) {
    int xpos = x.get(i);
    int ypos = y.get(i);
    int lastxpos = x.get(0);
    int lastypos = y.get(0);
    fill(0, 255, 0);
    rect(x.get(i), y.get(i), gridSize, gridSize);
    
    x.add(xpos += xdir*gridSize);
    y.add(ypos += ydir*gridSize);
    x.remove(0);
    y.remove(0);
//this is where im struggling
    if (xpos == applex*gridSize && ypos == appley*gridSize) {
      x.add(lastxpos += xdir);
      y.add(lastypos += ydir);
    }
  }
}

void grid() {
  stroke(150);
  for (int j = 0; j < width; j++) {
    line(j*gridSize, 0, j*gridSize, height);
  }
  for (int k = 0; k < height; k++) {
    line(0, k*gridSize, width, k*gridSize);
  }
}

void testMovement() {
  if (keyPressed) {
    if (keyCode == UP) {
      xdir = 0; ydir = -1;
    }
    if (keyCode == DOWN) {
      xdir = 0; ydir = 1;
    }
    if (keyCode == LEFT) {
      xdir = -1; ydir = 0;
    }
    if (keyCode == RIGHT) {
      xdir = 1; ydir = 0;
    }
  }
}```

Hello and welcome to the forum!

Great to have you here!

Can you please state a question about your current code?

Thank you!

Chrisir

Hello,

You posted code and a subject but have not asked a specific question.

Please read and update your post:

https://discourse.processing.org/faq

:)

1 Like

Hi Chrisir,

I have wanted to make snake since I started processing.
As soon as i found out what an arraylist was, i tried to make it.
However, i can’t figure out how to make the snake add on properly.
As you can see, it adds on, but in the wrong spot and goes at a random speed.
I think it is around here that i am struggling:

Hopefully you can help,
Thanks