【Java实战】Java实现简易坦克对战小游戏

摘要:前期学习了Java入门的相关基础,现在通过这个小项目来熟悉巩固所学。该程序主要实现了一个简易的坦克对战小游戏,提供UI界面

//此程序用来实现一个简易的坦克对战小游戏!
//Version:1.0
//  @Author:Yongchun_zha

package cha09;

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.util.*;

public class L9_1 extends JFrame implements ActionListener

{

 Mypanel mp=null;

 GameStage gs=null;

 JMenuBar mb=null;

 JMenu mu=null;

 JMenuItem mi=null;

 JMenuItem mi1=null;

 JMenuItem mi2=null;

 JMenuItem mi3=null;



 public static void main(String[] args)

 {

      L91 l91=new L9_1();

 }



 public L9_1()

 {

  mb=new JMenuBar();

  mu=new JMenu("Game");

  mu.setMnemonic('G');

  mi=new JMenuItem("New Game");

  mi.setMnemonic('N');

  mi1=new JMenuItem("Go on Game

");

  mi1.setMnemonic('P');

  mi2=new JMenuItem("Save&Exit");

  mi2.setMnemonic('S');

  mi3=new JMenuItem("Exit");

  mi3.setMnemonic('E');



  mi.addActionListener(this);

  mi.setActionCommand("newGame");

  mi1.addActionListener(this);

  mi1.setActionCommand("goongame");

  mi2.addActionListener(this);

  mi2.setActionCommand("saveexit");

  mi3.addActionListener(this);

  mi3.setActionCommand("exit");



  mu.add(mi);

  mu.add(mi1);

  mu.add(mi2);

  mu.add(mi3);

  mb.add(mu);





  this.setJMenuBar(mb);

  gs=new GameStage();

  Thread ff=new Thread(gs);

  ff.start();

  this.add(gs);

  this.setIconImage(new ImageIcon("image/tank.jpg").getImage());

  this.setTitle("TANK_WAR");//设置用户界面

  this.setSize(400,500);//设置窗口大小,数字代表像素

  this.setLocation(300,260);//设置窗体位置

  this.setResizable(false);//设置窗体大小是否可调整

  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭进程

     this.setVisible(true);//true 显示,false不显示

 }



 public void actionPerformed(ActionEvent e)

 {

  if(e.getActionCommand().equals("newGame"))

  {

   mp=new Mypanel();

   this.remove(gs);

   this.add(mp);

   Thread bb=new Thread(mp);

   bb.start();



   this.addKeyListener(mp);

   this.setVisible(true);

  }



  else if(e.getActionCommand().equals("goongame"))

  {



  }



  else if(e.getActionCommand().equals("saveexit"))

  {

   Record record=new Record();

   record.setNumAt(mp.numArmyTank);

   record.saveGame();

   System.exit(0);

  }



  else if(e.getActionCommand().equals("exit"))

  {

   Record.writeRecord();

   System.exit(0);

  }

 }

}

class Mypanel extends JPanel implements KeyListener,Runnable

{

 MyTank mt=null;

 ArmyTank at=null;

 Explode bz=null;

 Vector armyTankV=new Vector();

 Vector bzV=new Vector();

 int numArmyTank=3;



 Image tp1=null;

 Image tp2=null;

 Image tp3=null;



 public void keyTyped(KeyEvent e){}

 public void keyReleased(KeyEvent e){}

 public void keyPressed(KeyEvent e)

 {

  if(e.getKeyCode()==KeyEvent.VK_W ||e.getKeyCode()==KeyEvent.VK_UP)

  {

   this.mt.setDirection(0);

   this.mt.turnUp();

  }



  else if(e.getKeyCode()==KeyEvent.VK_A ||e.getKeyCode()==KeyEvent.VK_DOWN)

  {

   this.mt.setDirection(1);

   this.mt.turnDown();

  }



  else if(e.getKeyCode()==KeyEvent.VK_S ||e.getKeyCode()==KeyEvent.VK_LEFT)

  {

   this.mt.setDirection(2);

   this.mt.turnLeft();

  }



  else if(e.getKeyCode()==KeyEvent.VK_D ||e.getKeyCode()==KeyEvent.VK_RIGHT)

  {

   this.mt.setDirection(3);

   this.mt.turnRight();

  }



  if(e.getKeyCode()==KeyEvent.VK_J)

  {

   if(this.mt.zdV.size()<8)

   {

    this.mt.shutBullet();

   }

  }

  this.repaint();



 }

 public Mypanel()

 {

  Shengyin music=new Shengyin("./tank.wav");

  music.start();

  Record.readRecord();

  mt=new MyTank(140,232);



  for(int i=0;i

  {

       at=new ArmyTank(i*181+5,0);

       at.setDirection(2);

       Thread cc=new Thread(at);

       cc.start();



       Bullet zd=new Bullet(at.x+10,at.y+30,2);

       at.dzdV.add(zd);

       Thread ee=new Thread(zd);

       ee.start();

       armyTankV.add(at);

  }



  tp1 = Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bzxg1.gif"));

  tp2 = Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bzxg2.gif"));

  tp3 = Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bzxg3.gif"));

 }



 public void paint(Graphics g)

 {

  super.paint(g);



  g.fillRect(0, 0, 400, 300);//设置画布大小



  if(mt.life==true)

  {

   this.drawTank(mt.getX(), mt.getY(), g, mt.direction , 0);

  }





  for(int i=0;i

  {

    at=armyTankV.get(i);



    if(at.life)

    {

     this.drawTank(at.getX(), at.getY(), g, at.direction, 1);

    }



    for(int j=0;j

    {

     Bullet zd=at.dzdV.get(j);

     if(zd.life)

     {

      g.setColor(Color.white);

      g.fill3DRect(zd.x,zd.y,3,3,false);

     }

     else

     {

      at.dzdV.remove(zd);

     }

    }

  }

  for(int i=0;i

  {

   Bullet zd=mt.zdV.get(i);



   if(zd!=null && mt.zd.life==true)

   {

    g.setColor(Color.white);

    g.fill3DRect(zd.x,zd.y , 3,3,false );

   }

   if(zd.life==false)

   {

    mt.zdV.remove(zd);

   }

  }



  for(int i=0;i

  {

   bz=bzV.get(i);



   if(bz.lifeLength>6)

   {

    g.drawImage(tp1, bz.x, bz.y, 30,30,this);

   }

   else if(bz.lifeLength>3)

   {

    g.drawImage(tp2, bz.x, bz.y, 30,30,this);

   }

   else

   {

    g.drawImage(tp3, bz.x, bz.y, 30,30,this);

   }

   bz.lifeLengthDecrease();



   if(bz.lifeLength==0)

   {

    bzV.remove(bz);

   }

  }

  this.showInformation(g);

 }



 public void drawTank(int x,int y,Graphics g,int direction,int type)

 {

  switch(type)

  {

  case 0://my tank

   g.setColor(Color.yellow);

   break;

  case 1://army's tank

   g.setColor(Color.green);

   break;

  }



  switch(direction)

  {

  case 0://up

   g.fill3DRect(x,y, 5, 30, false);

   g.fill3DRect(x+15,y, 5, 30,false);

   g.fill3DRect(x+5,y+5, 10, 20, false);

   g.fillOval(x+5,y+10, 10, 10);

   g.drawLine(x+10,y+15,x+10,y-3);

   break;



  case 1://down

   g.fill3DRect(x,y, 5, 30, false);

   g.fill3DRect(x+15,y, 5, 30,false);

   g.fill3DRect(x+5,y+5, 10, 20, false);

   g.fillOval(x+5,y+10, 10, 10);

   g.drawLine(x+10,y+15,x+10,y+33);

   break;



  case 2://left

   g.fill3DRect(x,y, 30, 5, false);

   g.fill3DRect(x,y+15, 30, 5,false);

   g.fill3DRect(x+5,y+5, 20, 10, false);

   g.fillOval(x+10,y+5, 10, 10);

   g.drawLine(x+15,y+10,x-3,y+10);

   break;



  case 3://right

   g.fill3DRect(x,y, 30, 5, false);

   g.fill3DRect(x,y+15, 30, 5,false);

   g.fill3DRect(x+5,y+5, 20, 10, false);

   g.fillOval(x+10,y+5, 10, 10);

   g.drawLine(x+20,y+10,x+30,y+10);

   break;



  }

 }



 public void showInformation(Graphics g)

 {

  this.drawTank(80, 330, g, 0, 0);

  this.drawTank(150,330, g, 0, 1);



  g.setColor(Color.black);

  g.drawString(Record.getNumAt()+"", 116,350);//整形数据后面加上“”,会把整形数据转换为String类型。

  g.drawString(Record.getNumMt()+"",186,350 );

  g.setFont(new Font("Bodoni MT",Font.CENTER_BASELINE,15));

  g.setColor(Color.BLACK);

  g.setFont(new Font("Bodoni MT",Font.BOLD,20));

  g.drawString("The number of Army Tanks you shutted:", 10,400);

  g.setColor(Color.DARK_GRAY);

  g.drawString(Record.getSumShutNumAt()+"",370,400 );

 }



public boolean shutted(Bullet zd,Tank tk)

 {

  boolean b2=false;



  switch(tk.direction)

  {

  case 0:

  case 1:

   if(zd.x>tk.x && zd.xtk.y && zd.y

   {

    zd.life=false;

    tk.life=false;

    Explode bz=new Explode(tk.x,tk.y);

    bzV.add(bz);

    b2=true;

   }

   break;

  case 2:

  case 3:

   if(zd.x>tk.x && zd.xtk.y && zd.y

   {

    zd.life=false;

    tk.life=false;

    b2=true;

    Explode bz=new Explode(tk.x,tk.y);

    bzV.add(bz);

    b2=true;

   }

   break;

  }

  return b2;

 }



 public void shuttedArmy()

 {

  for(int i=0;i

  {

   Bullet zd=mt.zdV.get(i);



   if(zd.life)

   {

    for(int j=0;j

    {

     ArmyTank at=armyTankV.get(j);



     if(at.life)

     {

      if(this.shutted(zd, at))

      {

       Record.atDc();

       Record.numShutAt();

      }

      this.shutted(zd, at);

     }

    }

   }

  }

 }

 public void shuttedMine()

 {

  for(int i=0;i

  {

   ArmyTank at=armyTankV.get(i);



   for(int j=0;j

   {

    Bullet zd=at.dzdV.get(j);



    this.shutted(zd, mt);



    if(this.shutted(zd, mt))

    {

     Record.mtDc();

    }

   }

   this.repaint();

  }

 }



 public void run()

 {

  while(true)

  {

   try

   {

    Thread.sleep(100);

    this.repaint();

   }

   catch(Exception e)

   {}



   for(int i=0;i

   {

    Bullet zd=mt.zdV.get(i);

    if(zd.life)

    {

     for(int j=0;j

     {

      ArmyTank at=armyTankV.get(j);

      if(at.life)

      {

       this.shuttedArmy();

      }

     }

    }

    this.repaint();

   }



   for(int i=0;i

   {

    Bullet zd=at.dzdV.get(i);

    if(mt.life)

    {

     this.shuttedMine();

    }

   }

   this.repaint();

  }

 }

}

class GameStage extends JPanel implements Runnable

{

 int time=0;



 public void paint(Graphics g)

 {

  super.paint(g);



  g.fillRect(0,0,400,300);



  if(time%2==0)

  {

   g.setColor(Color.orange);

   g.setFont(new Font("Blackoak Std",Font.BOLD,20));

   g.drawString("Welcome To", 50,140);

   g.setFont(new Font("Blackoak Std",Font.PLAIN,15));

   g.drawString("TANK WAR GAME", 30,170);

  }

 }



 public void run()

 {

  while(true)

  {

   try

   {

    Thread.sleep(500);

   }catch(Exception e){}

   time++;

   this.repaint();

  }

 }

}

//material lass

package cha09;

import java.io.*;

import java.util.Vector;

import javax.sound.sampled.AudioFormat;

import javax.sound.sampled.AudioInputStream;

import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.DataLine;

import javax.sound.sampled.SourceDataLine;

class Tank

{

 int x=0,y=0;

 int direction=0;

 int speed=5;

 boolean life=true;



 public int getDirection() {

  return direction;

 }

 public void setDirection(int direction) {

  this.direction = direction;

 }

 public int getSpeed() {

  return speed;

 }

 public void setSpeed(int speed) {

  this.speed = speed;

 }

 public int getX() {

  return x;

 }

 public void setX(int x) {

  this.x = x;

 }

 public int getY() {

  return y;

 }

 public void setY(int y) {

  this.y = y;

 }



 public Tank(int x,int y)

 {

  this.x=x;

  this.y=y;

 }

}

class Bullet implements Runnable

{

 int x,y;

 int direction;

 int speed=5;

 boolean life=true;



 public Bullet(int x,int y,int direction)

 {

  this.x=x;

  this.y=y;

  this.direction=direction;

 }



 public void run()

 {

  while(true)

  {

   try

   {

    Thread.sleep(50);

   }

   catch(Exception e)

   {}



   switch(direction)

   {

   case 0:

    y-=speed;

    break;



   case 1:

    y+=speed;

    break;



   case 2:

    x-=speed;

    break;



   case 3:

    x+=speed;

    break;

   }



   if(x<0||x>400||y<0||y>300)

   {

    this.life=false;

   }



  }



 }



}

class MyTank extends Tank

{

 Vector zdV=new Vector();



 Bullet zd=null;



 public MyTank(int x,int y)

 {

  super(x,y);

 }



 public void turnUp()

 {

  y-=speed;

 }



 public void turnDown()

 {

  y+=speed;

 }



 public void turnLeft()

 {

  x-=speed;

 }



 public void turnRight()

 {

  x+=speed;

 }



 public void shutBullet()

 {

  switch(this.direction)

  {

  case 0:

    zd=new Bullet(x+10,y,0);

    zdV.add(zd);

   break;



  case 1:

   zd=new Bullet(x+10,y+30,1);

   zdV.add(zd);

      break;

  case 2:

   zd=new Bullet(x,y+10,2);

   zdV.add(zd);

      break;



  case 3:

   zd=new Bullet(x+30,y+10,3);

   zdV.add(zd);

      break;

  }



  Thread aa=new Thread(zd);

  aa.start();

 }

}

class ArmyTank extends Tank implements Runnable

{

 int time=0;

 int direction;

 Bullet zd=null;

 Vector dzdV=new Vector();

 Vector armyTankV=null;

 public ArmyTank(int x,int y)

 {

  super(x, y);

 }

 public boolean Impact()

 {

  boolean b=true;



  switch(this.direction)

  {

  case 0:

  case 1:

   for(int i=0;i

   {

    ArmyTank at=armyTankV.get(i);

    if(at!=this)

    {

     if(this.x>=at.x+20 || this.x+20<=at.x || (this.x<=at.x+20 && this.x+20>=at.x && (this.y+30<=at.y || this.y<=at.y+30)))

     {

      return true;

     }

     if(this.y>=at.y+20 || this.y+30<=at.y || (this.y>=at.y-30 && this.y<=at.y+20 && (this.x>at.x+30) || (this.x+20<=at.x)))

     {

      return true;

     }

    }

   }

   break;

  case 2:

  case 3:

   for(int i=0;i

   {

    ArmyTank at=armyTankV.get(i);

    if(at!=this)

    {

     if(at.x+20<=this.x || at.x>=this.x+30 || (this.x>=at.x-30 && this.x<=at.x+20 &&(this.y>=at.y+30 || this.y+20<=at.y)))

     {

      return true;

     }

     if(this.y>=at.y+20 || this.y+20<=at.y || (this.y>=at.y-20 && this.y<=at.y+20 &&(this.x>=at.x+30 || this.x+30<=at.x)))

     {

      return true;

     }

    }

   }

   break;

  }

  return b;

 }



 public void run()

 {

  int speed=2;

  while(true)

  {

      switch(this.direction)

      {

      case 0:

       for(int i=0;i<30;i++)

       {

        if(y>0 && Impact())

        {

         y-=speed;

        }

        try

     {

      Thread.sleep(50);

     }catch(Exception e){}

       }

       break;

      case 1:

        for(int i=0;i<30;i++)

        {

         if(y<240 && Impact())

         {

          y+=speed;

         }

         try

      {

       Thread.sleep(50);

      }catch(Exception e){}

        }

        break;

      case 2:

       for(int i=0;i<30;i++)

       {

        if(x>0 && Impact())

        {

         x-=speed;

        }

        try

     {

      Thread.sleep(50);

     }catch(Exception e){}

       }

       break;

      case 3:

       for(int i=0;i<30;i++)

       {

        if(x<360 && Impact())

        {

         x+=speed;

        }

        try

     {

      Thread.sleep(50);

     }catch(Exception e){}

       }

       break;

       }



      this.direction=(int)(Math.random()*4);



      if(this.life==false)

      {

       break;

      }

      this.time++;



      if(time%2==0)

      {

       if(life)

       {

        if(dzdV.size()<8)

        {

         switch(direction)

         {

         case 0:

          zd=new Bullet(x+10,y,0);

          dzdV.add(zd);

          break;

         case 1:

          zd=new Bullet(x+10,y+30,1);

          dzdV.add(zd);

          break;

         case 2:

          zd=new Bullet(x+10,y+10,2);

          dzdV.add(zd);

          break;

         case 3:

          zd=new Bullet(x+30,y+10,3);

          dzdV.add(zd);

          break;

         }

         Thread dd=new Thread(zd);

         dd.start();

        }

       }

      }

  }

 }

}

class Explode

{

 int x,y;

 int lifeLength=9;

 boolean life=true;



 public Explode(int x,int y)

 {

  this.x=x;

  this.y=y;

 }

 public void lifeLengthDecrease()

 {

  if(lifeLength>0)

  {

   lifeLength--;

  }

  else

  {

   this.life=false;

  }

 }

}

class Record

{

 Vector armyTankV=null;

 private static int numAt=10;

 private static int numMt=2;

 private static int sumShutNumAt=0;

 private static FileOutputStream fo=null;

 private static FileInputStream fi=null;

 public static int getSumShutNumAt()

 {

  return sumShutNumAt;

 }

 public static void setSumShutNumAt(int sumShutNumAt)

 {

  Record.sumShutNumAt = sumShutNumAt;

 }

 public static void numShutAt()

 {

  sumShutNumAt++;

 }

 public static int getNumAt()

 {

  return numAt;

 }

 public static void setNumAt(int numAt)

 {

  Record.numAt = numAt;

 }

 public static int getNumMt()

 {

  return numMt;

 }

 public static void setNumMt(int numMt)

 {

  Record.numMt = numMt;

 }

 public static void atDc()

 {

  numAt--;

 }

 public static void mtDc()

 {

  numMt--;

 }

 public static void writeRecord()

 {

  try

  {

   fo=new FileOutputStream("F:/java/Part2/writeRecord.txt");

   fo.write(sumShutNumAt);

  }

  catch(Exception e){}

  finally

  {

   try

   {

    fo.close();

   }

   catch(Exception e){}

  }

 }

 public static void readRecord()

 {

  try

  {

   fi=new FileInputStream("F:/java/Part2/writeRecord.txt");

   sumShutNumAt=fi.read();

  }

  catch(Exception e){}

  finally

  {

   try

   {

    fi.close();

   }

   catch(Exception e){}

  }

 }

 public void saveGame()

 {

  try

  {

   fo=new FileOutputStream("F:/java/Part2/writeRecord.txt");

   fo.write(sumShutNumAt);



   for(int i=0;i

   {

    ArmyTank at=armyTankV.get(i);

    if(at.life)

    {

     int zb=at.x;

     int zb1=at.y;

     int zb2=at.direction;

     fo.write(zb);

     fo.write(zb1);

     fo.write(zb2);

    }

   }

  }

  catch(Exception e)

  {}

  finally

  {

   try

   {

    fo.close();

    fi.close();

   }

   catch(Exception e){}

  }



 }

}

class Location

{

 int x,y;

 int location;



 public Location(int x,int y,int location)

 {

  this.x=x;

  this.y=y;

  this.location=location;

 }

}

class Shengyin extends Thread {

 private String wjm;

 public Shengyin(String ypwj)

 {

   wjm=ypwj;

 }

 public void run() {

  File wjl = new File(wjm);

  AudioInputStream ypsrl = null;

  try {

   ypsrl = AudioSystem.getAudioInputStream(wjl);

  } catch (Exception e){}

  AudioFormat format = ypsrl.getFormat();

  SourceDataLine aqsj = null;

  DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

  try {

   aqsj = (SourceDataLine) AudioSystem.getLine(info);

   aqsj.open(format);

  } catch (Exception e){}

  aqsj.start();



  int zjtj = 0;

  byte[] hczj = new byte[1024];

  try {

   while (zjtj != -1) {

    zjtj = ypsrl.read(hczj, 0, hczj.length);

    if (zjtj >= 0)

     aqsj.write(hczj, 0, zjtj );

   }

  } catch (Exception e){}

  finally {

   aqsj.drain();

   aqsj.close();

  }

 }

}
posted @ 2017-08-16 13:08  yczha  阅读(437)  评论(0)    收藏  举报