// Individual termite for Artificial Termites. // // Author Matthew Caryl // Created 29.10.96 // // Although under copywrite to the author (Matthew Caryl) this code can be copied and modified for non-commercial // purposes as long as any derivatives contain this condition. package ArtificialTermites; import java.awt.*; final class Termite { private World containingWorld; int x, y; int facing; // in range 0..7 boolean carryingWood; private static Color termiteColor = Color.red; private static int facingXDelta[] = { 0, 1, 1, 1, 0, -1, -1, -1}; // x-delta for facing private static int facingYDelta[] = {-1, -1, 0, 1, 1, 1, 0, -1}; // y-delta for facing public Termite(World w, int xcoord, int ycoord) { containingWorld = w; x = xcoord; y = ycoord; facing = randomFacing(); carryingWood = false; } public void paint() { containingWorld.paintBlock(x, y, termiteColor); } public void tick() { containingWorld.paintBlock(x, y); // erase screen block if (timeForTurn()) // maybe turn a bit randomTurn(); move(facing); // move forward if (woodAt(facing)) { if (!carryingWood) // if wood in front and not carrying then pick up getWood(facing); else if (!woodAt()) { // if wood in front and carrying and no wood here then putWood(); // put down and about turn turn(4); } } paint(); // paint termite } private int randomFacing() { return containingWorld.random(8); } private boolean timeForTurn() { return containingWorld.random(10) == 0; } private void randomTurn() { turn(containingWorld.random(3) - 1); } private void turn(int delta) { facing = World.mod(facing + delta, 8); } private void move(int direction) { x = World.mod(x + facingXDelta[World.mod(direction, 8)], containingWorld.width()); y = World.mod(y + facingYDelta[World.mod(direction, 8)], containingWorld.height()); } private boolean woodAt(int x, int y) { return containingWorld.woodAt(x, y); } private boolean woodAt() { return woodAt(x, y); } private boolean woodAt(int direction) { return woodAt(x + facingXDelta[World.mod(direction, 8)], y + facingYDelta[World.mod(direction, 8)]); } private void getWood(int x, int y) { containingWorld.getWood(x, y); carryingWood = true; } private void getWood() { getWood(x, y); } private void getWood(int direction) { getWood(x + facingXDelta[World.mod(direction, 8)], y + facingYDelta[World.mod(direction, 8)]); } private void putWood(int x, int y) { containingWorld.putWood(x, y); carryingWood = false; } private void putWood() { putWood(x, y); } private void putWood(int direction) { putWood(x + facingXDelta[World.mod(direction, 8)], y + facingYDelta[World.mod(direction, 8)]); } }