swing 飞机大战 四 生成敌人飞机和敌人子弹

来源:互联网 发布:mac桌面双桌面 编辑:程序博客网 时间:2024/04/23 19:15

敌人飞机类,因为后面还想做些关卡弄不同的飞机,所以加了个飞机类型,线程根据不同的飞机类型类控制移动的规则

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);}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic 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);}@Overridepublic 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;}}}}

效果图


原创粉丝点击