วันจันทร์ที่ 15 กันยายน พ.ศ. 2557

Lab 3 : Task#2 - Graph (with Min & Max & Avg)



Warning >>> A little text position bug on Processing
int n=8;
float w_box;
float[] y=new float[n];

void setup()
{
  size(480,300);
  background(0);
  w_box=width/n;
  for(int i=0;i<n;i++)
  {y[i]=0;}
}

void draw()
{
  background(0);
  draw_graph();
  draw_max();
  draw_min();
  draw_avg();
  draw_grid();
}

void mousePressed()
{
  for(int i=0;i<n;i++)
  {
    if(mouseX>i*w_box&&mouseX<(i+1)*w_box)
    {
      y[i]=height-mouseY;
    }
  }
}

void mouseDragged()
{
  for(int i=0;i<n;i++)
  {
    if(mouseX>i*w_box&&mouseX<(i+1)*w_box)
    {
      y[i]=height-mouseY;
    }
  }
}

void draw_graph()
{
  stroke(0,255,0);
  textAlign(CENTER);
  for(int i=0;i<n;i++)
  {
    fill(0,255,0,50);
    rect(i*w_box,height,w_box,-y[i]);
    fill(0,255,0,255);
    text(round(y[i]/3),(i*w_box)+(w_box/2),height-5);
  }
}

void draw_max()
{
  float $max;
  $max=max(y);
  line(0,height-$max,width,height-$max);
  textAlign(RIGHT);
  text("max = "+round($max/3),width-2,height-$max+13);
}

void draw_min()
{
  float $min;
  $min=min(y);
  line(0,height-$min,width,height-$min);
  textAlign(RIGHT);
  text("min = "+round($min/3),width-2,height-$min+13);
}

void draw_avg()
{
  float sum=0,avg;
  for(int i=0;i<n;i++)
  {
    sum=sum+y[i];
  }
  avg=(sum/n);
  line(0,height-avg,width,height-avg);
  textAlign(RIGHT);
  text("avg = "+round(avg/3),width-2,height-avg+13);
}

void draw_grid()
{
  stroke(0,255,0,80);
  for(int i=height;i>=0;i=i-10)
  {
    line(0,i,width,i);
  }
  for(float i=width;i>=0;i=i-w_box)
  {
    line(i,0,i,height);
  }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น