FileDocCategorySizeDatePackage
SmallBall.javaAPI DocJ2ME MIDP 2.03952Thu Nov 07 12:02:20 GMT 2002example.audiodemo

SmallBall

public class SmallBall extends Object implements Runnable
A SmallBall is a lightweight animated ball that runs in it's own thread. It moves within a rectangular region, bouncing off the walls.

Fields Summary
static Random
random
static int
delay
static int[]
matrix
int
top
int
left
int
width
int
height
int
posX
int
posY
int
radius
int
ballSize
int
deltaX
int
deltaY
Graphics
g
Canvas
canvas
int
note
int
clr
public boolean
stop
Constructors Summary
SmallBall(Canvas c, int left, int top, int width, int height)
Constructor defines the region in which the ball moves as well as its starting position.

    
                        
              
	super();
	canvas = c;
	
	this.left = left + 1;		
	this.top  = top + 1;		
	this.width = width - (2 * radius + 2);
	this.height = height - (2 * radius + 2);

	// use positive random #s
	this.posX = (random.nextInt()>>>1) % (this.width-20) + 10;
	this.posY = (random.nextInt()>>>1) % (this.height-20) + 10;
	
	deltaX = random.nextInt() & 1;
	deltaY = random.nextInt() & 1;
	
	if (deltaX == 0) deltaX = -1;
	if (deltaY == 0) deltaY = -1;
    
Methods Summary
static voidfaster()

	delay -= 10;
	if (delay < 10) delay = 10;
    
voidpaint(Graphics g)
Paint the ball.

	g.setColor(clr);
	g.fillArc(posX,posY,ballSize,ballSize,0,360);
    
public voidrun()
Starts the ball running.

	//	    System.out.println("starting... " + this);
	int right = left + width;
	int bottom = top + height;
	
	stop = false;
	while (!stop) {
	    
	    ballSize = radius * 2;
	    
	    // calculate a direction of the ball as an integer in the range
	    // -2 .. 2 (excluding 0)
	    int direction = deltaX + deltaY;
	    if (direction == 0) direction = deltaX + 2*deltaY;
	    
	    // is the current position colliding with any wall
	    int collision = 0;
	    if (posX <= left || posX >= right) collision++;
	    if (posY <= top || posY >= bottom) collision += 2;
	    
	    // change the direction appropriately if there was a collision
	    if (collision != 0) {
		try {
		    javax.microedition.media.Manager.playTone(note, 100/*ms*/,100);
		} catch (Exception ex) {
		    System.out.println("failed to play tone");
		}

		collision = (collision - 1) * 2;
		
		deltaX = matrix[direction+2][collision];
		deltaY = matrix[direction+2][collision+1];
	    }
	    
	    // calculate the new position and queue a repaint
	    posX = posX + deltaX;
	    posY = posY + deltaY;
	    canvas.repaint();
	    
	    // use the delay to control the speed of the ball
	    try {
		Thread.sleep(delay);
	    } catch (InterruptedException e) {}
	}
    
public voidsetColor(int clr)

	this.clr = clr;
    
public voidsetNote(int note)

	this.note = note;
    
static voidslower()

       
	delay += 10;
	if (delay > 100) delay = 100;
    
public java.lang.StringtoString()

	return super.toString() + " x = " + posX + ", y = " + posY;