Pàgines

Mar 5, 2011

Us de punters en Processing

En el següent exemple simulo l'us de punters en processing.
Per fer-ho he declarat la clse Boolean.
A més a més el codi també és un exemple del us del threading en Processing.

//http://wiki.processing.org/w/Threading




Boolean pinta = new Boolean(false);


void setup() {
  setValueAfterMs(pinta, true, 2000);
  setValueAfterMs(pinta, false, 3000);
  setValueAfterMs(pinta, true, 4000);
  setValueAfterMs(pinta, false, 5000);
  setValueAfterMs(pinta, true, 6000);
  setValueAfterMs(pinta, false, 7000);
}


void draw() {
  print(pinta.valor);
}


ArrayList StacksetValueAfterMsClass = new ArrayList();
int usedArrayListElements = 0;

void setValueAfterMs(Boolean lVarDest, boolean lValor, int lWait){
  int index = StacksetValueAfterMsClass.size();

  StacksetValueAfterMsClass.add(new setValueAfterMsClass(lVarDest, lValor, lWait));
  ((setValueAfterMsClass)StacksetValueAfterMsClass.get(index)).start();
}


class Boolean{
  boolean valor;

  Boolean(boolean lValor){
    valor = lValor;
  }
}


class setValueAfterMsClass extends Thread {
  boolean running; // Is the thread running? Yes or no?
  int wait; // How many milliseconds should we wait in between executions?
  Boolean varDest;
  boolean valor;

  // Constructor, create the thread // It is not running by default
  setValueAfterMsClass (Boolean lVarDest, boolean lValor, int lWait) {
    usedArrayListElements++;
    varDest = lVarDest;
    valor = lValor;
    wait = lWait;
    running = false;
  }

  void start () { // Overriding "start()"
    if(!running){
      running = true; // Set running equal to true
      super.start();
    }
  }

  void run () { // We must implement run, this gets triggered by start()
    while (running) {
      try {
        sleep((long)(wait));
        varDest.valor = valor;
        quit();
      } catch (Exception e) {
      }
    }
  }

  void quit() { // Our method that quits the thread

    running = false; // Setting running to false ends the loop in run()
    interrupt(); // IUn case the thread is waiting. . .
    usedArrayListElements--;
    if(usedArrayListElements == 0){ // Destrueix l'ArrayList
      for(int j = StacksetValueAfterMsClass.size()-1 ; j >= 0 ; j--){
        StacksetValueAfterMsClass.remove(j);
      }
    }
  }
}// end class