int rows = 30; float sq; vector food; snake p1,p2; int gameSpeed = 10; int foodValue = 5; void setup() { size(500,500); background(0); fill(255); noStroke(); frameRate(gameSpeed); food = new vector(int(random(0,rows)),int(random(0,rows))); sq = width/float(rows); p1 = new snake(new vector(0,0),color(0,0,255)); p2 = new snake(new vector(rows-1,0),color(0,255,0)); } void draw() { for(int x = 0; x < rows; x++) { for(int y = 0; y < rows; y++) { fill(100); rect(sq*x,sq*y,sq,sq); fill(50); rect(sq*x+1,sq*y+1,sq-2,sq-2); fill(255); } } p1.update(p2); p2.update(p1); fill(255,0,0); rect(food.x*sq,food.y*sq,sq,sq); fill(255); } void keyPressed() { if(key == CODED) { switch(keyCode) { case UP: p2.dir = 3; break; case RIGHT: p2.dir = 0; break; case DOWN: p2.dir = 1; break; case LEFT: p2.dir = 2; break; } } else { switch(key) { case 'w': p1.dir = 3; break; case 'd': p1.dir = 0; break; case 's': p1.dir = 1; break; case 'a': p1.dir = 2; break; } } } class snake { vector[] trail; int dir; color col; snake(vector v,color c) { trail = new vector[1]; trail[0] = v; dir = 1; col = c; } void update(snake s) { vector n = new vector(trail[0].x,trail[0].y); switch(dir) { case 0: n.x = trail[0].x+1; n.y = trail[0].y; break; case 1: n.x = trail[0].x; n.y = trail[0].y+1; break; case 2: n.x = trail[0].x-1; n.y = trail[0].y; break; case 3: n.x = trail[0].x; n.y = trail[0].y-1; break; } slide(n,s); fill(col); for(int i = 0; i < trail.length; i++) { rect(trail[i].x*sq,trail[i].y*sq,sq,sq); } fill(255); } void eatTile() { food.x = int(random(0,rows)); food.y = int(random(0,rows)); vector[] tmp = new vector[trail.length+1]; for(int i = 0; i < trail.length; i++) { tmp[i] = trail[i]; } tmp[trail.length] = trail[trail.length-1]; trail = tmp; } void slide(vector v,snake s) { if(v.x >= rows || v.x < 0 || v.y >= rows || v.y < 0) { lose(); return; } for(int i = 0; i < trail.length; i++) { if(v.x == trail[i].x && v.y == trail[i].y) { lose(); return; } } for(int i = 0; i < s.trail.length; i++) { if(v.x == s.trail[i].x && v.y == s.trail[i].y) { lose(); return; } } if(v.x == food.x && v.y == food.y) { for(int i = 0; i < foodValue; i++) eatTile(); } for(int i = trail.length-1; i > 0; i--) { trail[i] = trail[i-1]; } trail[0] = v; } void lose() { } } class vector { public int x,y; vector(int _x,int _y) { x = _x; y = _y; } }