Am a beggner & struggling to Code. Just created account to ask a qustion
I AM STUCK!!!
i think the problem is in the move() function in snake class
the snake acts weird when i eat the food
/////CODE//////
/////main.program/////(the class the contains setup & draw)
Snake snake = new Snake();
PVector food;
float w = 400/20;
float h = w;
void setup(){
size(400, 400);
foodLoc();
}
void draw(){
scale (20);
background(220);
fill(255, 0, 0);
rect(food.x, food.y, 1, 1);
snake.show();
snake.move();
if (snake.eat(food)) {
foodLoc();
snake.grow();
}
}
void keyPressed(){
if (keyCode == RIGHT) snake.set(1, 0);
else if (keyCode == UP) snake.set(0, -1);
else if (keyCode == DOWN) snake.set(0, 1);
else if (keyCode == LEFT) snake.set(-1, 0);
}
void foodLoc(){
int x = floor( random(w) );
int y = floor( random(h) );
food = new PVector(x, y);
}
////Snake.class//////
class Snake{
PVector body[] = new PVector[1];
float xd;
float yd;
Snake(){
for (int i = 0 ; i < body.length ; i++) body[i] = new PVector(0, 0);
}
void show(){
noStroke();
fill(0);
for(int i = 0 ; i < body.length ; i++){
rect(body[i].x, body[i].y, 1, 1);
}
}
void grow(){
body =(PVector[]) append(body, new PVector (0, 0));
}
void set(float x, float y){
xd = x;
yd = y;
}
boolean eat(PVector f){
return ( body[0].equals(f) );
}
void move(){
println(body.length);
if(frameCount % 12 == 0){
PVector head = body[body.length-1].copy();
shift(body);
head.x += xd;
head.y += yd;
body = (PVector[]) append(body, head);
}
println(body.length);
}
void shift(PVector[] b){
PVector[] temp = new PVector[b.length-1];
arrayCopy(b, 1, temp, 0, b.length-1);
//println(temp);
//println(b);
b = (PVector[]) shorten(b);
arrayCopy(temp, 0, body, 0, temp.length);
body = b;
//println(temp);
//println(body);
}
}