void setup(){
  size(400,75);
 addBuildings(); 
}

void mouseMoved(){
// frameRate(map(mouseX,0,width,5,200));
 
}
void draw(){

  background(0);
  Building toKill = null;
  float right = -9999;
  for(Building b : buildings){
     b.draw(); 
     b.moveLeft();
     if(b.x + BRICKSIZE > right){
        right = b.x + BRICKSIZE; 
     }
     if(b.x < -BRICKSIZE){
       toKill = b;
     }
  }
  if(toKill != null) buildings.remove(toKill);
  if(right < width){
     addBuilding(right); 
  }
}

void mousePressed(){
   for(Building b : buildings){
      b.hurt();
   } 
}
void mouseReleased(){
   for(Building b : buildings){
      b.fix();
   } 
}



float CITY_BOTTOM=75;


int BRICKSIZE=12;

float CHANCEOFBASE=50;

float CHANCEOFMID=50;

float CHANCEOFROOF=50;

int COUNTBASE=4;

int COUNTMID=3;

int COUNTROOF=6;


class Brick{
    
  PImage img;
  String fileRoot = "bricks/";
  float x,y;

  String lit = "";

  PImage fixed;
  PImage hurted;

  
  Brick(float px, float py, String pName, int pRange){
    x = px; y = py;
    fileRoot += pName + ceil(random(pRange));

    if((!pName.equals("Roof")) && random(100) < 75){
       lit = "Lit"; 
    }
    fixed = loadImage(fileRoot+lit+".png");
        hurted = loadImage(fileRoot+"Destroyed.png");

    if(mousePressed){
     hurt(); 
    } else {
    fix();
    }
     
  }
  
  void fix(){  
   img = fixed;  
  }
  void hurt(){
    img = hurted;
  }
 
  void draw(){
    image(img,x,y);
  }
  
 
 
  
}

  
 ArrayList<Building>buildings = new ArrayList<Building>();
 class Building{
   ArrayList<Brick>bricks= new ArrayList<Brick>();
     Building(){
       
     }
  float x;
      void moveLeft(){
           for(Brick b : bricks){
         b.x--;
         x = b.x;
        }
      }
     void add(Brick b){
         bricks.add(b);
     }
     void draw(){
        for(Brick b : bricks){
         b.draw();
        }   
     }
     void hurt(){
        for(Brick b : bricks){
         b.hurt();
        }   
     }
     void fix(){
        for(Brick b : bricks){
         b.fix();
        }   
     }
     
 
 }




void addBuildings(){
  
    float x = 0;
    while(x < width){
    addBuilding(x);
    x += BRICKSIZE ;
    }    
  
}


void addBuilding(float x){
  Brick b;
      Building bld = new Building();
      buildings.add(bld);
      boolean hadBaseOrMid = false;
      float y = CITY_BOTTOM-BRICKSIZE;

      if(random(100) < CHANCEOFBASE){
       b = new Brick(x,y,"Base",COUNTBASE);
        bld.add(b);
        y-=BRICKSIZE;
        hadBaseOrMid = true;
      }
      if(random(100) < CHANCEOFMID){
        b = new Brick(x,y,"Mid",COUNTMID);
        bld.add(b);
        y-=BRICKSIZE;
        hadBaseOrMid = true;
      }
      if(random(100) < CHANCEOFMID){
      b = new Brick(x,y,"Mid",COUNTMID);
        bld.add(b);
        y-=BRICKSIZE;
        hadBaseOrMid = true;
      }
    if(hadBaseOrMid){
      if(random(100) < CHANCEOFROOF){
b = new Brick(x,y,"Roof",COUNTROOF);
        bld.add(b);
      }
    }
       


}