Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: How do I let the tail of my snake grow?

1. ## How do I let the tail of my snake grow?

It starts at 2, but when the snake eats an apple it becomes 1 and after it eats another apple, it goes back to 2. Please help!

This is my code:
//x, y

int xMax = 13, yMax = 13;

int xApple, yApple;

int xRandom = 10, yRandom = 7;

int leftOffset = 700, topOffset = 280;

int dir = 0;

//size
int tileSize = 40;
int appleSize = 30;

//More
ArrayList<Integer> xTail = new ArrayList<Integer>(), yTail = new ArrayList<Integer>();
int score;
int spd;
boolean gameOver = false;
boolean youWon = false;

void setup() {
size(1920, 1080);
frameRate(8);
}

void draw() {
background(170, 150, 220);

Field();

if(dir == 1 && xHead < xMax - 1) {xHead += 1;} //Right
if(dir == 2 && yHead < yMax - 1) {yHead += 1;} //Down

AppleEaten();
Apple();
Score();

for (int i = (xTail.size() - 1); i >= 0; i--) {
if (i == 0) {
} else {
xTail.set(i, xTail.get(i-1));
yTail.set(i, yTail.get(i-1));
}

fill(60, 170, 70);
rect(leftOffset + xTail.get(i) * tileSize, topOffset + yTail.get(i) * tileSize, tileSize, tileSize);
fill(60, 170, 70);
rect(leftOffset + xTail.get(i) * tileSize, topOffset + yTail.get(i) * tileSize, tileSize, tileSize);
}
}
}

void keyPressed(){
if(keyCode == 39 && dir != 3) {dir = 1;}
if(keyCode == 40 && dir != 4) {dir = 2;}
if(keyCode == 37 && dir != 1) {dir = 3;}
if(keyCode == 38 && dir != 2) {dir = 4;}
}

void Field(){
int xWaarde = 0;
int yWaarde = 0;
fill(100, 240, 100);
for(int i = 0; i < xMax; i++){
for(int j = 0; j < yMax; j++){
strokeWeight(0);
if((i+j) % 2 == 0) {fill(100, 230, 100);}
else {fill(100, 240, 100);}
rect(leftOffset + xWaarde * tileSize, topOffset + yWaarde * tileSize, tileSize, tileSize);
yWaarde ++;
}
yWaarde = 0;
xWaarde ++;
}
}

fill(60, 170, 70);
rect(leftOffset + xHead * tileSize, topOffset + yHead * tileSize, tileSize, tileSize);
}

void Apple() {
xApple = leftOffset - (tileSize / 2) + (xRandom * tileSize);
yApple = topOffset - (tileSize / 2) + (yRandom * tileSize);
fill(255, 0, 0);
ellipse(xApple, yApple, appleSize, appleSize);
}

void AppleEaten(){
score++;
xRandom = round(random(1, 13));
yRandom = round(random(1, 13));