使用java编写的小游戏:雷霆战机
效果如图
其中使用到的技术有: 1.线程 2.swing 画面的重画技术 3.集合等 都是JavaSE中最基本的
玩法是:按空格发射子弹 当子弹碰到敌方飞机时会消灭敌方飞机 我方飞机能用方向键自由移动 但不能碰到敌机 碰到敌机立刻死亡
若碰到敌方敌机发射的子弹则会扣100血 扣完就GG
虽然是一个简单的小游戏 但也有很多地方要注意 .
废话不多说 贴上源代码
游戏物体的夫类:
packagecom.planegame.util;importjava.awt.*;/***** 创建游戏物体****/public classGameObject {Imageimage;protected doublespeed,x,y;//定义物体的坐标和速度protected intheigth,width;//图像的长宽publicGameObject(){}publicGameObject(Image image,doublespeed,doublex,doubley,intheigth,intwidth){this.image= image;this.speed= speed;this.x=x;this.y=y;this.heigth=heigth;this.width=width;}public voidgraw(Graphics g){g.drawImage(image,(int)x,(int)y,null);}publicImage getImage() {returnimage;}public voidsetImage(Image image) {this.image= image;}public doublegetSpeed() {returnspeed;}public voidsetSpeed(doublespeed) {this.speed= speed;}public doublegetX() {returnx;}public voidsetX(doublex) {this.x= x;}public doublegetY() {returny;}public voidsetY(doubley) {this.y= y;}public intgetHeigth() {returnheigth;}public voidsetHeigth(intheigth) {this.heigth= heigth;}public intgetWidth() {returnwidth;}public voidsetWidth(intwidth) {this.width= width;}/** * 包围物体的正方形 * *@return正方形 */publicRectangle getRectangle(){return newRectangle(width,heigth);}}
游戏画面的夫类:
packagecom.planegame.main;importjavax.imageio.ImageIO;importjavax.imageio.ImageReader;importjavax.swing.*;importjava.awt.*;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.IOException;importjava.util.HashMap;import staticcom.planegame.util.Constant.Frame_Width;import staticcom.planegame.util.Constant.Frame_heigth;public classGameFrameextendsJFrame {public staticStringpath= System.getProperty("user.dir")+"\\src\\Image";public staticHashMap<String,BufferedImage>map=newHashMap<String , BufferedImage>();static{File file[]=newFile(path).listFiles();for(inti =0;i<file.length;i++){System.out.println(file[i].getName());try{map.put(file[i].getName(), ImageIO.read(file[i]));}catch(IOException e) {e.printStackTrace();}}}public voidlaunchFrame(){this.setSize(Frame_Width,Frame_heigth);this.setVisible(true);this.setLocationRelativeTo(null);this.setResizable(false);this.setDefaultCloseOperation(EXIT_ON_CLOSE);System.out.println(path);}public voidpaint(Graphics g ){}public static voidmain(String[] args) {newGameFrame().launchFrame();}}
主界面:
packagecom.planegame.main;importcom.planegame.util.*;importjava.awt.*;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.KeyListener;importjava.awt.image.BufferedImage;importjava.util.ArrayList;importjava.util.Iterator;public classFirstStageextendsGameFrameimplementsKeyListener{booleanhit_ememy;booleanhit;booleanhit_together=false;Pointpoint=newPoint(0,-646);Planeplane=newPlane(map.get("plane.jpg"),1,300,400,44,30);//建立自己的飞机类 传入参数 ScorePlatescorePlate=newScorePlate();Hphp=newHp();intre=0;intflag=0;//Ememy_Plane ememy_plane = new Ememy_Plane(map.get("small_enemy.png"),1000,300,50,50,50); ArrayList<Bullet>bullets=newArrayList<Bullet>();//建立一个存放随机射子弹的list ArrayList<MyBullets>mybulletelist=newArrayList<>();//创建list存放我们自己发射的子弹 ArrayList<Point>ememy_bulletelist=newArrayList<>();ArrayList<Ememy_Plane>ememy_planes=newArrayList<>();//创建list存放敌方飞机 //Bullet bullet = new Bullet(map.get("bullet.png"),5,50,100,20,50); // Bullet bullet1 = new Bullet(map.get("bullet.png"),5,500,100,20,50); /** * 构造一个无参的构造函数 * */publicFirstStage(){//newThread(newmove()).start();//背景移动和子弹飞行的线程newThread(newEmemyBullet()).start();//把bullet放入和敌方飞机移动list的线程newThread(newEmemy_plane()).start();//敌方飞机创建放入list的线程newThread(newememy_move()).start();newThread(newadd_bigememy() ).start();this.addKeyListener(this);//键盘监听 // bullets.add(bullet); // bullets.add(bullet1); }@Override /** * 把画面画在窗口 */public voidpaint(Graphics g) {super.paint(g);//创建一个画板 参数:宽800 高600 画板颜色类型 BufferedImage image =newBufferedImage(800,600,BufferedImage.TYPE_INT_RGB);Graphics gs= image.createGraphics();//创建画笔 gs.drawImage(map.get("Background-3.jpg"),point.x,point.y,this);//画背景gs.drawString("分数:",600,200);gs.drawString(String.valueOf(scorePlate.getScore()) ,640,200);gs.drawString("生命值:",600,300);gs.drawString(String.valueOf(hp.getHp()) ,640,300);if(hp.getHp()==0){plane.setAlive(false);}if(plane.isAlive()) {gs.drawImage(map.get("red_plane.png") , (int)plane.getX() , (int)plane.getY() ,this);}else{plane.setWidth(0);plane.setWidth(0);Color c = g.getColor();gs.setColor(Color.WHITE);//plane.move(); gs.setFont(newFont("aa",Font.LAYOUT_RIGHT_TO_LEFT,60));gs.drawString("Game Over",270,300);gs.setColor(c);}for(inti=0; i <ememy_planes.size(); i++) {if(ememy_planes.get(i).isLive()) {inty=(int)ememy_planes.get(i).getY()+50;ememy_bulletelist.add(newPoint((int)ememy_planes.get(i).getX(),y));gs.drawImage(ememy_planes.get(i).getImage() , (int)ememy_planes.get(i).getX() , (int)ememy_planes.get(i).getY() ,this);hit_together=ememy_planes.get(i).getRectangle().intersects(plane.getRectangle());if(hit_together) {System.out.println("hit_together");plane.setAlive(false);}}}for(intj =0;j<mybulletelist.size();j++){for(intq =0;q<ememy_planes.size();q++){hit_ememy=ememy_planes.get(q).getRectangle().intersects(mybulletelist.get(j).getRectangle());if(hit_ememy){ememy_planes.get(q).dispear();ememy_planes.get(q).setLive(false);scorePlate.addScore();//ememy_plane.setLive(false); }}gs.drawImage(map.get("red_bullet.png"),mybulletelist.get(j).x,mybulletelist.get(j).y,this);// hit_ememy=ememy_planes.get(i).getRectangle().intersects(mybulletelist.get(i).getRectangle()); }for(inti =0;i<bullets.size();i++){gs.drawImage(map.get("bullet.png"), (int)bullets.get(i).getX() ,(int)bullets.get(i).getY(),this);bullets.get(i).move();hit=plane.getRectangle().intersects(bullets.get(i).getRectangle());if(hit){bullets.get(i).setHeigth(0);bullets.get(i).setWidth(0);hp.decreaseHp();}}g.drawImage(image,0,0,this);}@Overridepublic voidkeyTyped(KeyEvent e) {}@Overridepublic voidkeyPressed(KeyEvent e) {if(e.getKeyCode()==KeyEvent.VK_UP){plane.setTop(true);plane.move();}else if(e.getKeyCode()==KeyEvent.VK_SPACE){if(plane.isAlive()){plane.fire(map.get("red_bullet.png"),(int)plane.getX() , (int)plane.getY() ,mybulletelist);}}else if(e.getKeyCode()==KeyEvent.VK_RIGHT){plane.setRight(true);plane.move();}else if(e.getKeyCode()==KeyEvent.VK_LEFT){plane.setLeft(true);plane.move();}else if(e.getKeyCode()==KeyEvent.VK_DOWN){plane.setDown(true);plane.move();}}@Overridepublic voidkeyReleased(KeyEvent e) {}classEmemyBulletimplementsRunnable{@Overridepublic voidrun() {while(true){intx_random= (int) ((int)1000*Math.random());bullets.add(newBullet(map.get("bullet.png"),5,x_random,100,48,44));try{Thread.sleep(100);}catch(InterruptedException e) {e.printStackTrace();}}}}classEmemy_planeimplementsRunnable{@Overridepublic voidrun() {while(true){intememy_plane_x= (int) (Math.random()*800);intrand= (int)(Math.random()*10);if(rand>5){ememy_planes.add(newEmemy_Plane(map.get("small_enemy.png"),1000,ememy_plane_x,50,50,50));}else{ememy_planes.add(newEmemy_Plane(map.get("middle_enemy.png"),1000,ememy_plane_x,50,50,50));}try{Thread.sleep(1000);}catch(InterruptedException e) {e.printStackTrace();}}}}classmoveimplementsRunnable{@Overridepublic voidrun() {while(true){if(point.y==0){point.y=-646;}point.y+=1;for(inti =0;i<mybulletelist.size();i++){mybulletelist.get(i).y-=5;}try{Thread.sleep(10);}catch(InterruptedException e) {e.printStackTrace();}repaint();}}}classadd_bigememyimplementsRunnable{@Overridepublic voidrun() {while(true){intememy_plane_x = (int)(Math.random()*800);if(scorePlate.getScore()>100){ememy_planes.add(newEmemy_Plane(map.get("big_enemy.png"),1000,ememy_plane_x,50,50,50));ememy_bulletelist.add(newPoint(ememy_plane_x,50));}try{Thread.sleep(3000);}catch(InterruptedException e) {e.printStackTrace();}}}}classememy_moveimplementsRunnable{@Overridepublic voidrun() {while(true){for(inti=0;i<ememy_planes.size();i++){ememy_planes.get(i).move();}try{Thread.sleep(100);}catch(InterruptedException e) {e.printStackTrace();} }}}}敌方子弹:
packagecom.planegame.util;importjava.awt.*;import staticcom.planegame.util.Constant.Frame_Width;import staticcom.planegame.util.Constant.Frame_heigth;/**** 创建游戏中飞行的子弹**/public classBulletextendsGameObject{doublex,y,speed;@OverridepublicRectangle getRectangle() {return newRectangle((int)x,(int)y,width,heigth);}public doublegetX() {returnx;}public voidsetX(doublex) {this.x= x;}public doublegetY() {returny;}public voidsetY(doubley) {this.y= y;}public doublegetSpeed() {returnspeed;}public voidsetSpeed(doublespeed) {this.speed= speed;}public intgetWidth() {returnwidth;}public voidsetWidth(intwidth) {this.width= width;}public intgetHeigth() {returnheigth;}public voidsetHeigth(intheigth) {this.heigth= heigth;}private doubledegree;publicBullet(Image image,doublespeed,doublex,doubley,intheigth,intwidth) {this.speed=speed;//子弹的运行速度speed 其实是半径this.x=x;//子弹飞行的x轴初始坐标this.y=y;//子弹飞行的y轴初始坐标this.image= image;//子弹图像this.heigth=heigth;//子弹宽度this.width=width;//子弹高度this.degree=Math.PI*2*Math.random();//子弹飞行的角度——随机 由0.01*π到π这区间内 }public voidgraw(Graphics g){g.drawImage(image,(int)x,(int)y,null);//调用Graphics的方法 在窗口中画图像move();}public voidmove(){this.x+=speed*Math.cos(degree);// x= x+半径*cos随机角度this.y+=speed*Math.sin(degree);}}
游戏常量:
packagecom.planegame.util;importjava.awt.*;public classConstant {public static intFrame_Width=800;//窗口宽度public static intFrame_heigth=600;//窗口高度}
敌方飞机:
packagecom.planegame.util;importjava.awt.*;importjava.util.ArrayList;import staticcom.planegame.util.Constant.Frame_Width;import staticcom.planegame.util.Constant.Frame_heigth;/***@Author7aY*@Description:TODO()*@Date:Create in 21:26/12/20*/public classEmemy_PlaneextendsGameObject {Imageimage;doublespeed;doublex;doubley;intheigth;intwidth;booleanlive=true;public booleanisLive() {returnlive;}public voidsetLive(booleanlive) {this.live= live;}publicImage getImage() {returnimage;}public voidsetImage(Image image) {this.image= image;}public doublegetSpeed() {returnspeed;}public voidsetSpeed(doublespeed) {this.speed= speed;}public doublegetX() {returnx;}public voidsetX(doublex) {this.x= x;}public doublegetY() {returny;}public voidsetY(doubley) {this.y= y;}public intgetHeigth() {returnheigth;}public voidsetHeigth(intheigth) {this.heigth= heigth;}public intgetWidth() {returnwidth;}public voidsetWidth(intwidth) {this.width= width;}publicEmemy_Plane() {super();}publicEmemy_Plane(Image image ,doublespeed ,doublex ,doubley ,intheigth ,intwidth) {this.image=image;this.speed=speed;this.x=x;this.y=y;this.heigth=heigth;this.width=width;}@OverridepublicRectangle getRectangle() {return newRectangle((int)x,(int)y,width,heigth);}public voiddispear(){this.x=0;this.y=0;this.width=0;this.heigth=0;}public voidmove(){intdirection= (int) (Math.random()*10);if(direction<2){this.x=this.x-4;if(this.x<0){this.x=20;}}if(direction>4&&direction<7){this.y=y+5;if(this.y>Frame_heigth){this.y=Frame_heigth-30;}}if(direction>7){this.y=y+5;if(this.y>Frame_heigth){this.y=Frame_heigth-30;}}if(direction<4&&direction>2){this.x=this.x+4;if(this.x>Frame_Width-50){this.x=Frame_Width;}}}// public void fire(Image image, double plane_x, double plane_y, ArrayList<Ememy_bullete> list){// list.add(new Ememy_bullete(image,100,(int)plane_x,(int)plane_y+100,64,64)); //}}
HP;
packagecom.planegame.util;/***@Author7aY*@Description:TODO()*@Date:Create in 21:19/12/21*/public classHp {inthp=1000;public intgetHp() {returnhp;}public voidsetHp(inthp) {this.hp= hp;}/** * 减血量 */public voiddecreaseHp(){setHp(getHp()-100);}}
我方子弹:
packagecom.planegame.util;importjava.awt.*;/***@Author7aY*@Description:TODO()*@Date:Create in 22:17/12/20*/public classMyBulletsextendsGameObject {public intx;public inty;intheigth,width;Imageimage;publicMyBullets() {super();}publicMyBullets(Image image,intx,inty,intheigth,intwidth){this.x=x;this.y=y;this.heigth=heigth;this.width=width;this.image=image;}@OverridepublicRectangle getRectangle() {return newRectangle(x,y,width,heigth);}}
我方飞机:
packagecom.planegame.util;importjava.awt.*;importjava.util.ArrayList;import staticcom.planegame.util.Constant.Frame_Width;import staticcom.planegame.util.Constant.Frame_heigth;/**** 创建游戏飞机主体****/public classPlaneextendsGameObject {booleantop=false,down,left,right;//判断键盘输入方向booleanalive=true;//判断飞机是否被击落doublex;doubley;intbullet_x;intbullet_y;intwidth;intheigth;public intgetWidth() {returnwidth;}public voidsetWidth(intwidth) {this.width= width;}public intgetHeigth() {returnheigth;}public voidsetHeigth(intheigth) {this.heigth= heigth;}@OverridepublicRectangle getRectangle() {return newRectangle((int)x,(int)y,width,heigth);}public doublegetX() {returnx;}public voidsetX(inti ,doublex) {this.x= x;}public doublegetY() {returny;}public voidsetY(doubley) {this.y= y;}publicPlane() {super();}publicPlane(Image image,doublespeed,doublex,doubley,intheigth,intwidth) {this.image= image;this.speed= speed;this.x=x;this.y=y;this.heigth=heigth;this.width=width;}public voidfire(Image image,intplane_x,intplane_y, ArrayList<MyBullets> list){list.add(newMyBullets(image,plane_x-10,plane_y-50,64,64));}public voidmove(){if(this.top==true){if(this.y<0) {this.y=60;}else{this.y-= 10;setTop(false);}}else if(this.down==true){if(this.y>Frame_heigth-60){this.y=Frame_heigth-60;}else{this.y+=10;setDown(false);}}else if(this.left==true){if(this.x<0){this.x=0;}else{this.x-= 10;setLeft(false);}}else if(this.right==true){if(this.x>Frame_Width-100){this.x=Frame_Width-100;}else{this.x+=10;setRight(false);}}}public booleanisTop() {returntop;}public voidsetTop(booleantop) {this.top= top;}public booleanisDown() {returndown;}public voidsetDown(booleandown) {this.down= down;}public booleanisLeft() {returnleft;}public voidsetLeft(booleanleft) {this.left= left;}public booleanisRight() {returnright;}public voidsetRight(booleanright) {this.right= right;}public booleanisAlive() {returnalive;}public voidsetAlive(booleanalive) {this.alive= alive;}}
总分数:
packagecom.planegame.util;/***@Author7aY*@Description:TODO()*@Date:Create in 12:41/12/21*/public classScorePlate {intscore=0;public intgetScore() {returnscore;}public voidsetScore(intscore) {this.score= score;}public voidaddScore(){setScore(getScore()+100);}}