I’m using Processing 3 to code and I'm pretty new but know some basics, so I wanted to make the game Snake. I’ve been able to make the square move in a grid and eat food then spawn new food, but adding a new square is giving me trouble. In the Snake class and void update() I’m trying to create a vector for the new part of the snake by increasing total by 1 in boolean eat() then having inside the update an array that adds 1 to the length. Right now I have the total set as 0 so I get the ArrayIndex… error but if I change total to 1 to fix that I get NullPointerException when trying to draw the new rectangle in the void show() function.
PVector food;
float scl=20;
Snake s;
void setup()
{
size(800,800);
background(255);
s= new Snake();
frameRate(10);
pickLocation();
}
void draw()
{
background(200);
s.update();
s.show();
if(s.eat(food))
{
pickLocation();
}
fill(255,0,0);
rect(food.x,food.y,scl,scl);
}
void pickLocation()
{
float cols=floor(width/scl);
float rows=floor(height/scl);
food= new PVector(floor(random(cols)),floor(random(rows)));
food.mult(scl);
}
class Snake
{
float x=0;
float y=0;
float xspeed=1;
float yspeed=0;
float total=1;
PVector[] tail= new PVector[6400];
void dir(float x, float y)
{
xspeed=x;
yspeed=y;
}
boolean eat(PVector pos)
{
float d=dist(x,y,pos.x,pos.y);
if(d<1)
{
total++;
return true;
}
else return false;
}
void update()
{
if(total==tail.length)
{
for(int i=(int)total; i<tail.length-1; i++)
{
tail[i]=tail[i+1];
}
}
tail[(int)total-1]= new PVector(x,y);
x=x + xspeed*scl;
y=y + yspeed*scl;
x=constrain(x,0,width-scl);
y=constrain(y,0,height-scl);
}
void show()
{
fill(0);
for(int i=0; i<tail.length; i++)
{
rect(tail[i].x,tail[i].y,scl,scl);
}
stroke(255);
fill(0);
rect(x,y,20,20);
}
}
void keyPressed()
{
if(keyCode==UP)
{
s.dir(0,-1);
}
else if(keyCode==DOWN)
{
s.dir(0,1);
}
else if(keyCode==RIGHT)
{
s.dir(1,0);
}
else if(keyCode==LEFT)
{
s.dir(-1,0);
}
}
What I have tried:
I’ve tried using 2 floats instead of the Pvector and get no errors but then the new tail block doesnt stay connected with the snake. I know my code is probably messy and bad but I’ve been trying to find a fix and I can’t so I hope someone can help. If you need me to explain something else in the code that wasn’t already mentioned just ask. I've also tried changing the < in the for loop in void show() to > which gets rid of the errors but doesn't add the new snake tail block onto the snake.