int x = 0; int y = 0; int t = 0; int[] xBodies = {1,2}; int[] yBodies = {0,0}; int up = -1; int right = 0; int toSetRight = 0; int toSetUp = -1; boolean LOST = false; int foodX = 0; int foodY = 0; void setup(){ size(600,600); foodX = int(random(0,40)); foodY = int(random(0,40)); } void draw(){ if(LOST){ fill(255,0,0); rect(0,0,width,height); fill(0); textSize(50); } else{ fill(255,255,255); rect(0,0,width,height); t++; if(t == 10){ t = 0; up = toSetUp; right = toSetRight; for(int i = xBodies.length-1; i > -1; i--){ if(i > 0){ xBodies[i] = xBodies[i-1]; yBodies[i] = yBodies[i-1]; }else{ xBodies[i] = x; yBodies[i] = y; } rect( xBodies[i]*15,yBodies[i] *15,15,15); } if(right == -1){ x--; } if(right == 1){ x++; } if(up == 1){ y--; } if(up == -1){ y++; } testForCollision(); } if(foodX == x && foodY == y){ foodX = int(random(0,40)); foodY = int(random(0,40)); addBody(); } fill(0,0,255); rect(foodX*15,foodY*15,15,15); fill(255,0,0); rect(x*15,y*15,15,15); fill(255,255,0); for(int i = 0; i < xBodies.length; i++){ int cx = xBodies[i]; int cy = yBodies[i]; rect(cx*15,cy*15,15,15); }}} void testForCollision(){ for(int i = 0; i < xBodies.length; i++){ int cx = xBodies[i]; int cy = yBodies[i]; if(x == cx && y == cy){ LOST = true; }} if(x*15 < 0 || y*15 < 0 || x*15 >= width || y*15 >= height){ LOST = true; }} void addBody(){ xBodies = append(xBodies,xBodies[xBodies.length-1]); yBodies = append(yBodies,yBodies[yBodies.length-1]); } void keyPressed() { if (key == CODED) { if (keyCode == UP && toSetUp == 0) { toSetUp = 1; toSetRight = 0; } else if (keyCode == DOWN && toSetUp == 0) { toSetUp = -1; toSetRight = 0; } else if (keyCode == RIGHT && toSetRight == 0) { toSetRight = 1; toSetUp = 0; } else if (keyCode == LEFT && toSetRight == 0) { toSetRight = -1; toSetUp = 0; } else if (keyCode == LEFT && toSetRight == 0) { toSetRight = -1; toSetUp = 0; } } }