Hello, I really need help. I have to code snake but I have no clue anymore what to do. I currently have the snake coded and an apple which spawns at the start randomly.
I need help in the following:
- Snake should be able to eat the apple and when eating, the size should increase +1 and a new apple should spawn
- A score display, how many apples the snake ate
- When touching the edge, the game should stop
Optional:
- If you are moving to the right, you cant move to the left. The same on the opposite way
I’m trying to code it for about 5 hours now but I’m just not friendly with that PVector (but I have to)
My code:
ArrayList<PVector> snake = new ArrayList<PVector>();
int speed = 50;
PImage background;
float appleX = random(780), appleY = random(780);
void setup() {
PVector head = new PVector(150, 350);
snake.add(head);
for (int i = 0; i < 3; i++) {
snake.add(new PVector(100 + i * 50, 350));
}
background = loadImage("Background.png");
image(background, 0, 0);
size(800, 800);
frameRate(6);
}
void draw() {
background(background);
drawApple();
fill(#426fe3);
move();
for (int i = 0; i < snake.size(); i++) {
PVector element = snake.get(i);
rect(element.x, element.y, 50, 50, 12);
}
}
void move() {
int xMove = 0, yMove = 0;
switch (keyCode) {
case UP:
yMove = -speed;
break;
case DOWN:
yMove = speed;
break;
case LEFT:
xMove = -speed;
break;
case RIGHT:
xMove = speed;
break;
}
if (xMove == 0 && yMove == 0) {
return;
}
PVector newHead = new PVector(snake.get(0).x + xMove, snake.get(0).y + yMove);
snake.add(0, newHead);
snake.remove(snake.size()-1);
}
void drawApple() {
fill(#ff0000);
rect(appleX, appleY, 40, 40, 24);
}