Getting the snake to increase in length, and follow the head
in
Programming Questions
•
6 months ago
I am new to programming, and have decided to make the game snake for my introductory programming class. I am having trouble getting the snake to increase in length, and for each block to follow the head. My professor told me to use ArrayLists, which I am unfamiliar with. Can someone please direct me in what I should do to make this work? Below is my code, and thank you in advance.
ArrayList snake;
boolean food = true, game = true;
float snakeX = 400, snakeY = 300;
float foodX = random(750), foodY = random(550);
int score = 1, dir =1;
void setup() {
size (800, 600);
snake = new ArrayList();
snake.add(new PVector(width/2, height/2));
}
void draw() {
background(255);
drawSnake();
if (game == true) {
movesnake();
}
collison();
drawFood();
fill (0);
textSize (12);
text ("score:", width-65, 20);
text (score, width-30, 20);
}
void movesnake() {
if (keyPressed) {
if (key == 'w' && dir !=3|| key == 'W' && dir !=3|| keyCode == UP && dir !=3) {
dir = 1;
}
else if (key == 'd' && dir !=4|| key == 'D' && dir !=4|| keyCode == RIGHT && dir !=4) {
dir = 2;
}
else if (key == 's' && dir !=1|| key == 'S'&& dir !=1|| keyCode == DOWN && dir !=1) {
dir = 3;
}
else if (key == 'a' && dir !=2|| key == 'A' && dir !=2|| keyCode == LEFT && dir !=2) {
dir = 4;
}
}
if (dir == 1)
snakeY -=4;
else if (dir == 2)
snakeX +=4;
else if (dir == 3)
snakeY +=4;
else if (dir == 4)
snakeX -=4;
}
void drawSnake() {
for (int i=0; i< snake.size(); i++) {
PVector p = (PVector) snake.get (i);
p.x =snakeX;
p.y = snakeY;
fill(0, 250, 0);
rect(p.x, p.y, 20, 20);
}
}
void addToSnake() {
for (int i=0; i< snake.size(); i++) {
PVector p = (PVector) snake.get (i);
snake.add(new PVector(snakeX-20, height/2));
fill(0, 250, 0);
rect(p.x, p.y, 20, 20);
}
}
void updateSnake() {
}
void drawFood() {
fill (250, 0, 0);
rect (foodX, foodY, 20, 20);
}
void collison() {
if ( snakeX >= width-20 || snakeX <= 0 || snakeY >= height-20 || snakeY <= 0) {
dir = 0;
game = false;
textSize(15);
text ("click to play again", width/2-80, height/2+30);
textSize(30);
text("GAME OVER", width/2-100, height/2);
if (mousePressed) {
snakeX = 400;
snakeY = 300;
score = 1;
dir = 1;
foodX = int(random (750));
foodY = int(random (550));
game = true;
}
}
if (snakeX >= foodX && snakeX <= foodX + 20 && snakeY >= foodY && snakeY <= foodY +20 ||snakeX+20 >= foodX && snakeX+20 <= foodX + 20 && snakeY+20 >= foodY && snakeY+20 <= foodY +20) {
food = false;
score ++ ;
foodX = int(random (750));
foodY = int(random (550));
food = true;
addToSnake();
}
}
1