Executing the Rules

The rules are located in the GrowthBehavior class, a subclass of Behavior. The GrowthBehavior object created by WrapTrees3D maintains an ArrayList of TreeLimb objects and an ImageComponent2D array of leaf pictures. The pictures are passed to it at construction time, while storing the first five TreeLimb objects via calls to addLimb():

    // globals
    private final static int TIME_DELAY = 100;  //ms

    private WakeupCondition timeOut;
    private ArrayList treeLimbs;           // of TreeLimb objects
    private ImageComponent2D[] leafIms;    // a sequence of leaf images



    public GrowthBehavior(ImageComponent2D[] lfIms)
    { timeOut = new WakeupOnElapsedTime(TIME_DELAY);
      treeLimbs = new ArrayList();
      leafIms = lfIms;
    }

    public void addLimb(TreeLimb limb)
    {  treeLimbs.add(limb);  }

processStimulus() is called every TIME_DELAY milliseconds (100 ms), which calls applyRulesToLimbs(). applyRulesToLimbs() cycles through the TreeLimb objects in the ArrayList, calling applyRules() for each one:

    private void applyRulesToLimbs()
    {
      TreeLimb limb;
      for(int i=0; i < treeLimbs.size(); i++) {
        limb = (TreeLimb) treeLimbs.get(i);
        applyRules(limb);
        limb.incrAge();   // a limb gets older after each iteration
      }
    }

Seven rules controlling the modification of a tree limb are placed in applyRules():

    private void applyRules(TreeLimb limb)
    // Apply rules to the tree limb.
    {
      // get longer
      if ((limb.getLength() < 1.0f) && !limb.hasLeaves())
        limb.scaleLength(1.1f);

      // get thicker if ((limb.getRadius() <= (-0.05f*limb.getLevel()+0.25f)) ...

Get Killer Game Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.