
import	javax.microedition.lcdui.*;
import	java.util.*;

public class MoveObj
{
	final static int vmax = 4;

	int	x;
	int	y;
	int	vx;
	int	vy;
	Polygon	polygon;

	MoveObj	next;

	static Random	random = new Random();

	MoveObj( Polygon p, int width, int height )
	{
		polygon = p;

		x = ( random.nextInt() >>> 1 ) % width;
		y = ( random.nextInt() >>> 1 ) % height;
		vx = random.nextInt() % vmax;
		vy = random.nextInt() % vmax;
	}

	public void add( MoveObj o )
	{
		if( next == null )
		{
			next = o;
		}
		else
		{
			next.add( o );
		}
	}

	public void move( int width, int height )
	{
		while( x + vx < 0 || x + vx >= width ||
				y + vy < 0 || y + vy >= height || ( vx == 0 && vy == 0 ) )
		{
			vx = random.nextInt() % vmax;
			vy = random.nextInt() % vmax;
		}

		x += vx;
		y += vy;

		if( next != null )
		{
			next.move( width, height );
		}
	}

	public void draw( Graphics g )
	{
		if( polygon != null )
		{
			polygon.draw( g, x, y );
		}

		if( next != null )
		{
			next.draw( g );
		}
	}
}

