void keyPressed(){
  worms = new ArrayList<Worm>();
}
ArrayList<Worm>worms = new ArrayList<Worm>();
Worm worm;

void setup(){
  smooth();
  strokeWeight(5);
   size(500,500); 
}
void draw(){
  background(0);
  if(mousePressed){
     if(worm == null){
        worm = new Worm();
     } else {
        worm.addPoint();
     } 
  } else {
     if(worm != null){
        worms.add(worm);
        worm = null;
     } 
  }
  for(Worm w: worms){
       w.draw(); 
    }
  
if(worm != null){  worm.draw();}

}



class Worm{
   ArrayList<Point>points = new ArrayList<Point>(); 
   float startx, starty;
   float lastx, lasty;
   int ptr;
   color c;
   Worm(){
     c = color(random(128,250),random(128,250),random(128,250));
     startx = mouseX;
     starty = mouseY;
     lastx = startx;
     lasty = starty;
     
   }
   
   
   void addPoint(){
      points.add(new Point(mouseX-lastx,mouseY-lasty)); 
      lastx = mouseX; lasty = mouseY;
   }
   void draw(){
     stroke(c);
     float oldx = startx;
     float oldy = starty;
    for(Point p : points){
       line(oldx,oldy,oldx + p.x,oldy + p.y);
       oldx += p.x;
       oldy += p.y;
    } 
    
    if(this != worm){
      if(oldx >= 0 && oldx <= 500 && oldy >= 0 && oldy <= 500){
      Point p = points.get(ptr);
      points.add(p);
      ptr++;
    }
    }
    
   }
   
  
}



class Point{
  float x,y;
  Point(float px, float py){
     x = px; y = py; 
  }
}