ArrayList snake = new ArrayList(); SnakePart head; SnakeFood food; char direction;
void setup() { size(500,500); frameRate(8); snake.add(new SnakePart(0,0)); food = new SnakeFood(); smooth(); }
void draw() { background(100); head = (SnakePart)snake.get(0); moveBody(); moveHead();
chackGameOver(); //check if the snake ate the food if(dist(head.x.head.y,food.x,food.y)<5) { food = new SnakeFood(); snake.add(new SnakePart(head.x, head.y)); }
//Draw everything to the screen food.display(); for(int i = 0; i<snake.size(); i++) { SnakePart sp =(SnakePart)snake.get(i); sp.display(); }
class SnakeFood { int x,y;
SnakeFood()
{
x = int(random(width/20))*20;
y = int(random(height/20))*20;
}
void display()
{
fill(255,100,100);
rect(x,y,20,20);
}
} }
void KeyPressed()//the direction { if(key =='a') direction ='w'; if(key =='d') direction ='e'; if(key =='w') direction = 'n'; if(key =='s') direction ='s'; } void moveHead()//move the head { switch(direction) { case'n': head.y -=20; break;
case's':
head.y +=20;
break;
case'e':
head.x +=20;
break;
case'w':
head.x -=20;
}
void moveBody()
{
for(int i = snake.size()-1; i>0; i--)
{
SnakePart front =(SnakePart)snake.get(i-1);
SnakePart back =(SnakePart)snake.get(i);
back.x = front.x;
back.y = front.y;
}
void checkGameOver()
{
for(int i =1; i<snake.size(); i++)
{
SnakePart sp =(SnakePart)snake.get(i);
if(disk(head.x,head.y,sp.x,sp.y)<5)
{
println("Game Over!");
noLoop();
}
}
if(head.x<0 || head.x>width || head.y<0 || head.y>height)
{
println("Game Over!");
noLoop();
}
}