⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 garden.java

📁 Java source code for the Ant Colony Optimization Problem.
💻 JAVA
字号:
package jwo.jpss.ants;     // Part of the ant simulation package.
import java.awt.*;		   // For drawing the garden.
import jwo.jpss.spatial.*; // For spatial footprint.
import java.util.*;        // For dynamic collections.

//  *******************************************************
/** Class for defining a garden containing an ants' nest.
  * @author Jo Wood
  * @version 1.3, 18th September, 2001.
  */
//  *******************************************************

public class Garden extends SpatialObject implements Dynamic,Drawable
{
    // ------------------ Object variables -------------------
    
    private Vector nests, newNests;     // A collection of ant nests.
    private Vector foodSources;         // A collection of food sources.
    private Rectangle bounds;           // Drawable dimensions.
    private boolean evolving;           // Controls the movement of time.
    private int time;                   // Keeps track of time.
    private GraphicsListener gListener;	// Allows graphics to be updated.
        
    // -------------------- Constructor ---------------------
    
    /** Creates a garden with an ants' nest and given spatial footprint.
      * @param footprint Spatial footprint of garden.
      */
    public Garden(Footprint footprint)
    {
        super(footprint);

        // Store garden footprint.
        Footprint fp = getBounds();
        bounds = new Rectangle((int)fp.getXOrigin(),  (int)fp.getYOrigin(),
                               (int)fp.getMERWidth(), (int)fp.getMERHeight());

        // Add 2 ants' nests to the garden.
    	nests = new Vector(2);
        newNests = new Vector();	
        float nestY = (fp.getMERHeight()/2)-10;
        float nestX = (fp.getMERWidth()/3);

        nests.addElement(new Nest(nestX-10,nestY));
        nests.addElement(new Nest(2*nestX-10,nestY));

        // Add food sources to garden.
        foodSources = new Vector(40);
        for (int i=0; i<40; i++)
        {
            int x = (int)((bounds.width-30)*Math.random());
            int y = (int)((bounds.height-30)*Math.random());
            foodSources.addElement(new FoodSource(x,y,10000));
    	}
    }  
    
    // ----------------------- Methods -----------------------

    /** Starts off time sequence in the garden, allowing ants to evolve.
      */
    public void startEvolution()
    {
        evolving = true;
        long startTime = System.currentTimeMillis()-1;
     
        while(evolving)
        {
            evolve();
            time++;
            if (time%100 == 0)
    	    {
    	    	int cps = (int)(1000000/(System.currentTimeMillis()-startTime));
    	    	String message = new String(" Ants in the Garden, "+time+ " cycles elapsed at ");
    	    	if (cps > 10)
    	    	    message = message+(cps/10f)+" cycles per second.";
    	    	else
    	    	    message = message+(10f/cps)+" seconds per cycle.";
    	    	
    	        gListener.displayMessage(message);
    	        
    	        // Reset realtime timer.
    	        startTime = System.currentTimeMillis()-1;
            }
        }
    }

    /** Stops the passage of time in the garden.
      */
    public void stopEvolution()
    {
        evolving = false;
    }

    /** Reports the list of SpatialObjects associated with the given
      * spatial object (within, matching, overlapping or containing). 
      * @param spObject Spatial object with which to compare.
      * @return List of spatial objects in contact with the given one.
      */
    public Vector objectsAt(SpatialObject spObject)
    {
        Vector spatialObjects = new Vector();

        // If garden is separate from footprint, there can be no other
        // objects at this footprint.
        if (compare(spObject) == SEPARATE)
    	    return spatialObjects;
    	        	
        // Add any nest items that are connected to footprint.
        Enumeration enum = nests.elements();
        while (enum.hasMoreElements())
        {
            Nest nest = (Nest)enum.nextElement();
            if (nest.compare(spObject) != SEPARATE)
                spatialObjects.addElement(nest);
        }
    	
    	// Add any food sources that are connected to footprint.
    	enum = foodSources.elements();
    	while (enum.hasMoreElements())
    	{
            FoodSource foodSource = (FoodSource)enum.nextElement();
    
            if (foodSource.compare(spObject) != SEPARATE)
                spatialObjects.addElement(foodSource);
        }

        // Add this garden to the end of the list
        spatialObjects.addElement(this);
    
        return spatialObjects;
    }

    /** Adds the given nest to the garden.
      * @param nest Nest to add to garden.
      */
    public void requestNewNest(Nest nest)
    {
        if (gListener != null)
            nest.addGraphicsListener(gListener);
        
        newNests.addElement(nest);
    }

    // ----------------- Implemented methods -----------------

    /** Let the garden grow for one time unit.
      */
    public void evolve()
    {   
        // Remove any food sources that have run out of food.
        Enumeration enum = foodSources.elements();
        while (enum.hasMoreElements())
        {
            FoodSource food = (FoodSource)enum.nextElement();

            if (food.getFoodLevel() == 0)
                foodSources.removeElement(food);
        }

        // Possibly add a food source at random location.	
        if (Math.random() < 0.02)
        {
            int x = (int)((bounds.width-30)*Math.random());
            int y = (int)((bounds.height-30)*Math.random());

            foodSources.addElement(new FoodSource(x,y,10000));
      	    gListener.redrawGraphics();
    	}
		
        // Let the ants' nest evolve.
        enum = nests.elements();
        while (enum.hasMoreElements())
    	{
    	    Nest nest = (Nest)enum.nextElement();
    	    nest.evolve();
    	}

        // Check to see if any new nests have been requested.
        if (newNests.size() > 0)
        {
            enum = newNests.elements();
            while (enum.hasMoreElements())
                nests.addElement(enum.nextElement());
            newNests = new Vector();
        }
    }

    /** Adds a graphics listener to this object. Passes on the listener
      * to any ants' nests within the garden.
      * @param gListener Component doing the drawing.
      */
    public void addGraphicsListener(GraphicsListener gListener)
    { 
        this.gListener = gListener;
        
        // Also add a graphics listener to each nest.
        Enumeration enum = nests.elements();
    	while (enum.hasMoreElements())
    	{
    	    Nest nest = (Nest)enum.nextElement();
    	    nest.addGraphicsListener(gListener);
    	}
    }

    /** Draws the garden and all contained within it using the 
      * given graphics context.
      * @param g Graphics context to draw to.
      */
    public void paint(Graphics g)
    {    	
        // Draw garden.
        g.setColor(new Color(200,220,200));
        g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
            	
        // Draw nests.
        Enumeration enum = nests.elements();
        while (enum.hasMoreElements())
        {
            Nest nest = (Nest)enum.nextElement();
            nest.paint(g);
        }
    	
    	// Draw food sources.
    	enum = foodSources.elements();
        while (enum.hasMoreElements())
        {
            FoodSource foodSource = (FoodSource)enum.nextElement();
            foodSource.paint(g);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -