Java版坦克大战游戏源码示例

整理文档,搜刮出一个Java版坦克大战游戏的代码,稍微整理精简一下做下分享。

package tankwar;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

import tankwar.Tank.Direction;
import barrier.EnemyBorn;
import barrier.Gold;
import barrier.Home;
import barrier.Iron;
import barrier.SelfBorn;
import barrier.Wall;
/**
 * Java学习交流QQ群:589809992 我们一起学Java!
 */
public class TankWar implements KeyListener {
  static boolean TIMEOUT = false;
  private JFrame f;
  private JPanel gamePanel;
  private PanelShow messgePanel;
  private myPanel p;
  private Tank myTank;
  public static final int AREA_WIDTH = 830;
  public static final int AREA_HEIGHT = 800;
  private ArrayList<Missle> missles = new ArrayList<Missle>();
  private ArrayList<Tank> allTanks = new ArrayList<Tank>();
  private ArrayList<Boom> booms = new ArrayList<Boom>();
  private ArrayList<Wall> walls = new ArrayList<Wall>();
  private ArrayList<Iron> irons = new ArrayList<Iron>();
  private ArrayList<Gold> golds = new ArrayList<Gold>();
  private ArrayList<Item> items = new ArrayList<Item>();
  private ArrayList<EnemyBorn> enemyBorns = new ArrayList<EnemyBorn>();
  private SelfBorn selfBorn;
  private Home home;
  private Tank enemyTank;
  private Random r;
  private ImageIcon backGround;
  private final String map;
  private int tankMax;
  private boolean over = false;
  private static int selfMax = 3;
  private boolean win;
  private boolean flash = false;
  private TankWar tw = this;
  static int SCORE = 0;

  private final JFrame mainF;
  private int style;

  public TankWar(String map, int tankMax, JFrame mainF, int style)
      throws Exception {
    this.map = map;
    this.tankMax = tankMax;
    this.mainF = mainF;
    this.style = style;
    init();
  }

  private void init() {
    f = new JFrame("坦克大战 V3.0");
    gamePanel = new JPanel(null);
    p = new myPanel();
    p.setBackground(Color.WHITE);
    r = new Random();
    messgePanel = new PanelShow();
    initMap(new File("map/" + map));

    try {
      myTank = new Tank(selfBorn.getX(), selfBorn.getY(), true, allTanks,
          walls, irons, golds, missles, home, booms, style);
    } catch (Exception e1) {
    }
    myTank.setDir(Direction.U);

    allTanks.add(myTank);
    addTank();
    try {
      backGround = new ImageIcon(
          TankWar.class.getResource("/pic/whiteback.jpg"));
    } catch (Exception e) {
    }

    p.setBorder(BorderFactory.createEtchedBorder(Color.BLACK, Color.WHITE));
    p.setSize(AREA_WIDTH, AREA_HEIGHT);
    messgePanel.setBounds(AREA_WIDTH, 0, 200, AREA_HEIGHT);
    gamePanel.add(messgePanel);
    gamePanel.add(p);
    f.add(gamePanel);
    f.setBounds(0, 0, AREA_WIDTH + 200, AREA_HEIGHT);
    f.setDefaultCloseOperation(3);
    f.setResizable(true);
    f.setFocusable(true);
    f.addKeyListener(this);
    f.setVisible(true);

    new Thread(new Runnable() {
      public void run() {
        while (!over) {
          if (!myTank.isLive()) {
            selfMax--;
            if (selfMax < 0) {
              f.removeKeyListener(tw);
              over = true;
              win = false;
              break;
            } else {
              myTank.setLevel(1);
              myTank.setX(selfBorn.getX());
              myTank.setY(selfBorn.getY());
              myTank.setDir(Direction.U);
              myTank.setHp(50);
              myTank.setLive(true);
            }
          }
          if (tankMax <= 0 && allTanks.size() == 1) {
            f.removeKeyListener(tw);
            over = true;
            win = true;
          }
          if (!home.isLive()) {
            f.removeKeyListener(tw);
            over = true;
            win = false;
          }
          p.repaint();
          myTank.move();
          for (int i = 1; i < allTanks.size(); i++) {
            allTanks.get(i).move();
            allTanks.get(i).setNoFire(myTank.getNoFire() + 1);
            // if(allTanks.get(i).getX()%5==0&&allTanks.get(i).getY()%5==0)
            aI(allTanks.get(i));
          }
          if (allTanks.size() <= enemyBorns.size() + 1)
            addTank();
          myTank.setNoFire(myTank.getNoFire() + 1);
          messgePanel.setEnemyCount(tankMax);
          messgePanel.setSelfCount(selfMax);
          messgePanel.setScore(SCORE);
          if (SCORE % 500 == 0) {
            SCORE += 100;
            Item item = new Item(allTanks, booms, irons, home);
            items.add(item);
            item.start();
          }
          try {
            Thread.sleep(30);
          } catch (InterruptedException e) {
          }
        }

        over();
      }

    }).start();

  }

  private class myPanel extends JPanel {
    /**
     *
     */
    private static final long serialVersionUID = 4408440723797225328L;

    @Override
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.drawImage(backGround.getImage(), 0, 0, null);
      for (int j = 0; j < walls.size(); j++) {
        walls.get(j).draw(g);
      }
      for (int j = 0; j < irons.size(); j++) {
        irons.get(j).draw(g);
      }
      for (int j = 0; j < golds.size(); j++) {
        golds.get(j).draw(g);
      }
      for (int j = 0; j < enemyBorns.size(); j++) {
        enemyBorns.get(j).draw(g);
      }
      home.draw(g);
      selfBorn.draw(g);

      for (int j = 0; j < allTanks.size(); j++) {
        allTanks.get(j).drawTank(g);
      }
      for (int j = 0; j < irons.size(); j++) {
        irons.get(j).draw(g);
      }

      for (int i = 0; i < missles.size(); i++) {
        missles.get(i).drawMissle(g);
        if (!missles.get(i).isLive())
          missles.remove(i);
      }
      for (int i = 0; i < booms.size(); i++) {
        if (booms.get(i).isLive())
          booms.get(i).drawBoom(g);
        else
          booms.remove(i);
      }
      for (int j = 0; j < items.size(); j++) {
        if (!items.get(j).isLive()) {
          items.remove(j);
          continue;
        }
        items.get(j).draw(g);
      }
      if (over)
        drawOver(g);
      messgePanel.repaint();
    }
  }

  @Override
  public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyPressed(KeyEvent e) {
    if (over) {
      if (e.getKeyCode() == KeyEvent.VK_F1) {
        over = false;
        missles.clear();
        allTanks.clear();
        booms.clear();
        walls.clear();
        irons.clear();
        golds.clear();
        enemyBorns.clear();
        try {
          init();
        } catch (Exception e1) {
        }
      } else {
        f.setVisible(false);
        mainF.setSize(800, 800);
        mainF.setVisible(true);
      }
    } else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
      myTank.fire();
    } else {
      myTank.keyPress(e);
    }
  }

  @Override
  public void keyReleased(KeyEvent e) {

    myTank.keyReleased(e);
  }

  public void aI(Tank tank) {
    if (TIMEOUT) {
      tank.setUp(false);
      tank.setLeft(false);
      tank.setDown(false);
      tank.setRight(false);
      return;
    }

    if (r.nextInt(40) == 0)
      tank.fire();
    if (r.nextInt(10) == 0) {
      if (tank.getX() >= myTank.getX()
          && tank.getX() <= myTank.getX() + Tank.SIZE
          && tank.getY() > myTank.getY()) {
        tank.setUp(true);
        tank.setLeft(false);
        tank.setDown(false);
        tank.setRight(false);
        tank.setDir(Direction.U);
        return;
      } else if (tank.getX() >= myTank.getX()
          && tank.getX() <= myTank.getX() + Tank.SIZE
          && tank.getY() < myTank.getY()) {
        tank.setUp(false);
        tank.setLeft(false);
        tank.setDown(true);
        tank.setRight(false);
        tank.setDir(Direction.D);
        return;
      }

      else if (tank.getX() > myTank.getX()
          && tank.getY() >= myTank.getY()
          && tank.getY() <= myTank.getY() + Tank.SIZE) {
        tank.setUp(false);
        tank.setLeft(true);
        tank.setDown(false);
        tank.setRight(false);
        tank.setDir(Direction.L);
        return;
      } else if (tank.getX() < myTank.getX()
          && tank.getY() >= myTank.getY()
          && tank.getY() <= myTank.getY() + Tank.SIZE) {
        tank.setUp(false);
        tank.setLeft(false);
        tank.setDown(false);
        tank.setRight(true);
        tank.setDir(Direction.R);
        return;
      }
    }
    if (tank.getX() <= 0) {
      tank.setUp(false);
      tank.setLeft(false);
      tank.setDown(false);
      tank.setRight(true);
      tank.setDir(Direction.R);
    }
    if (tank.getY() <= 0) {
      tank.setUp(false);
      tank.setLeft(false);
      tank.setDown(true);
      tank.setRight(false);
      tank.setDir(Direction.D);
    }
    if (tank.getX() >= AREA_WIDTH - Tank.SIZE) {
      tank.setUp(false);
      tank.setLeft(true);
      tank.setDown(false);
      tank.setRight(false);
      tank.setDir(Direction.L);
    }
    if (tank.getY() >= AREA_HEIGHT - Tank.SIZE) {
      tank.setUp(true);
      tank.setLeft(false);
      tank.setDown(false);
      tank.setRight(false);
      tank.setDir(Direction.U);
    } else if (r.nextInt(300) == 1) {
      tank.setUp(true);
      tank.setLeft(false);
      tank.setDown(false);
      tank.setRight(false);
      tank.setDir(Direction.U);
    }

    else if (r.nextInt(300) == 2) {
      tank.setUp(false);
      tank.setLeft(true);
      tank.setDown(false);
      tank.setRight(false);
      tank.setDir(Direction.L);
    } else if (r.nextInt(300) == 3) {
      tank.setUp(false);
      tank.setLeft(false);
      tank.setDown(true);
      tank.setRight(false);
      tank.setDir(Direction.D);
    } else if (r.nextInt(300) == 4) {
      tank.setUp(false);
      tank.setLeft(false);
      tank.setDown(false);
      tank.setRight(true);
      tank.setDir(Direction.R);
    }
  }

  public void initMap(File file) {
    try {
      FileInputStream read = new FileInputStream(file);
      for (int i = 0; i < AREA_HEIGHT / 50; i++) {
        for (int j = 0; j < AREA_WIDTH / 50; j++) {
          switch (read.read()) {
          case 1:
            walls.add(new Wall(j * 50, i * 50));
            break;
          case 2:
            irons.add(new Iron(j * 50, i * 50));
            break;
          case 3:
            golds.add(new Gold(j * 50, i * 50));
            break;
          case 4:
            selfBorn = new SelfBorn(j * 50, i * 50);
            break;
          case 5:
            enemyBorns.add(new EnemyBorn(j * 50, i * 50));
            break;
          case 6:
            home = new Home(j * 50, i * 50);
            break;
          }
        }
      }
      read.close();
    } catch (Exception e) {
    }
    ;
  }

  public void addTank() {
    if (tankMax <= 0)
      return;
    for (int i = allTanks.size(); i < enemyBorns.size() + 1; i++) {
      try {
        int temp = r.nextInt(enemyBorns.size());
        enemyTank = new Tank(enemyBorns.get(temp).getX(), enemyBorns
            .get(temp).getY(), false, allTanks, walls, irons,
            golds, missles, home, booms, r.nextInt(3) + 1);
      } catch (Exception e) {
        e.printStackTrace();
      }
      enemyTank.setDir(Direction.D);
      enemyTank.setDown(true);
      allTanks.add(enemyTank);
      tankMax--;
      if (tankMax <= 0)
        return;
    }
  }

  public static void addMyTankLives() {
    selfMax++;
  }

  private void over() {

    for (int i = 0; i < AREA_HEIGHT / 50; i++) {
      for (int j = 0; j < AREA_WIDTH / 50; j++) {
        irons.add(new Iron(j * 50, i * 50));
        p.repaint();
        try {
          Thread.sleep(5);
        } catch (InterruptedException e) {
        }
      }
    }
    while (true) {
      flash = !flash;
      p.repaint();
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
      }
      f.addKeyListener(this);
    }
  }

  private void drawOver(Graphics g) {
    p.repaint();
    g.setColor(Color.red);
    g.setFont(new Font("Arial", 1, 100));
    g.drawString("GAME OVER", 100, 200);
    g.setFont(new Font("Arial", 2, 50));
    if (win)
      g.drawString("Congratulation! You Win!", 100, 400);
    else
      g.drawString("So Sorry, You Lose!", 100, 400);
    if (flash) {
      g.setFont(new Font("Arial", 2, 30));
      g.setColor(Color.BLACK);
      g.drawString("Press F1 to try again...,", 150, 500);
      g.drawString("Press the other Key to Return the Title...,", 150,
          600);
    }
  }
}

代码运行效果截图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • java中的数学计算函数的总结

    java中的数学计算函数 Math类: java.lang.Math类中包含基本的数字操作,如指数.对数.平方根和三角函数. java.math是一个包,提供用于执行任意精度整数(BigInteger)算法和任意精度小数(BigDecimal)算法的类. java.lang.Math类中包含E和PI两个静态常量,以及进行科学计算的类(static)方法,可以直接通过类名调用. public static final Double E = 2.7182818284590452354 public

  • java贪吃蛇游戏编写代码

    本文实例为大家分享了java贪吃蛇游戏展示的具体代码,供大家参考,具体内容如下 1.采用MVC(model.view.control)框架模式 2.包和类的关系树形图为: 3.源码: package com.huai; import Java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.util.HashSet; import java.util.LinkedList; import java.u

  • Java使用Math.random()结合蒙特卡洛方法计算pi值示例

    本文实例讲述了Java使用Math.random()结合蒙特卡洛方法计算pi值.分享给大家供大家参考,具体如下: 一.概述 蒙特·卡罗方法(Monte Carlo method),也称统计模拟方法,是二十世纪四十年代中期由于科学技术的发展和电子计算机的发明,而被提出的一种以概率统计理论为指导的一类非常重要的数值计算方法.是指使用随机数(或更常见的伪随机数)来解决很多计算问题的方法.与它对应的是确定性算法. 详细可参考百度百科:https://baike.baidu.com/item/%E8%92

  • java 简单的计算器程序实例代码

    java 简单的计算器程序 实现实例: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Calculator { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { CalculatorFrame frame = new Calculato

  • 用Java实现小球碰壁反弹的简单实例(算法十分简单)

    核心代码如下: if(addX){ x+=3; }else{ x-=3; } if(addY){ y+=6; }else{ y-=6; } if(x<=0||x>=(width-50)){ addX=!addX; } if(y<=0||y>=(height-50)){ addY=!addY; } 根据x和y递增的值,来决定角度. 以上这篇用Java实现小球碰壁反弹的简单实例(算法十分简单)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • Java编程实现游戏中的简单碰撞检测功能示例

    本文实例讲述了Java编程中的简单碰撞检测功能.分享给大家供大家参考,具体如下: 今天在家正在写一个坦克大战的小游戏来玩,遇到了一个简单的圆和圆的碰撞检测的小问题, 碰撞检测的过程处理主要有以下三步: 1.碰撞检测(Collision Detection):返回两个或多个物体是否发生碰撞的布尔判断. 2.碰撞确定(Collision Determination):找到物体之间实际相交位置. 3.碰撞响应(Collision Response):针对两个物体之间的碰撞决定采取何种操作. 下面是关于

  • Java编写迷宫小游戏

    缘起: 去年(大三上学期)比较喜欢写小游戏,于是想试着写个迷宫试一下. 程序效果: 按下空格显示路径: 思考过程: 迷宫由一个一个格子组成,要求从入口到出口只有一条路径. 想了一下各种数据结构,似乎树是比较合适的,从根节点到每一个子节点都只有一条路径.假设入口是根节点,出口是树中某个子节点,那么,从根节点到该子节点的路径肯定是唯一的. 所以如果能构造一棵树把所有的格子都覆盖到,也就能够做出一个迷宫了. 另外还要求树的父节点和子节点必须是界面上相邻的格子. 在界面显示时,父节点和子节点之间共用的边

  • Java计算一个数加上100是完全平方数,加上168还是完全平方数

    题目:一个整数,它加上100后是一个完全平方数,加上168又是一个完全平方数,请问该数是多少? 程序分析:在10万以内判断,先将该数加上100后再开方,再将该数加上268后再开方,如果开方后的结果满足如下条件,即是结果.请看具体分析: 程序设计: public class test { public static void main (String[]args){ long k=0; for(k=1;k<=100000l;k++) if(Math.floor(Math.sqrt(k+100))=

  • 利用java、js或mysql计算高德地图中两坐标之间的距离

    前言 因为工作的原因,最近在做与地图相关的应用,使用了高德地图,研究了下高德地图计算两坐标距离的方法,官网上提供的开发包中有相关的方法,但是我的产品中比较特殊,无法直接使用提供的方法,所以就自己封装了相关计算方法,供大家参考,下面话不多说了,来一起看看详细的介绍吧. Java实现 首先定义一个用于存储经纬度的类,这里起个名字叫:LngLat package amap; import java.text.DecimalFormat; import java.text.DecimalFormatSy

  • java计算两个日期之前的天数实例(排除节假日和周末)

    如题所说,计算两个日期之前的天数,排除节假日和周末.这里天数的类型为double,因为该功能实现的是请假天数的计算,有请一上午假的为0.5天. 不够很坑的是每个日期都要查询数据库,感觉很浪费时间. 原则: 1.节假日存放在数据库中 实现步骤: 1.循环每个日期 2.判断每个日期是否为节假日或者为周末 3.若不是节假日和周末,天数+1 代码: public double calLeaveDays(Date startTime,Date endTime){ double leaveDays = 0;

随机推荐