xxxxxxxxxx
ArrayList<SnakePart> snake = new ArrayList<SnakePart>();
char direction;
SnakeFood food;
void setup() {
size(400, 400);
snake.add(new SnakePart(0, 0));
frameRate(8);
food = new SnakeFood();
}
void draw() {
smooth();
grid();
drawSnake();
food.display();
moveBody();
moveHead();
checkGameOver();
foodHit();
}
void grid() {
background(#A2FFED);
stroke(255);
for (int x =0; x < width; x+=20) {
line(x, 0, x, height);
}
for (int y =0; y < height; y+=20) {
line(0, y, width, y);
}
}
void drawSnake() {
for (int i = 0; i < snake.size();i++) {
SnakePart sp = snake.get(i);
sp.display();
}
}
void moveHead() {
SnakePart head = snake.get(0);
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;
break;
}
}
void moveBody() {
for (int i = snake.size()-1; i > 0; i--) {
SnakePart spBack = snake.get(i);
SnakePart spFront = snake.get(i-1);
spBack.x = spFront.x;
spBack.y = spFront.y;
}
}
void foodHit() {
SnakePart head = snake.get(0);
if (head.x == food.x && head.y == food.y) {
// add a new segment to the snake
snake.add(new SnakePart(head.x, head.y));
// reset the position of the food by creating a new object
food = new SnakeFood();
}
}
void checkGameOver() {
SnakePart head = snake.get(0);
for (int i = 1; i < snake.size(); i++) {
SnakePart sp = snake.get(i);
if (head.x == sp.x && head.y == sp.y) {
textAlign(CENTER);
text("GAME OVER!", width/2, height/2);
noLoop();
break;
}
}
if (head.x < 0 || head.x >= width || head.y < 0 || head.y >= height) {
textAlign(CENTER);
text("GAME OVER!", width/2, height/2);
noLoop();
}
}
void keyPressed() {
SnakePart head = snake.get(0);
if (key == 'a' || key == 'A')direction = 'w';
if (key == 'd' || key == 'D')direction = 'e';
if (key == 'w' || key == 'W')direction = 'n';
if (key == 's' || key == 'S')direction = 's';
}
class SnakeFood {
int x, y;
SnakeFood() {
x = int(random(width/20))*20;
y = int(random(height/20))*20;
}
void display() {
fill(255, 100, 100);
noStroke();
rect(x, y, 19, 19);
}
}
class SnakePart {
int x, y;
color c;
float w, h;
SnakePart(int newX, int newY) {
x=newX;
y=newY;
c = color(random(255), random(255), random(255));
w=0;
h=0;
}
void display() {
fill(c);
noStroke();
ellipseMode(CORNER);
ellipse(x, y, 20, 20);
// fill(random(255), random(255), random(255));
// ellipseMode(CENTER);
// ellipse(x+10, y+10, w+10, h+10);
fill(random(255), random(255), random(255));
ellipseMode(CENTER);
ellipse(x+10, y+10, w+5, h+5);
fill(random(255), random(255), random(255));
ellipseMode(CENTER);
ellipse(x+10, y+10, w, h);
w+=2;
h+=2;
if (w>=18||h>=18) {
w=5;
h=5;
w+=2;
h+=2;
}
}
}