天天看點

swing 飛機大戰 四 生成敵人飛機和敵人子彈

敵人飛機類,因為後面還想做些關卡弄不同的飛機,是以加了個飛機類型,線程根據不同的飛機類型類控制移動的規則

package Game;

import java.util.Vector;

import javax.swing.ImageIcon;

public class FoeFly extends Fly implements Runnable{
	public Vector<FoeFly> foeFlyArr;
	public ImageIcon img;
	public int type; //敵人飛機類型
	public FoeFly(){
		foeFlyArr = new Vector<>(); //執行個體化敵人飛機集合
	}
	public FoeFly(int x, int y, int hp, boolean doom, int type, String path){
		super(x,y,hp,doom);
		this.type = type;
		img = new ImageIcon(path);
	}
	@Override
	public void run() { //敵人飛機移動線程
		while (true){
			try {
				Thread.sleep(8);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			for (int i=0; i<foeFlyArr.size(); i++){
				if (foeFlyArr.get(i).type == 1){ //類型一飛機,直線向下移動
					if (foeFlyArr.get(i).y > 600){
						foeFlyArr.remove(i);
						i--;
						continue;
					}
					foeFlyArr.get(i).y += 1;
				}
			}
		}
	}
}
           

通過一個線程類來創造敵人飛機

package pass;

import Game.FoeFly;

/**
 * 
 * @author Administrator
 *關卡1的建立飛機線程
 */
public class ProduceNo1 implements Runnable{
	FoeFly foefly;
	public ProduceNo1(FoeFly foefly) {
		this.foefly = foefly;
	}
	@Override
	public void run() {
		while (true){
			try {
				Thread.sleep(2000);//間隔兩秒生成一架敵人飛機
			} catch (InterruptedException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}
			int x = (int)Math.round(Math.random()*350);
			int y = (int)Math.round(Math.random()*(-20));
			foefly.foeFlyArr.add(new FoeFly(x,y,40,true,1,"img/Foefly-1.png"));
		}
	}
}
           

敵人子彈通過線程建立出來(在敵人飛機位置生成)

package Game;
/**
 * 
 * @author Administrator
 *生成敵人子彈類線程
 */
public class Pfb implements Runnable{
	FoeFly foefly;
	FoeBomb foebomb;
	public Pfb(FoeFly foefly, FoeBomb foebomb){
		this.foefly = foefly;
		this.foebomb = foebomb;
	}
	@Override
	public void run() {
		while (true){
			//給每個子彈類在敵人飛機位置生成 子彈
			for (int i=0 ;i<foefly.foeFlyArr.size(); i++){
					foebomb.bombarr.add(new FoeBomb(foefly.foeFlyArr.get(i).x+25, foefly.foeFlyArr.get(i).y+50, true,"img/drzd-1.png"));
			}
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
           

敵人子彈類

package Game;

import java.util.Vector;

import javax.swing.ImageIcon;

/**
 * 
 * @author Administrator
 *敵人子彈線程
 */
public class FoeBomb extends Bomb implements Runnable{
	public FoeBomb(){
		bombarr = new Vector<>();
	}
	public FoeBomb(int x, int y, boolean vis, String path) {
		super(x, y, vis);
		img = new ImageIcon(path);
	}
	@Override
	public void run() {
		while (true){
			try {
				Thread.sleep(7);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			for (int i=0; i<bombarr.size(); i++){
				if (bombarr.get(i).y > 600){//超出邊界
					bombarr.remove(i);
					i--;
					continue;
				}
				bombarr.get(i).y += 1;
			}
		}
	}
}
           

效果圖

swing 飛機大戰 四 生成敵人飛機和敵人子彈