Cat Applet
// this applet produces an animation of a cat
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Color;
public class Cat extends java.applet.Applet
implements Runnable {
Image[] cats;
Image currentImg;
int xpos;
int ypos;
Thread runner;
int grid;
int imWidth;
int imHeight;
public void start() {
if (runner == null) {
runner = new Thread(this);
runner.start();
}
}
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
// get the images for the animation, and set the position for the
// animation and the size of the background grid
public void init()
{
String catnames[] = {"stop.gif", "yawn.gif","scratch1.gif","scratch2.gif",
"sleep1.gif","sleep2.gif","awake.gif"};
cats = new Image[7];
for (int i = 0 ; i < catnames.length ; i++)
cats[i] = getImage(getDocumentBase(),catnames[i]);
xpos = 100;
ypos = 100;
grid = 10;
}
// create the grid and draw the current cat image
public void paint(Graphics g)
{
int width = size().width/grid;
int height = size().height/grid;
boolean black = true;
for (int y = 0 ; y <= grid ; y++)
for (int x = 0 ; x <= grid ; x++)
{
if (black)
{
g.setColor(Color.black);
black = false;
}
else
{
g.setColor(Color.white);
black = true;
}
g.fillRect(x*width,y*height,width,height);
}
g.drawImage(currentImg,xpos,ypos,this);
}
// cycle through the images so that the cat scratches, sleeps, and wakes
public void run()
{
while (true)
{
currentImg = cats[0];
repaint();
pause(1000);
currentImg = cats[1];
repaint();
pause(1000);
scratch(4);
sleep(5);
currentImg = cats[6];
repaint();
pause(500);
}
}
private void pause(int time)
{
try
{
Thread.sleep(time);
}
catch(InterruptedException e) {}
}
// sequence of images for scratching
private void scratch(int times)
{
for (int i = 1 ; i <= times ; i++)
{
currentImg = cats[2];
repaint();
pause(150);
currentImg = cats[3];
repaint();
pause(150);
}
}
// sequence of images for sleeping
private void sleep(int times)
{
for (int i = 1 ; i <= times ; i++)
{
currentImg = cats[4];
repaint();
pause(250);
currentImg = cats[5];
repaint();
pause(250);
}
}
}