www.pudn.com > ch8-spaceshooter.rar > UFO.java


/* 
 * UFO.java 
 * 
 * Copyright 2001 SkyArts. All Rights Reserved. 
 */ 
import javax.microedition.lcdui.*; 
 
/** 
 * UFO类 
 * 
 * @author  Hideki Yonekawa 
 * @version 1.0 
 */ 
class UFO extends Sprite { 
	/** 储存自机对象的变量 */ 
	private	MyShip				myShip; 
	/** 储存UFO图像的类变量 */ 
	private int				missileCount		= 0; 
	/** 储存UFO爆炸图像的类变量 */ 
	private int				direction; 
	/** 代表向右的常量 */ 
	static final int			DIRECTION_RIGHT		= 0; 
	/** 代表向左的常量 */ 
	static final int			DIRECTION_LEFT		= 1; 
	/** 储存UFO图像的类变量 */ 
	private static Image		ufoImg				= null; 
	/** 储存UFO爆炸图像的类变量 */ 
	private static Image		burstImg			= null; 
 
	/** 
	 * 构造函数 
	 * @param	myShip          自机对象 
	 */ 
	UFO(MyShip myShip) { 
		this.myShip = myShip; 
 
		if(ufoImg == null) { 
		//UFO图像为null时就取得图像 
			try { 
				ufoImg = Image.createImage("/ufo.png"); 
				burstImg = Image.createImage("/burst.png"); 
			}catch(Exception e) {} 
		} 
 
		//设定宽度与高度 
		width = ufoImg.getWidth(); 
		height = ufoImg.getHeight(); 
	} 
 
	/** 
	 * 设定Alive状态的方法 
	 * @param isAlive        是Alive状态就为true,不是Alive状态就为false 
	 */ 
	void setAlive(boolean isAlive) { 
		if(isAlive) { 
		//由于在变成Alive状态时会将这个UFO复活,因此要把值予以初始化 
			this.isHit = false; 
			missileCount = 0; 
			tickCount = 0; 
		} 
		super.setAlive(isAlive); 
	} 
 
	/** 要移动Sprite时所调用的方法 */ 
	void doMove() { 
		if(this.isAlive) {		//Alive时 
			if(isHit()) {		//Hit时 
				tickCount++; 
				//Tick计数为5的话就会从画面消失 
				if(tickCount > 4) { 
					setAlive(false); 
				} 
			}else {				//不是Hit时 
				//针对行进方向来移动UFO 
				switch(direction) { 
					case DIRECTION_RIGHT: 
						x = x + (width / 2) + 1; 
						break; 
 
					case DIRECTION_LEFT: 
						x = x - (width / 2) - 1; 
						break; 
				} 
			} 
		} 
	} 
 
	/** 在描绘Sprite的时候所调用的方法 */ 
	void doDraw(Graphics g) { 
		if(isAlive) { 
			if(isHit()) { 
			//Hit时就描绘爆炸图像 
				g.drawImage(burstImg, x, y, Graphics.TOP|Graphics.LEFT); 
			}else { 
				g.drawImage(ufoImg, x, y, Graphics.TOP|Graphics.LEFT); 
			} 
		} 
	} 
 
	/** 
	 * 设定UFO方向的方法 
	 * @param	direction	DIRECTION_RIGHT丄DIRECTION_LEFT偺偳偪傜偐 
	 */ 
	void setDirection(int direction) { 
		this.direction = direction; 
	} 
 
	/** 
	 * 用来判定UFO是否发出飞弹的方法 
	 * @return	boolean	发射飞弹时为true、没有发射时为false 
	 */ 
	boolean isDropBomb() { 
		if(missileCount < 3) { 
		//飞弹的发射数比3发还少时 
			//切割出UFO的中央坐标 
			int center = x + (width /2); 
			if(center >= myShip.getX() && center <= myShip.getX() + myShip.getWidth()) { 
			//UFO的中央坐标与自机的X坐标重叠时 
				//发射飞弹 
				missileCount++; 
				return true; 
			} 
		} 
		//处理到这个地方就不发射飞弹 
		return false; 
	} 
}