import java.util.Random;
import java.applet.*;
import java.awt.*;
/*
<applet code="CockroachWalk" width=600 height=600>
</applet>
*/
public class CockroachWalk extends Applet implements Runnable
{
final int UP = 0, DOWN = 1, LEFT = 2 , RIGHT = 3 , NSTEPS = 5;
final int STEPSIZE = 30;
int maxRows , maxCols ;
int row , col ;
Thread t = null;
Image roach , up , down , left , right;
public void init ()
{
maxRows = getSize().height;
maxCols = getSize().width;
setBackground (Color.white);
row = maxRows / 2;
col = maxCols / 2;
up = getImage (getDocumentBase() , "Roach_Up.jpg");
down = getImage (getDocumentBase() , "Roach_Down.jpg");
left = getImage (getDocumentBase() , "Roach_Left.jpg");
right = getImage (getDocumentBase() , "Roach_Right.jpg");
}
public void start ()
{
if (t == null)
{
t = new Thread (this);
t.start();
}
}
public void run ()
{
try
{
Random r = new Random ();
while (true)
{
int dir = r.nextInt(4); //Choose random direction
loop:
for (int i = 1 ; i <= NSTEPS; i++) //Move cockroach along the direction NSTEPS times
{
switch (dir)
{
case UP:
if (row <= 0)
{
dir = r.nextInt(4);
continue loop;
}
row -= STEPSIZE;
roach = up;
break;
case DOWN:
if (row >= maxRows - STEPSIZE)
{
dir = r.nextInt(4);
continue loop;
}
row += STEPSIZE;
roach = down;
break;
case LEFT:
if (col <= 0)
{
dir = r.nextInt(4);
continue loop;
}
col -= STEPSIZE;
roach = left;
break;
case RIGHT:
if (col >= maxCols - STEPSIZE)
{
dir = r.nextInt(4);
continue loop;
}
col += STEPSIZE;
roach = right;
break;
}
repaint ();
t.sleep (100);
}
}
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted");
}
}
public void paint (Graphics g)
{
//DrawCockroach
g.drawImage (roach , col , row , this );
}
}