Java实现飞机大战-连接数据库并把得分写入数据库
编写飞行物类
packagecom.tarena.shoot; importjava.awt.image.BufferedImage; /** *飞行物(敌机,蜜蜂,子弹,英雄机) */ publicabstractclassFlyingObject{ protectedintx; protectedinty; protectedintwidth; protectedintheight; protectedBufferedImageimage; protectedBufferedImage[]ember; publicintgetX(){ returnx; } publicvoidsetX(intx){ this.x=x; } publicintgetY(){ returny; } publicvoidsetY(inty){ this.y=y; } publicintgetWidth(){ returnwidth; } publicvoidsetWidth(intwidth){ this.width=width; } publicintgetHeight(){ returnheight; } publicvoidsetHeight(intheight){ this.height=height; } publicBufferedImagegetImage(){ returnimage; } publicvoidsetImage(BufferedImageimage){ this.image=image; } /** *检查是否出界 *@paramwidth边界宽 *@paramheight边界高 *@returntrue出界与否 */ publicabstractbooleanoutOfBounds(); /** *飞行物移动一步 */ publicabstractvoidstep(); /** *检查当前飞行物体是否被子弹(x,y)击(shoot)中, *true表示击中,飞行物可以被击中 *@paramBullet子弹对象 *@returntrue表示被击中了 */ publicbooleanshootBy(Bulletbullet){ if(bullet.isBomb()){ returnfalse; } intx=bullet.x;//子弹横坐标 inty=bullet.y;//子弹纵坐标 booleanshoot=this.x编写飞机类
packagecom.tarena.shoot; /** *敌飞机:是飞行物,也是敌人 */ publicclassAirplaneextendsFlyingObjectimplementsEnemy{ intspeed=2;//移动步骤 publicAirplane(){ this.image=ShootGame.airplane; this.ember=ShootGame.airplaneEmber; width=image.getWidth(); height=image.getHeight(); y=-height; x=(int)(Math.random()*(ShootGame.WIDTH-width)); } @Override publicintgetScore(){//获取分数 return5; } @Override public booleanoutOfBounds(){//越界处理 returny>ShootGame.HEIGHT; } @Override publicvoidstep(){//移动 y+=speed; } }编写奖励接口
packagecom.tarena.shoot; /** *奖励 */ publicinterfaceAward{ intDOUBLE_FIRE=0;//双倍火力 intLIFE=1;//1条命 /**获得奖励类型(上面的0或1)*/ intgetType(); }编写蜜蜂类
packagecom.tarena.shoot; importjava.util.Random; publicclassBeeextendsFlyingObjectimplementsAward{ privateintxSpeed=1; privateintySpeed=2; privateintawardType; publicBee(){ this.image=ShootGame.bee; this.ember=ShootGame.beeEmber; width=image.getWidth(); height=image.getHeight(); y=-height; Randomrand=newRandom(); x=rand.nextInt(ShootGame.WIDTH-width); awardType=rand.nextInt(2);//初始化时给奖励 } publicintgetType(){ returnawardType; } @Override publicbooleanoutOfBounds(){ returny>ShootGame.HEIGHT; } @Override publicvoidstep(){//可斜飞 x+=xSpeed; y+=ySpeed; if(x>ShootGame.WIDTH-width){ xSpeed=-1; } if(x<0){ xSpeed=1; } } }编写大飞机类
packagecom.tarena.shoot; importjava.util.Random; publicclassBigPlaneextendsFlyingObject implementsEnemy,Award{ privateintxSpeed=1; privateintySpeed=1; privateintlife; privateintawardType; publicBigPlane(){ life=4; this.image=ShootGame.bigPlane; this.ember=ShootGame.bigPlaneEmber; width=image.getWidth(); height=image.getHeight(); y=-height; Randomrand=newRandom(); x=rand.nextInt(ShootGame.WIDTH-width); awardType=rand.nextInt(2); } publicintgetType(){ returnawardType; } @Override publicintgetScore(){ return50; } @Override publicbooleanoutOfBounds(){ returnfalse; } // @Override // publicBufferedImagegetImage(){ // Graphicsg=image.getGraphics(); // g.setColor(Color.white); // g.fillRect(0,0,40,30); // g.setColor(Color.black); // g.drawString("L:"+life,10,20); // returnimage; // } publicEnemyBullet[]shoot(){//发射子弹 intxStep=width/4;//子弹步分为飞机宽度4半 intyStep=20; EnemyBullet[]bullets2=newEnemyBullet[1]; bullets2[0]=newEnemyBullet(x+2*xStep,y-yStep); returnbullets2; } @Override publicvoidstep(){//移动 x+=xSpeed; y+=ySpeed; if(x>ShootGame.WIDTH-width){ xSpeed=-1; } if(x<0){ xSpeed=1; } } publicbooleanshootBy(Bulletbullet){ if(super.shootBy(bullet)){ life--; } returnlife==0; } }编写子弹类
packagecom.tarena.shoot; /** *子弹类 */ publicclassBulletextendsFlyingObject{ privateintspeed=3;//移动的速度 privatebooleanbomb; publicBullet(intx,inty){ this.x=x; this.y=y; this.image=ShootGame.bullet; } publicvoidsetBomb(booleanbomb){ this.bomb=bomb; } publicbooleanisBomb(){ returnbomb; } @Override publicvoidstep(){//移动方法 y-=speed; } @Override publicbooleanoutOfBounds(){ returny<-height; } }编写飞机爆炸效果
packagecom.tarena.shoot; importjava.awt.image.BufferedImage; /** *灰烬飞机被打掉以后的残影 *@authorRobin */ publicclassEmber{ privateBufferedImage[]images={}; privateintindex; privateinti; privateBufferedImageimage; privateintintevel=10; privateintx,y; publicEmber(FlyingObjectobject){ images=object.ember; image=object.image; x=object.x; y=object.y; index=0; i=0; } publicbooleanburnDown(){ i++; if(i%intevel==0){ if(index==images.length){ returntrue; } image=images[index++]; } returnfalse; } publicintgetX(){ returnx; } publicintgetY(){ returny; } publicBufferedImagegetImage(){ returnimage; } }编写敌人类
packagecom.tarena.shoot; /** *敌人,可以有分数 */ publicinterfaceEnemy{ //敌人的分数 intgetScore(); }编写敌机子弹类
packagecom.tarena.shoot; publicclassEnemyBulletextendsFlyingObject{ privateintspeed=2;//移动的速度 privatebooleanbomb; publicEnemyBullet(intx,inty){ this.x=x; this.y=y; this.image=ShootGame.EnemyBullet; } publicvoidsetBomb(booleanbomb){ this.bomb=bomb; } publicbooleanisBomb(){ returnbomb; } @Override publicvoidstep(){//移动方法 y+=speed; } @Override publicbooleanoutOfBounds(){ returny<-height; } }编写英雄机类
packagecom.tarena.shoot; importjava.awt.image.BufferedImage; /** *英雄机 * *@authorAdministrator * */ publicclassHeroextendsFlyingObject{ protectedBufferedImage[]images={}; protectedintindex=0; //privatebooleandoubleFire; privateintdoubleFire; privateintlife; publicHero(){ life=3; doubleFire=0; this.image=ShootGame.hero0; this.ember=ShootGame.heroEmber; images=newBufferedImage[]{ShootGame.hero0,ShootGame.hero1}; width=image.getWidth(); height=image.getHeight(); x=150; y=400; } publicintisDoubleFire(){ returndoubleFire; } publicvoidaddDoubleFire(){ doubleFire=40; } publicvoidsetDoubleFire(intdoubleFire){ this.doubleFire=doubleFire; } publicvoidaddLife(){//增命 life++; } publicvoidsubtractLife(){//减命 life--; } publicintgetLife(){ returnlife; } /** *当前物体移动了一下,相对距离,x,y鼠标位置 */ publicvoidmoveTo(intx,inty){ this.x=x-width/2; this.y=y-height/2; } @Override publicbooleanoutOfBounds(){ returnx<0||x>ShootGame.WIDTH-width||y<0 ||y>ShootGame.HEIGHT-height; } publicBullet[]shoot(){//发射子弹 intxStep=width/4;//子弹步分为飞机宽度4半 intyStep=20; if(doubleFire>0){ Bullet[]bullets=newBullet[2]; bullets[0]=newBullet(x+xStep,y-yStep); bullets[1]=newBullet(x+3*xStep,y-yStep); doubleFire-=2; returnbullets; }else{//单倍 Bullet[]bullets=newBullet[1]; bullets[0]=newBullet(x+2*xStep,y-yStep);//y-yStep(子弹距飞机的位置) returnbullets; } } @Override publicvoidstep(){ if(images.length>0){ image=images[index++/10%images.length]; } } publicbooleanhit(FlyingObjectother){//碰撞算法 intx1=other.x-this.width/2; intx2=other.x+other.width+this.width/2; inty1=other.y-this.height/2; inty2=other.y+other.height+this.height/2; returnthis.x+this.width/2>x1&&this.x+this.width/2y1 &&this.y+this.width/2 x1&&hx y1&&hy 编写bgm类
packagecom.tarena.shoot; importjava.applet.Applet; importjava.applet.AudioClip; importjava.io.File; importjava.net.URI; importjava.net.URL; importjavax.swing.JFrame; publicclassSoundextendsJFrame{ Filef; URIuri; URLurl; Sound(){ try{ f=newFile("C:\\Users\\姜涛\\Desktop\\dddd\\StudioEIM-MapleStory.wav"); uri=f.toURI(); url=uri.toURL();//解析地址 AudioClipaau; aau=Applet.newAudioClip(url); aau.loop();//循环播放 }catch(Exceptione) {e.printStackTrace(); } } }编写主类
packagecom.tarena.shoot; importjava.awt.Color; importjava.awt.Font; importjava.awt.Graphics; importjava.awt.event.MouseAdapter; importjava.awt.event.MouseEvent; importjava.awt.image.BufferedImage; importjava.util.Arrays; importjava.util.Random; importjava.util.Timer; importjava.util.TimerTask; importjavax.imageio.ImageIO; importjavax.swing.ImageIcon; importjavax.swing.JFrame; importjavax.swing.JPanel; importDAO.DAO; publicclassShootGameextendsJPanel{ publicstaticfinalintWIDTH=400;//面板宽 publicstaticfinalintHEIGHT=654;//面板高 /**游戏的当前状态:STARTRUNNINGPAUSEGAME_OVER*/ privateintstate; publicstaticfinalintSTART=0; publicstaticfinalintRUNNING=1; publicstaticfinalintPAUSE=2; publicstaticfinalintGAME_OVER=3; privateintscore=0;//得分 privateTimertimer;//定时器 privateintintervel=1000/100;//时间间隔(毫秒) publicstaticBufferedImagebackground; publicstaticBufferedImagestart; publicstaticBufferedImagepause; publicstaticBufferedImagegameover; publicstaticBufferedImagebullet; publicstaticBufferedImageairplane; publicstaticBufferedImageEnemyBullet; publicstaticBufferedImage[]airplaneEmber=newBufferedImage[4]; publicstaticBufferedImagebee; publicstaticBufferedImage[]beeEmber=newBufferedImage[4];; publicstaticBufferedImagehero0; publicstaticBufferedImagehero1; publicstaticBufferedImage[]heroEmber=newBufferedImage[4];; publicstaticBufferedImagebigPlane; publicstaticBufferedImage[]bigPlaneEmber=newBufferedImage[4];; privateFlyingObject[]flyings={};//敌机数组 privateBullet[]bullets={};//子弹数组 privateEnemyBullet[]bullets2={};//敌机子弹数组 privateHerohero=newHero();//英雄机 privateEmber[]embers={};//灰烬 privateBigPlanebigplane=newBigPlane(); static{//静态代码块 try{ background=ImageIO.read(ShootGame.class .getResource("background.png")); bigPlane=ImageIO .read(ShootGame.class.getResource("bigplane.png")); airplane=ImageIO .read(ShootGame.class.getResource("airplane.png")); bee=ImageIO.read(ShootGame.class.getResource("bee.png")); bullet=ImageIO.read(ShootGame.class.getResource("bullet.png")); hero0=ImageIO.read(ShootGame.class.getResource("hero0.png")); hero1=ImageIO.read(ShootGame.class.getResource("hero1.png")); pause=ImageIO.read(ShootGame.class.getResource("pause.png")); EnemyBullet=ImageIO.read(ShootGame.class.getResource("EnemyBullet.png")); gameover=ImageIO .read(ShootGame.class.getResource("gameover.png")); start=ImageIO .read(ShootGame.class.getResource("start.png")); for(inti=0;i<4;i++){ beeEmber[i]=ImageIO.read( ShootGame.class.getResource("bee_ember"+i+".png")); airplaneEmber[i]=ImageIO.read( ShootGame.class.getResource("airplane_ember"+i+".png")); bigPlaneEmber[i]=ImageIO.read( ShootGame.class.getResource("bigplane_ember"+i+".png")); heroEmber[i]=ImageIO.read( ShootGame.class.getResource("hero_ember"+i+".png")); } }catch(Exceptione){ e.printStackTrace(); } } @Override publicvoidpaint(Graphicsg){ g.drawImage(background,0,0,null);//画背景图 paintEmber(g); paintHero(g);//画英雄机 paintBullets(g);//画子弹 paintFlyingObjects(g);//画飞行物 paintScore(g);//画分数 paintState(g);//画游戏状态 paintEnemyBullets(g);//画敌机子弹 } /**画英雄机*/ publicvoidpaintHero(Graphicsg){ g.drawImage(hero.getImage(),hero.getX(),hero.getY(),null); } publicvoidpaintEmber(Graphicsg){ for(inti=0;i下面实现数据库的连接,首先编写将分数写入数据库的方法,在src重新建一个包,包里写写入分数的方法。
packageDAO; importjava.sql.Connection; importjava.sql.PreparedStatement; importjava.sql.SQLException; importutil.DBUtil; publicclassDAO{ /* *增加分数的方法 */ publicstaticvoidsave(intscore)throwsException{ PreparedStatementps=null; Connectionconn=null; try{ conn=DBUtil.getConnection(); Stringsql="INSERTINTOmydb2(score)values(?)"; ps=conn.prepareStatement(sql); ps.setInt(1,score); ps.executeUpdate(); }catch(SQLExceptione){ e.printStackTrace(); }finally{ DBUtil.close(conn); } } } 然后连接数据库
packageutil; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.SQLException; publicclassDBUtil{ publicstaticvoidmain(String[]args)throwsException{ Connectionconn=DBUtil.getConnection(); System.out.println(conn); DBUtil.close(conn); } publicstaticvoidclose(Connectionconn){ try{ if(conn!=null){ conn.close(); } }catch(SQLExceptione){ e.printStackTrace(); } } publicstaticConnectiongetConnection()throwsException{ //System.out.println("112"); Connectionconn=null; //1.注册驱动(加载驱动) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=数据库名字","sa","********"); //System.out.println("123"); // try{ // Class.forName("com.microsoft.sqlserver.jdbc.Driver"); // System.out.println("111"); // //2.建立连接 // conn=DriverManager.getConnection("jdbc:sqlserver://localhost:1443/mydb2","sa","the1012secret"); // System.out.println("111"); // }catch(ClassNotFoundExceptione){ // //System.out.println("注册驱动"); // }catch(SQLExceptione){ // e.printStackTrace(); // } returnconn; } }