code:
import java.awt.*;
class Ant extends Frame {
private int[][] theMap;
private int mapEdge;
// 0 is north, 1 is east, 2 is south, 3 is west.
private int antDirection;
// Current position.
private int antXpos;
private int antYpos;
// Direction-change table. -1 indicates left, 1 indicates right.
private static final int[] dirChange = {-1, 1};
public static void main (String[] args) {
Ant n = new Ant();
}
public Ant() {
// Setup graphics logistics
super();
setUndecorated(true);
mapEdge = 700;
setSize(mapEdge, mapEdge);
setResizable(false);
// Initialise ant
antXpos = 50;
antYpos = 50;
antDirection = 0;
theMap = new int[mapEdge][mapEdge];
show();
// Main decision loop, run until ant goes off the edge
while ((antXpos >= 0) && (antXpos < mapEdge) &&
(antYpos >= 0) && (antYpos < mapEdge)) {
// Change directions
antDirection += dirChange[theMap[antXpos][antYpos]];
if (antDirection > 3) antDirection = 0;
else if (antDirection < 0) antDirection = 3;
// Change colour and show new grid
theMap[antXpos][antYpos]++;
if (theMap[antXpos][antYpos] >= dirChange.length) theMap[antXpos][antYpos] = 0;
paint(getGraphics());
switch (antDirection) {
case 0 : antYpos--; // North
break;
case 1 : antXpos++; // East
break;
case 2 : antYpos++; //South
break;
case 3 : antXpos--; // West
break;
// Default should never happen, treat it as north.
default :
antYpos--;
antDirection = 0;
break;
}
try {
Thread.sleep(25);
}
catch (InterruptedException e) {}
}
System.exit(0);
}
public void paint(Graphics g) {
switch (theMap[antXpos][antYpos]) {
case 0 :
g.setColor(Color.white);
break;
case 1 :
g.setColor(Color.black);
break;
default :
g.setColor(Color.green);
break;
}
g.fillRect(2*antXpos, 2*antYpos, 2, 2);
}
}