FileDocCategorySizeDatePackage
Sprite.javaAPI DocExample2902Fri Mar 30 17:55:40 BST 2001None

Sprite

public class Sprite extends Component implements Runnable
A Sprite is one Image that moves around the screen on its own

Fields Summary
protected static int
spriteNumber
protected Thread
t
protected int
x
protected int
y
protected Component
parent
protected Image
img
protected boolean
done
protected int
sleepTime
The time in mSec to pause between each move.
protected int
direction
The direction for this particular sprite.
public static final int
HORIZONTAL
The direction for going across the page
public static final int
VERTICAL
The direction for going up and down
public static final int
DIAGONAL
The direction for moving diagonally
Constructors Summary
public Sprite(Component parent, Image img, int dir)
Construct a Sprite with a Component parent, image and direction. Construct and start a Thread to drive this Sprite.


	                   	 
	       
		super();
		this.parent = parent;
		this.img = img;
		switch(dir) {
			case VERTICAL: case HORIZONTAL: case DIAGONAL:
				direction = dir;
				break;
			default:
				throw new IllegalArgumentException(
					"Direction " + dir + " invalid");
		}
		setSize(img.getWidth(this), img.getHeight(this));
	
public Sprite(Component parent, Image img)
Construct a sprite with the default direction

		this(parent, img, DIAGONAL);
	
Methods Summary
public voidpaint(java.awt.Graphics g)
paint -- just draw our image at its current location

		g.drawImage(img, 0, 0, this);
    
public voidrun()
Run one Sprite around the screen. This version just moves them around either across, down, or at some 45-degree angle.

		int width = parent.getSize().width;
		int height = parent.getSize().height;
		// Set initial location
		x = (int)(Math.random() * width);
		y = (int)(Math.random() * height);
		// Flip coin for x & y directions
		int xincr = Math.random()>0.5?1:-1;
		int yincr = Math.random()>0.5?1:-1;
		while (!done) {
			width = parent.getSize().width;
			height = parent.getSize().height;
			if ((x+=xincr) >= width)
				x=0;
			if ((y+=yincr) >= height)
				y=0;
			if (x<0)
				x = width;
			if (y<0)
				y = height;
			switch(direction) {
				case VERTICAL: 
					x = 0;
					break;
				case HORIZONTAL: 
					y = 0;
					break;
				case DIAGONAL: break;
			}
			//System.out.println("from " + getLocation() + "->" + x + "," + y);
			setLocation(x, y);
			repaint();
			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				return;
			}
		}
	
protected voidsetSleepTime(int n)
Adjust the motion rate

		sleepTime = n;
	
public voidstart()
Start this Sprite's thread.

		t = new Thread(this);
		t.setName("Sprite #" + ++spriteNumber);
		t.start();
	
public voidstop()
Stop this Sprite's thread.

		if (t == null)
			return;
		System.out.println("Stopping " + t.getName());
		done = true;