Ant Hill
<< Plinko | OtherProjectsTrailIndex | DroppingLetters >>
This applet uses an ArrayList of Ant. The Ant class needs a constructor with two int parameters. These parameters are the x and y locations of the origin of the ant. The Ant also needs a rise and run for its direction and speed. It needs at least a method draw, but you may wish to add some sort of counter or distance algorithm to see if a ant is too old or too far away to draw. Everytime it draws itself, it should move the x@ location by run and the y location by rise@@, and then change the rise and run to is randomly changes direction.
/**
* @return a random int from a to b
*/
public int randomInt(int a, int b)
{
return Math.min(a, b)+(int)(Math.abs(b-a)*Math.random());
}
Make a loop in the paint method to draw all the ants
AntHillApplet.java
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.Timer;
public class AntHillApplet extends Applet implements ActionListener
{
private ArrayList<Ant> ants;
private Timer animateTimer, spawnTimer;
public void init(){
ants = new ArrayList<Ant>();
animateTimer = new Timer(30, this);
spawnTimer = new Timer(45,this);
animateTimer.start();
spawnTimer.start();
}
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0, 0, 600, 400);
int i=0;
//draw every ant in the ants ArrayList
for(Ant a: ants){
a.draw();
a.move();
}
g.setColor(Color.BLACK);
g.drawString(ants.size()+" ants.", 20 , 20);
}
public void update(Graphics g)
{
paint(g); //get rid of flicker with this method
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==animateTimer){
repaint();
} else {//must have been the spawnTimer generating the event
ants.add(new Ant(300,200));
}
}
}
What else?
- set a limit to the number of Ants
- make an method that determines if a ant is off the screen and be removed from
ants - Make @@AntHill@ class that has its own list of ants, and then draw more than one AntHill in this applet.
- Make a star field by not changing the direction of the Ant.
