坦克大战java源代码

合集下载

坦克大战源代码

坦克大战源代码

import java.awt.Color;import java.awt.Frame;import java.awt.Graphics;import java.awt.Image;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.util.ArrayList;import java.util.List;public class TankClient extends Frame {public static final int GAME_WIDTH = 800;public static final int GAME_HEIGHT = 600;Tank myTank = new Tank(50, 50, true, Tank.Direction.STOP, this);List<Missile> missiles = new ArrayList<Missile>();List<Explode> explodes = new ArrayList<Explode>();List<Tank> tanks = new ArrayList<Tank>();Image offScreenImage = null;@Overridepublic void paint(Graphics g) {g.drawString("missiles count:" + missiles.size(), 10, 50);g.drawString("explodes count:" + explodes.size(), 10, 70);g.drawString("tanks count:" + tanks.size(), 10, 90);for(int i=0; i<missiles.size(); i++) {Missile m = missiles.get(i);m.hitTanks(tanks);m.draw(g);}for(int i=0; i<explodes.size(); i++) {Explode e = explodes.get(i);e.draw(g);}for(int i=0; i<tanks.size(); i++) {Tank t = tanks.get(i);t.draw(g);}myTank.draw(g);}@Overridepublic void update(Graphics g) {if(offScreenImage == null) {offScreenImage = this.createImage(800, 600);}Graphics gOffScreen = offScreenImage.getGraphics();Color c = gOffScreen.getColor();gOffScreen.setColor(Color.GREEN);gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);gOffScreen.setColor(c);paint(gOffScreen);g.drawImage(offScreenImage, 0, 0, null);}public void launchFrame() {//生产多少地方坦克for(int i=0; i<5; i++) {tanks.add(new Tank(50 + 40*(i+1), 50, false, Tank.Direction.D, this));}this.setLocation(400, 300);this.setSize(GAME_WIDTH, GAME_HEIGHT);this.setTitle("TankWar");this.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {System.exit(0);}});this.setResizable(false);this.setBackground(Color.GREEN);this.addKeyListener(new KeyMonitor());this.setVisible(true);new Thread(new PaintThread()).start();}public static void main(String[] args) {TankClient tc = new TankClient();unchFrame();}class PaintThread implements Runnable {public void run() {while(true) {repaint();try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}}}}class KeyMonitor extends KeyAdapter {@Overridepublic void keyReleased(KeyEvent e) {myTank.keyReleased(e);}@Overridepublic void keyPressed(KeyEvent e) {myTank.keyPressed(e);}}}import java.awt.Color;import java.awt.Graphics;import java.awt.Rectangle;import java.awt.event.KeyEvent;import java.util.Random;public class Tank {public static final int XSPEED = 5;public static final int YSPEED = 5;public static final int WIDTH = 30;public static final int HEIGHT = 30;boolean good;int x, y;private static Random r = new Random();private boolean live = true;private int step = r.nextInt(12) + 3;TankClient tc;boolean bL, bU, bR, bD;enum Direction {L, LU, U, RU, R, RD, D, LD, STOP};Direction dir = Direction.STOP;Direction ptDir = Direction.D;public Tank(int x, int y, boolean good) {this.x = x;this.y = y;this.good = good;}public Tank(int x, int y, boolean good, Direction dir, TankClient tc) { this(x, y, good);this.dir = dir;this.tc = tc;}public void draw(Graphics g) {if(!live) {if(!good) {tc.tanks.remove(this);}return;}Color c = g.getColor();if(good) g.setColor(Color.RED);else g.setColor(Color.BLUE);g.fillOval(x, y, WIDTH, HEIGHT);g.setColor(c);switch(ptDir) {case L:g.drawLine(x + WIDTH/2, y + HEIGHT/2, x, y + HEIGHT/2);break;case LU:g.drawLine(x + WIDTH/2, y + HEIGHT/2, x, y);break;case U:g.drawLine(x + WIDTH/2, y + HEIGHT/2, x + WIDTH/2, y);break;case RU:g.drawLine(x + WIDTH/2, y + HEIGHT/2, x + WIDTH, y);break;case R:g.drawLine(x + WIDTH/2, y + HEIGHT/2, x + WIDTH, y + HEIGHT/2);break;case RD:g.drawLine(x + WIDTH/2, y + HEIGHT/2, x + WIDTH, y + HEIGHT);break;case D:g.drawLine(x + WIDTH/2, y + HEIGHT/2, x + WIDTH/2, y + HEIGHT);break;case LD:g.drawLine(x + WIDTH/2, y + HEIGHT/2, x, y + HEIGHT);break;}move();}private void move() {switch(dir) {case L:x -= XSPEED;break;case LU:x -= XSPEED;y -= YSPEED;break;case U:y -= YSPEED;break;case RU:x += XSPEED;y -= YSPEED;break;case R:x += XSPEED;break;case RD:x += XSPEED;y += YSPEED;break;case D:y += YSPEED;break;case LD:x -= XSPEED;y += YSPEED;break;case STOP:break;}if(dir != Direction.STOP) {ptDir = dir;}if(x < 0) x = 0;if(y < 30) y = 30;if(x + WIDTH > TankClient.GAME_WIDTH) x = TankClient.GAME_WIDTH - WIDTH;if(y+ HEIGHT> TankClient.GAME_HEIGHT) y= TankClient.GAME_HEIGHT- HEIGHT;if(!good) {if(step == 0) {step = r.nextInt(12) + 3;Direction[] dirs = Direction.values();dir = dirs[r.nextInt(dirs.length)];}step --;if(r.nextInt(40) > 38) this.fire();}}public void keyPressed(KeyEvent e) {int key = e.getKeyCode();switch (key) {case KeyEvent.VK_LEFT:bL = true;break;case KeyEvent.VK_UP:bU = true;break;case KeyEvent.VK_RIGHT:bR = true;break;case KeyEvent.VK_DOWN:bD = true;break;}locateDirection();}private void locateDirection() {if(bL && !bU && !bR && !bD) dir = Direction.L;else if(bL && bU && !bR && !bD) dir = Direction.LU;else if(!bL && bU && !bR && !bD) dir = Direction.U;else if(!bL && bU && bR && !bD) dir = Direction.RU;else if(!bL && !bU && bR && !bD) dir = Direction.R;else if(!bL && !bU && bR && bD) dir = Direction.RD;else if(!bL && !bU && !bR && bD) dir = Direction.D;else if(bL && !bU && !bR && bD) dir = Direction.LD;else if(!bL && !bU && !bR && !bD) dir = Direction.STOP;}public void keyReleased(KeyEvent e) {int key = e.getKeyCode();switch (key) {case KeyEvent.VK_CONTROL:fire();break;case KeyEvent.VK_LEFT:bL = false;break;case KeyEvent.VK_UP:bU = false;break;case KeyEvent.VK_RIGHT:bR = false;break;case KeyEvent.VK_DOWN:bD = false;break;}locateDirection();}private Missile fire() {int x = this.x + WIDTH/2 - Missile.WIDTH/2;int y = this.y + HEIGHT/2 - Missile.HEIGHT/2;Missile m = new Missile(x, y, this.good, this.ptDir, this.tc);tc.missiles.add(m);return m;}public Rectangle getRect() {return new Rectangle(x, y, WIDTH, HEIGHT);}public boolean isLive() {return live;}public void setLive(boolean live) {this.live = live;}}import java.awt.Color;import java.awt.Graphics;import java.awt.Rectangle;import java.util.List;public class Missile {public static final int XSPEED = 10;public static final int YSPEED = 10;public static final int WIDTH = 10;public static final int HEIGHT = 10;TankClient tc;int x, y;Tank.Direction dir = Tank.Direction.R;boolean live = true;private boolean good;public Missile(int x, int y, boolean good, Tank.Direction dir) { this.x = x;this.y = y;this.good = good;this.dir = dir;}public Missile(int x, int y, boolean good, Tank.Direction dir, TankClient tc) {this(x, y, good, dir);this.tc = tc;}public void draw(Graphics g) {if(!live) {tc.missiles.remove(this);return;}Color c = g.getColor();g.setColor(Color.BLACK);g.fillOval(x, y, WIDTH, HEIGHT);g.setColor(c);move();}private void move() {switch(dir) {case L:x -= XSPEED;break;case LU:x -= XSPEED;y -= YSPEED;break;case U:y -= YSPEED;break;case RU:x += XSPEED;y -= YSPEED;break;case R:x += XSPEED;break;case RD:x += XSPEED;y += YSPEED;break;case D:y += YSPEED;break;case LD:x -= XSPEED;y += YSPEED;break;case STOP:break;}if(x< 0 || y< 0 || x> TankClient.GAME_WIDTH|| y> TankClient.GAME_HEIGHT) {live = false;}}public Rectangle getRect() {return new Rectangle(x, y, WIDTH, HEIGHT);}public boolean hitTank(Tank t) {if(this.live && t.isLive() && this.good != t.good&&this.getRect().intersects(t.getRect())) {this.live = false;t.setLive(false);tc.explodes.add(new Explode(x, y, tc));return true;}return false;}public boolean hitTanks(List<Tank> tanks) { for(int i=0; i<tanks.size(); i++) {if(this.hitTank(tanks.get(i))) {return true;}}return false;}}import java.awt.Color;import java.awt.Graphics;public class Explode {int x, y;private int[] diameters = {4, 7, 12, 18, 26, 32, 49, 30, 14, 6};private boolean live = true;private TankClient tc;int step = 0;public Explode(int x, int y, TankClient tc) {this.x = x;this.y = y;this.tc = tc;}public void draw(Graphics g) {if(!live) {tc.explodes.remove(this);return;}Color c = g.getColor();g.setColor(Color.ORANGE);g.fillOval(x, y, diameters[step], diameters[step]);g.setColor(c);step ++;if(step == diameters.length) {live = false;}}}。

坦克大战程序代码

坦克大战程序代码

import java.awt.* ;import javax.swing.* ;import java.awt.event.*;import java.util.EventListener;class f extends JFrame {f(String title) {this.setTitle(title) ;this.setSize(608 , 630) ;this.setLocation(300 , 100) ;this.setBackground(Color.BLACK) ;MyTank mp = new MyTank() ;this.add(mp) ;this.addKeyListener(mp) ;new Thread(mp).start() ;}public static void main(String[] args) {f h = new f("坦克大战(版本1.0)") ;h.setVisible(true) ;}}//主战坦克class MyTank extends JPanel implements KeyListener , Runnable {int x = 280, y = 280 ;//坦克的初始位置int op = 1 ;//坦克的移动方向int color = 0 ;int tankspeed = 8 ;//坦克的速度int tankbullet = 8 ;//坦克的子弹速度int tankfbullet = 4 ;//敌军的子弹速度int shengming = 100 ;//生命int fenshu = 0 ;int nandu = 5 ; //设置游戏难度//子弹int dx = 295 , dy = 295 ;int dx1 = 295 , dy1 = -10 ;int dx2 = 600 , dy2 = 295 ;int dx3 = 295 , dy3 = 600 ;int dx4 = -10 , dy4 = 295 ;//敌军坦克int num = 10 ;//敌军坦克数量,不能修改int[] xf = new int[num] ;int[] yf = new int[num] ;int[] opf = new int[num] ;int[] dxf = new int[num] ;int[] dyf = new int[num] ;int[] dxf1 = new int[num] ;int[] dyf1 = new int[num] ;int[] dxf2 = new int[num] ;int[] dyf2 = new int[num] ;int[] dxf3 = new int[num] ;int[] dyf3 = new int[num] ;int[] dxf4 = new int[num] ;int[] dyf4 = new int[num] ;//构造函数,初始化敌军坦克的位置和状态MyTank() {for (int i = 0; i<num; i++) {xf[i] = (int) (Math.random() * 560) ; yf[i] = (int) (Math.random() * 560) ; dxf[i] = xf[i] + 15 ;dyf[i] = yf[i] + 15 ;}for (int i = 0; i<num; i++) {dxf1[i] = 295 ; dyf1[i] = -10 ;dxf2[i] = 600 ; dyf2[i] = 295 ;dxf3[i] = 295 ; dyf3[i] = 600 ;dxf4[i] = -10 ; dyf4[i] = 295 ;}}//主面版public void paint(Graphics g) { super.paint(g) ;this.setBackground(Color.YELLOW) ;g.setColor(Color.red) ;g.drawString("生命:" , 10 , 20 ) ;g.fillRect(50 , 10 , shengming * 5 , 10) ;g.drawRect(50 , 10 , 500 , 10) ;g.drawString("得分: "+ fenshu , 10 , 40) ;if(op == 1) {g.setColor(Color.red) ;g.fillRect(x , y , 40 , 40) ;switch (color % 6) {case 0: g.setColor(Color.blue) ; break; case 1: g.setColor(Color.yellow) ; break; case 2: g.setColor(Color.red) ; break;case 3: g.setColor(Color.orange) ; break; case 4: g.setColor(Color.green) ; break; case 5: g.setColor(Color.black) ; break; }g.fillOval(x - 5 , y - 5 , 10 , 10) ;g.fillOval(x - 5 , y + 5 , 10 , 10) ;g.fillOval(x - 5 , y + 15 , 10 , 10) ;g.fillOval(x - 5 , y + 25 , 10 , 10) ;g.fillOval(x - 5 , y + 35 , 10 , 10) ;g.fillOval(x + 35 , y - 5 , 10 , 10) ;g.fillOval(x + 35 , y + 5 , 10 , 10) ;g.fillOval(x + 35 , y + 15 , 10 , 10) ;g.fillOval(x + 35 , y + 25 , 10 , 10) ;g.fillOval(x + 35 , y + 35 , 10 , 10) ;g.setColor(Color.black) ;g.fillRect(x + 15 , y - 20 , 10 , 40) ;switch (color % 20) {case 0: g.setColor(Color.white) ; break; case 1: g.setColor(Color.white) ; break; case 2: g.setColor(Color.white) ; break; case 3: g.setColor(Color.white) ; break; case 4: g.setColor(Color.white) ; break; case 5: g.setColor(Color.white) ; break; case 6: g.setColor(Color.white) ; break;case 7: g.setColor(Color.white) ; break;case 8: g.setColor(Color.white) ; break;case 9: g.setColor(Color.white) ; break;case 10: g.setColor(Color.black) ; break;case 11: g.setColor(Color.black) ; break;case 12: g.setColor(Color.black) ; break;case 13: g.setColor(Color.black) ; break;case 14: g.setColor(Color.black) ; break;case 15: g.setColor(Color.black) ; break;case 16: g.setColor(Color.black) ; break;case 17: g.setColor(Color.black) ; break;case 18: g.setColor(Color.black) ; break;case 19: g.setColor(Color.black) ; break; }g.fillOval(x + 5 , y + 30 , 10 , 10) ;g.fillOval(x + 25 , y + 30 , 10 , 10) ;}if(op == 2) {g.setColor(Color.green) ;g.fillRect(x , y , 40 , 40) ;switch (color % 6) {case 0: g.setColor(Color.blue) ; break;case 1: g.setColor(Color.yellow) ; break;case 2: g.setColor(Color.red) ; break;case 3: g.setColor(Color.orange) ; break;case 4: g.setColor(Color.green) ; break;case 5: g.setColor(Color.black) ; break;}g.fillOval(x - 5 , y - 5 , 10 , 10) ;g.fillOval(x + 5 , y - 5 , 10 , 10) ;g.fillOval(x + 15 , y - 5 , 10 , 10) ;g.fillOval(x + 25 , y - 5 , 10 , 10) ;g.fillOval(x + 35 , y - 5 , 10 , 10) ;g.fillOval(x - 5 , y+35 , 10 , 10) ;g.fillOval(x + 5 , y+35 , 10 , 10) ;g.fillOval(x + 15 , y+35 , 10 , 10) ;g.fillOval(x + 25 , y+35 , 10 , 10) ;g.fillOval(x + 35 , y+35 , 10 , 10) ;g.setColor(Color.black) ;g.fillRect(x + 20 , y + 15 , 40 , 10) ;switch (color % 20) {case 0: g.setColor(Color.white) ; break;case 1: g.setColor(Color.white) ; break;case 2: g.setColor(Color.white) ; break;case 3: g.setColor(Color.white) ; break;case 4: g.setColor(Color.white) ; break;case 5: g.setColor(Color.white) ; break;case 6: g.setColor(Color.white) ; break;case 7: g.setColor(Color.white) ; break;case 8: g.setColor(Color.white) ; break;case 9: g.setColor(Color.white) ; break;case 10: g.setColor(Color.black) ; break;case 11: g.setColor(Color.black) ; break;case 12: g.setColor(Color.black) ; break;case 13: g.setColor(Color.black) ; break;case 14: g.setColor(Color.black) ; break;case 15: g.setColor(Color.black) ; break;case 16: g.setColor(Color.black) ; break;case 17: g.setColor(Color.black) ; break;case 18: g.setColor(Color.black) ; break;case 19: g.setColor(Color.black) ; break; }g.fillOval(x , y + 5 , 10 , 10) ;g.fillOval(x , y + 25 , 10 , 10) ;}if(op == 3) {g.setColor(Color.blue) ;g.fillRect(x , y , 40 , 40) ;switch (color % 6) {case 0: g.setColor(Color.blue) ; break;case 1: g.setColor(Color.yellow) ; break;case 2: g.setColor(Color.red) ; break;case 3: g.setColor(Color.orange) ; break;case 4: g.setColor(Color.green) ; break;case 5: g.setColor(Color.black) ; break;}g.fillOval(x - 5 , y - 5 , 10 , 10) ;g.fillOval(x - 5 , y + 5 , 10 , 10) ;g.fillOval(x - 5 , y + 15 , 10 , 10) ;g.fillOval(x - 5 , y + 25 , 10 , 10) ;g.fillOval(x - 5 , y + 35 , 10 , 10) ;g.fillOval(x + 35 , y - 5 , 10 , 10) ;g.fillOval(x + 35 , y + 5 , 10 , 10) ;g.fillOval(x + 35 , y + 15 , 10 , 10) ;g.fillOval(x + 35 , y + 25 , 10 , 10) ;g.fillOval(x + 35 , y + 35 , 10 , 10) ;g.setColor(Color.black) ;g.fillRect(x + 15 , y + 20 , 10 , 40) ;switch (color % 20) {case 0: g.setColor(Color.white) ; break;case 1: g.setColor(Color.white) ; break;case 2: g.setColor(Color.white) ; break;case 3: g.setColor(Color.white) ; break;case 4: g.setColor(Color.white) ; break;case 5: g.setColor(Color.white) ; break;case 6: g.setColor(Color.white) ; break;case 7: g.setColor(Color.white) ; break;case 8: g.setColor(Color.white) ; break;case 9: g.setColor(Color.white) ; break;case 10: g.setColor(Color.black) ; break;case 11: g.setColor(Color.black) ; break;case 12: g.setColor(Color.black) ; break;case 13: g.setColor(Color.black) ; break;case 14: g.setColor(Color.black) ; break;case 15: g.setColor(Color.black) ; break;case 16: g.setColor(Color.black) ; break;case 17: g.setColor(Color.black) ; break;case 18: g.setColor(Color.black) ; break;case 19: g.setColor(Color.black) ; break; }g.fillOval(x + 5 , y , 10 , 10) ;g.fillOval(x + 25 , y , 10 , 10) ;}if(op == 4) {g.setColor(Color.yellow) ;g.fillRect(x , y , 40 , 40) ;switch (color % 6) {case 0: g.setColor(Color.blue) ; break;case 1: g.setColor(Color.yellow) ; break;case 2: g.setColor(Color.red) ; break;case 3: g.setColor(Color.orange) ; break;case 4: g.setColor(Color.green) ; break;case 5: g.setColor(Color.black) ; break;}g.fillOval(x - 5 , y - 5 , 10 , 10) ;g.fillOval(x + 5 , y - 5 , 10 , 10) ;g.fillOval(x + 15 , y - 5 , 10 , 10) ;g.fillOval(x + 25 , y - 5 , 10 , 10) ;g.fillOval(x + 35 , y - 5 , 10 , 10) ;g.fillOval(x - 5 , y+35 , 10 , 10) ;g.fillOval(x + 5 , y+35 , 10 , 10) ;g.fillOval(x + 15 , y+35 , 10 , 10) ;g.fillOval(x + 25 , y+35 , 10 , 10) ;g.fillOval(x + 35 , y+35 , 10 , 10) ;g.setColor(Color.black) ;g.fillRect(x - 20 , y + 15 , 40 , 10) ;switch (color % 20) {case 0: g.setColor(Color.white) ; break;case 1: g.setColor(Color.white) ; break;case 2: g.setColor(Color.white) ; break;case 3: g.setColor(Color.white) ; break;case 4: g.setColor(Color.white) ; break;case 5: g.setColor(Color.white) ; break;case 6: g.setColor(Color.white) ; break;case 7: g.setColor(Color.white) ; break;case 8: g.setColor(Color.white) ; break;case 9: g.setColor(Color.white) ; break;case 10: g.setColor(Color.black) ; break;case 11: g.setColor(Color.black) ; break;case 12: g.setColor(Color.black) ; break;case 13: g.setColor(Color.black) ; break;case 14: g.setColor(Color.black) ; break;case 15: g.setColor(Color.black) ; break;case 16: g.setColor(Color.black) ; break;case 17: g.setColor(Color.black) ; break;case 18: g.setColor(Color.black) ; break;case 19: g.setColor(Color.black) ; break; }g.fillOval(x + 30 , y + 5 , 10 , 10) ;g.fillOval(x + 30 , y + 25 , 10 , 10) ;}g.setColor(Color.black) ;g.fillOval(dx , dy , 10 , 10) ;g.fillOval(dx1 , dy1 , 10 , 10) ;g.fillOval(dx2 , dy2 , 10 , 10) ;g.fillOval(dx3 , dy3 , 10 , 10) ;g.fillOval(dx4 , dy4 , 10 , 10) ;for (int i = 0; i<num; i++) {if(opf[i] == 1) {g.fillRect(xf[i] , yf[i] , 40 , 40) ;g.fillOval(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; g.fillOval(xf[i] - 5 , yf[i] + 5 , 10 , 10) ; g.fillOval(xf[i] - 5 , yf[i] + 15 , 10 , 10) ;g.fillOval(xf[i] - 5 , yf[i] + 25 , 10 , 10) ;g.fillOval(xf[i] - 5 , yf[i] + 35 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] - 5 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 5 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 15 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 25 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 35 , 10 , 10) ;g.fillRect(xf[i] + 15 , yf[i] - 20 , 10 , 40) ;g.fillOval(xf[i] + 5 , yf[i] + 30 , 10 , 10) ;g.fillOval(xf[i] + 25 , yf[i] + 30 , 10 , 10) ; }if(opf[i] == 2) {g.fillRect(xf[i] , yf[i] , 40 , 40) ;g.fillOval(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; g.fillOval(xf[i] + 5 , yf[i] - 5 , 10 , 10) ; g.fillOval(xf[i] + 15 , yf[i] - 5 , 10 , 10) ;g.fillOval(xf[i] + 25 , yf[i] - 5 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] - 5 , 10 , 10) ;g.fillOval(xf[i] - 5 , yf[i] + 35 , 10 , 10) ;g.fillOval(xf[i] + 5 , yf[i] + 35 , 10 , 10) ;g.fillOval(xf[i] + 15 , yf[i] + 35 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 35 , 10 , 10) ;g.fillRect(xf[i] + 20 , yf[i] + 15 , 40 , 10) ;g.fillOval(xf[i] , yf[i] + 5 , 10 , 10) ;g.fillOval(xf[i] , yf[i] + 25 , 10 , 10) ;}if(opf[i] == 3) {g.fillRect(xf[i] , yf[i] , 40 , 40) ;g.fillOval(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; g.fillOval(xf[i] - 5 , yf[i] + 5 , 10 , 10) ; g.fillOval(xf[i] - 5 , yf[i] + 15 , 10 , 10) ;g.fillOval(xf[i] - 5 , yf[i] + 25 , 10 , 10) ;g.fillOval(xf[i] - 5 , yf[i] + 35 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] - 5 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 5 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 15 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 25 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 35 , 10 , 10) ;g.fillRect(xf[i] + 15 , yf[i] + 20 , 10 , 40) ;g.fillOval(xf[i] + 5 , yf[i] , 10 , 10) ;g.fillOval(xf[i] + 25 , yf[i] , 10 , 10) ;}if(opf[i] == 4) {g.fillRect(xf[i] , yf[i] , 40 , 40) ;g.fillOval(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; g.fillOval(xf[i] + 5 , yf[i] - 5 , 10 , 10) ; g.fillOval(xf[i] + 15 , yf[i] - 5 , 10 , 10) ;g.fillOval(xf[i] + 25 , yf[i] - 5 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] - 5 , 10 , 10) ;g.fillOval(xf[i] - 5 , yf[i] + 35 , 10 , 10) ;g.fillOval(xf[i] + 5 , yf[i] + 35 , 10 , 10) ;g.fillOval(xf[i] + 25 , yf[i] + 35 , 10 , 10) ;g.fillOval(xf[i] + 35 , yf[i] + 35 , 10 , 10) ;g.fillRect(xf[i] - 20 , yf[i] + 15 , 40 , 10) ;g.fillOval(xf[i] + 30 , yf[i] + 5 , 10 , 10) ;g.fillOval(xf[i] + 30 , yf[i] + 25 , 10 , 10) ; }g.fillOval(dxf1[i] , dyf1[i] , 10 , 10 ) ;g.fillOval(dxf2[i] , dyf2[i] , 10 , 10 ) ;g.fillOval(dxf3[i] , dyf3[i] , 10 , 10 ) ;g.fillOval(dxf4[i] , dyf4[i] , 10 , 10 ) ;}}public void keyTyped(KeyEvent e) {}//键盘控制坦克的移动,发弹public void keyPressed(KeyEvent e) {color ++ ;if(e.getKeyCode() == KeyEvent.VK_UP) {op = 1 ;y = y - tankspeed ;dy = dy - tankspeed ;if(y <= 0) {y = y + tankspeed ;dy = dy + tankspeed ;}}if(e.getKeyCode() == KeyEvent.VK_RIGHT) {op = 2 ;x = x + tankspeed ;dx = dx + tankspeed ;if(x >= 560) {x = x - tankspeed ;dx = dx - tankspeed ;}}if(e.getKeyCode() == KeyEvent.VK_DOWN) {op = 3 ;y = y + tankspeed ;dy = dy + tankspeed ;if(y >= 560) {y = y - tankspeed ;dy = dy - tankspeed ;}}if(e.getKeyCode() == KeyEvent.VK_LEFT) { op = 4 ;x = x - tankspeed ;dx = dx - tankspeed ;if(x <= 0) {x = x + tankspeed ;dx = dx + tankspeed ;}}if(e.getKeyCode() == KeyEvent.VK_SPACE) { if(op == 1) {dx1 = dx ; dy1 = dy ;}if(op == 2) {dx2 = dx ; dy2 = dy ;}if(op == 3) {dx3 = dx ; dy3 = dy ;}if(op == 4) {dx4 = dx ; dy4 = dy ;}}this.repaint() ;}public void keyReleased(KeyEvent e) {}public void run() {for (int a = 0; a<60000; a++) {dy1 = dy1 - tankbullet ;dx2 = dx2 + tankbullet ;dy3 = dy3 + tankbullet ;dx4 = dx4 - tankbullet ;for (int i = 0; i<num; i++) {dyf1[i] = dyf1[i] - tankfbullet ;dxf2[i] = dxf2[i] + tankfbullet ;dyf3[i] = dyf3[i] + tankfbullet ;dxf4[i] = dxf4[i] - tankfbullet ;}//判断是否被击中for (int i = 0; i<num; i++) {if(dyf1[i]<y + 38 &&dyf1[i]>y +8 && dxf1[i]-x>-10 && dxf1[i]-x<40) { System.out.println ("被1击中") ;dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ;shengming = shengming - nandu ;}if(dxf2[i]>x+2 &&dxf2[i]<x+32 &&dyf2[i] - y >-10 && dyf2[i] - y <40 ) { System.out.println ("被2击中") ;dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ;shengming = shengming - nandu ;}if(dyf3[i]>y+2 && dyf3[i]< y+32 && dxf3[i]-x >-10&& dxf3[i]-x<40) { System.out.println ("被3击中") ;dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ;shengming = shengming - nandu ;}if(dxf4[i]>x+8 &&dxf4[i]<x+38 &&dyf4[i] - y >-10 && dyf4[i] - y <40 ) { System.out.println ("被4击中") ;dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ;shengming = shengming - nandu ;}}//判断是否击中敌军for (int i = 0; i<num; i++) {if(dy1<yf[i] + 38 &&dy1>yf[i] +8 && dx1-xf[i]>-10 && dx1-xf[i]<40) { System.out.println ("1击中") ;fenshu = fenshu + 100 ;xf[i] = (int)(Math.random() * 560 );yf[i] = (int)(Math.random() * 560 );}if(dx2>xf[i]+2 &&dx2<xf[i]+32 &&dy2 - yf[i] >-10 && dy2 - yf[i] <40 ) { System.out.println ("2击中") ;fenshu = fenshu + 100 ;xf[i] = (int)(Math.random() * 560 );yf[i] = (int)(Math.random() * 560 );}if(dy3>yf[i]+2 && dy3< yf[i]+32 && dx3-xf[i] >-10&& dx3-xf[i]<40) { System.out.println ("3击中") ;fenshu = fenshu + 100 ;xf[i] = (int)(Math.random() * 560 );yf[i] = (int)(Math.random() * 560 );}if(dx4>xf[i]+8 &&dx4<xf[i]+38 &&dy4 - yf[i] >-10 && dy4 - yf[i] <40 ) { System.out.println ("4击中") ;fenshu = fenshu + 100 ;xf[i] = (int)(Math.random() * 560 );yf[i] = (int)(Math.random() * 560 );}dxf[i] = xf[i] + 15 ;dyf[i] = yf[i] + 15 ;}//坦克的移动for (int i = 0; i<num; i++) {switch (opf[i]) {case 1:{yf[i]-- ;dyf[i] -- ;for (int s = 0; s<num; s++) {if(yf[i] <= 0) {yf[i] ++ ;dyf[i] ++ ;}}break;}case 2:{xf[i]++ ;dxf[i]++ ;for (int s = 0; s<num; s++) { if(xf[i] >= 560){xf[i] -- ;dxf[i] -- ;}}break;}case 3:{yf[i]++ ;dyf[i]++ ;for (int s = 0; s<num ; s++) { if(yf[i] >= 560){yf[i] -- ;dyf[i] -- ;}}break;}case 4:{xf[i]-- ;dxf[i]-- ;for (int s = 0; s<num; s++) { if(xf[i] <= 0){xf[i] ++ ;dxf[i] ++ ;}}break;}}}try{Thread.sleep(20) ;}catch(Exception e) {e.printStackTrace() ;}//坦克的开火if(a % 50 == 5) {if(Math.random()>0.5){for (int i = 0; i<2; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}if(a % 50 == 15) {if(Math.random()>0.5) {for (int i = 2; i<4; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}if(a % 50 == 25) {if(Math.random()>0.5){for (int i = 4; i<6; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}if(a % 50 == 35) {if(Math.random()>0.5){for (int i = 6; i<8; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}if(a % 50 == 45) {if(Math.random()>0.5) {for (int i = 8; i<10; i++) {if(opf[i] == 1) {dxf1[i] = dxf[i] ; dyf1[i] = dyf[i] ; }if(opf[i] == 2) {dxf2[i] = dxf[i] ; dyf2[i] = dyf[i] ; }if(opf[i] == 3) {dxf3[i] = dxf[i] ; dyf3[i] = dyf[i] ; }if(opf[i] == 4) {dxf4[i] = dxf[i] ; dyf4[i] = dyf[i] ; }}}}//坦克的随机移动if(a % 50 == 1 ) {for (int i = 0; i<2; i++) {if( Math.random() > 0.5 ) {if(Math.random() > 0.5){opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if(Math.random() > 0.5){opf[i] = 3 ;}else{opf[i] = 4 ;}}}}if(a % 50 == 11 ) {//坦克的随机移动for (int i = 2; i<4; i++) {if( Math.random() > 0.5 ) {if(Math.random() > 0.5){opf[i] = 1 ;}else{}}else{if(Math.random() > 0.5){ opf[i] = 3 ;}else{opf[i] = 4 ;}}}}if(a % 50 == 21 ) {//坦克的随机移动for (int i = 4; i<6; i++) { if( Math.random() > 0.5 ) { if(Math.random() > 0.5){ opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if(Math.random() > 0.5){ opf[i] = 3 ;}else{opf[i] = 4 ;}}}}if(a % 50 == 31 ) {//坦克的随机移动for (int i = 6; i<8; i++) { if( Math.random() > 0.5 ) { if(Math.random() > 0.5){ opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if(Math.random() > 0.5){ opf[i] = 3 ;}else{}}}}if(a % 50 == 41 ) {//坦克的随机移动for (int i = 8; i<10; i++) {if( Math.random() > 0.5 ) {if(Math.random() > 0.5){opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if(Math.random() > 0.5){opf[i] = 3 ;}else{opf[i] = 4 ;}}}}//重画if(shengming<=0){//弹出player1胜利对话框JOptionPane.showMessageDialog(null,"你结束了!!!","Game Over !", JOptionPane.ERROR_MESSAGE); //结束游戏System.exit(0) ;}this.repaint() ;}}}。

Java综合编程——坦克大战(15.1.5)

Java综合编程——坦克大战(15.1.5)

子弹类中的run()方法中
ActionEvent e
实现事件监听三步:
1. 2. 3.
确定事件源 确定监听类 监听对象的注册
举例——练习1

1. 2.tton,当该 按钮被按下后,系统给出提示 事件源JButton对象 监听器:
单独创建一个类负责监听 让JFrame负责监听
3.
把监听器加入到事件源中(注册监听) *事件对象,系统自动产生

坦克有方向, 画出所有方向的坦克
3、形成Tank类的子类


敌人坦克(EnemyTank)和我方坦克 (MyTank) 在这两个方法中覆盖父类的构造方法 将敌人坦克的颜色设置成蓝色 我方坦克设置成红色
4、


在MyPanel中绘制出一辆我方坦克,方向 向上 绘制出五辆敌人坦克,方向向下
在paint方法中用System.out.println(“调用 paint");



画直线:g.drawLine(10, 10, 40, 40); 画矩形边框:g.drawRect(60, 60, 100, 200); 画填充矩形:g.fill3DRect(50, 50, 30, 30, true); 设置颜色:g.setColor(Color.red);
基础知识
1. 2.
图形用户界面 Java绘图技术
1、图形用户界面

创建一个用户界面JFrame,取名为MainFrame 在其上添加一个JPanel,显示一个圆。
编程思路

(构建坦克大战主窗口)

坦克大战的主窗口是由一个JFrame构成的,因 为需要在上面作图,但是JFrame没有这个功能, 所以我们要在JFrame上再加上一个JPanel,在 JPanel上绘图。 我们在这里没有直接用JFrame和JPanel类,而 是定义另外两个类MainFrame和MainPanel,这 个两个类分别继承了JFrame和JPanel,然后再 由这两个类分别生成对象mf和mp,我们要在mp 对象上作图

坦克大战java源代码审批稿

坦克大战java源代码审批稿

坦克大战j a v a源代码 YKK standardization office【 YKK5AB- YKK08- YKK2C- YKK18】有些图片路径会出错要注意package ;import 坦克类class Tank{int x=0;int y=0;int color=0;int speed=1;int direct=0;boolean isLive=true;public Tank(int x,int y){=x;=y;}public int getX() {return x;}public void setX(int x) {= x;}public int getY() {return y;}public void setY(int y) {= y;}public int getDirect() {return direct;}public void setDirect(int direct) {= direct;}public int getColor() {return color;}public void setColor(int color) {= color;}};import .*;import .*;import .*;public class MyTankGame4 extends JFrame implements ActionListener{ MyPanel mp=null;MyStartPanel msp=null;quals("New Game")){(msp);mp=new MyPanel();Thread mt=new Thread(mp);();(mp);(mp);(true);}}}etImage"/.jpg"));etImage"/"));image2=().getImage"/"));image3=().getImage"/"));}//控制坦克移动public void keyPressed(KeyEvent arg0) {// TODO Auto-generated method stubif()=={}else if()== {}else if()== {}else if()== {}else if()== {=0;=0;}//发射子弹(连发5枚子弹)if {if()=={(),(),());}}//控制坦克不能跑出边界if if if if//面板重绘();}public void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}public void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}public void run() {while(true){try {(50);} catch (InterruptedException e) {// TODO Auto-generated catch block();}//不停地调用敌人是否打中自己坦克函数for(int i=0;i<();i++){et=(i);for(int j=0;j< {Shot enshot=if==true&&==true){(enshot, hero);}}}//不停地调用是否打中敌人坦克函数for(int i=0;i< {Shot s=if(s!=null&&==true){for(int j=0;j<();j++){EnemyTank et=(j);if(et!=null&&==true){(s, et);}}}}//面板重绘();}}}。

韩顺平java坦克大战1.0版本_源代码

韩顺平java坦克大战1.0版本_源代码

/**画坦克1。

0*/import java.awt.Color;import java.awt.Graphics;import java.awt.event。

KeyEvent;import java.awt。

event。

KeyListener;import java。

awt。

event.MouseEvent;import java。

awt。

event。

MouseListener;import java。

awt。

event.MouseMotionListener;import java.awt。

event。

WindowEvent;import java.awt。

event。

WindowListener;import javax。

swing。

JFrame;import javax.swing。

JPanel;public class MyTankGame extends JFrame{MyPanel mp=null;public static void main(String[] args){MyTankGame mtk=new MyTankGame();}public MyTankGame(){mp=new MyPanel();this.add(mp);//把面板加入窗体//注册监听this。

addMouseListener(mp);this.addKeyListener(mp);this。

addMouseMotionListener(mp);this.addWindowListener(mp);this.setTitle(”坦克大战");//窗体标题this。

setSize(600,400);//大小,宽,高(像素)this。

setLocation(300,300);//显示位置。

左边距,上边距//禁止用户改变窗口大小this。

setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);//显示}}//我的面板class MyPanel extends JPanel implements WindowListener,MouseListener,MouseMotionListener,KeyListener{//定义一个我的坦克Hero hero=null;Diren diren=null;public MyPanel(){hero=new Hero(300,200);diren=new Diren(100,0);//diren。

java坦克游戏代码

java坦克游戏代码

import javax.sound.sampled.*;import java.awt.*;import java.io.*;import java.util.*;import javax.swing.*;import java.awt.event.*;import javax.sound.sampled.*;public class tank1 extends JFrame implements ActionListener{ Myp mp=null;GKMB gkmb=null;JMenuBar cd=null;JMenu cd1=null;JMenuItem cdx1=null;JMenuItem cdx2,cdx3,cdx4;public static void main(String[] args){tank1 one=new tank1();}public tank1(){cd =new JMenuBar();cd1=new JMenu("游戏(G)");cd1.setMnemonic('G');cdx1=new JMenuItem("新游戏(N)");cdx1.setMnemonic('N');cdx1.addActionListener(this);cdx1.setActionCommand("dkd");cdx2=new JMenuItem("退出游戏(E)");cdx2.setMnemonic('E');cdx2.addActionListener(this);cdx2.setActionCommand("exit");cdx3=new JMenuItem("存盘退出(C)");cdx3.setMnemonic('C');cdx3.addActionListener(this);cdx3.setActionCommand("saveExit");cdx4=new JMenuItem("继续游戏(S)");cdx4.setMnemonic('S');cdx4.addActionListener(this);cdx4.setActionCommand("goongame");cd1.add(cdx1);cd1.add(cdx2);cd1.add(cdx3);cd1.add(cdx4);cd.add(cd1);//mp=new Myp();//this.add(mp);//this.addKeyListener(mp);//Thread one=new Thread(mp);//one.start();gkmb=new GKMB();this.add(gkmb);Thread gk=new Thread(gkmb);gk.start();this.setJMenuBar(cd);this.setTitle("坦克大战");this.setIconImage(new ImageIcon("image/bz2.jpg").getImage());this.setSize(750,550);this.setLocation(450,100);this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public void actionPerformed(ActionEvent e){if(e.getActionCommand().equals("dkd")){this.remove(gkmb);mp=new Myp("xinjian");this.add(mp);this.addKeyListener(mp);Thread one=new Thread(mp);one.start();this.setVisible(true);}else if(e.getActionCommand().equals("exit")){jilu.xieru();System.exit(0);}else if(e.getActionCommand().equals("saveExit")){jilu jl=new jilu();jl.setArr5(mp.arr);jilu.xieru();jl.cunpan();System.exit(0);}else if(e.getActionCommand().equals("goongame")){this.remove(gkmb);mp=new Myp("jixu");this.add(mp);this.addKeyListener(mp);Thread one=new Thread(mp);one.start();this.setVisible(true);}}}class GKMB extends JPanel implements Runnable{int time=0;public void paint(Graphics g){g.fill3DRect(0, 0, 500, 400, false);if(time%2==0){g.setColor(Color.YELLOW);Font myFont=new Font("华文行楷",Font.BOLD,38);g.setFont(myFont);g.drawString("第一关",150,200);}}public void run(){while(true){try{Thread.sleep(500);}catch(Exception e){}time++;this.repaint();}}}class Myp extends JPanel implements KeyListener,Runnable{ wdtank mt=null;drtank dt=null;Vector<drtank> arr=new V ector<drtank>();int shuzi=3;Vector<baozha> arr2=new V ector<baozha>();Vector<weizhi> arr6=new V ector<weizhi>();//Image tp1=null;//Image tp2=null;Image tp3=null;baozha bz=null;public Myp(String ss){if(ss.equals("xinjian")){mt=new wdtank(150,360);for(int i=0;i<shuzi;i++){dt=new drtank(i*232,0);Thread dt1=new Thread(dt);dt1.start();arr.add(dt);} dt.jieshou(arr);//调用接受方法System.out.println(arr.size());}else if(ss.equals("jixu")){System.out.println("dfdsfsdfs");mt=new wdtank(150,360);arr6=jilu.duqu();for(int i=0;i<arr6.size();i++){weizhi wz=arr6.get(i);dt=new drtank(wz.getX(),wz.getY());dt.setFx(wz.getFx());Thread dt1=new Thread(dt);dt1.start();arr.add(dt);}}tp3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bz3.jpg"));shengyin sy1=new shengyin("d:/容易受伤的女人.wav");Thread trd=new Thread(sy1);trd.start();}public void huajilu(Graphics g){this.drawtank(50, 410, g,1, 0);g.setColor(Color.BLACK);g.drawString(jilu.getDtsl()+"",90,430);this.drawtank(150,410, g,0,0);g.setColor(Color.BLACK);g.drawString(jilu.getMtsl()+"",190,430);this.drawtank(550,50, g,1,0);g.setColor(Color.BLACK);g.drawString(jilu.getTj()+"",600,70);g.setColor(Color.BLUE);Font ft1=new Font("华文行楷",Font.BOLD,20);g.setFont(ft1);g.drawString("敌人坦克消灭的数量", 520,30);}public void paint(Graphics g){super.paint(g);this.huajilu(g);g.drawImage(tp3, 1500,400, 55,55, this);g.setColor(Color.BLACK);g.fillRect(0, 0, 500, 400);if(mt.shengming==true){this.drawtank(mt.getX(),mt.getY(), g,0,mt.fx);}else if(mt.shengming==false){}for(int i=0;i<arr.size();i++){drtank dt=arr.get(i);if(dt.shengming==true){//bz=new baozha(dt.getX(),dt.getY());//arr2.add(bz);this.drawtank(dt.getX(),dt.getY(), g,1, dt.fx);for(int s=0;s<dt.dzd.size();s++){zidan zd=dt.dzd.get(s);if(zd!=null&&zd.flag==true)g.setColor(Color.BLUE);g.fill3DRect(zd.getX(), zd.getY(),5, 5,false);if(zd.flag==false){dt.dzd.remove(zd);break;}}}else if(dt.shengming==false){arr.remove(dt);//baozha bz1=arr2.get(i);//g.drawImage(tp3, bz1.getX(), bz1.getY(),55,55,this);//arr2.remove(bz1);}}for(int i=0;i<mt.arr1.size();i++){zidan zd=mt.arr1.get(i);if(zd!=null&&zd.flag==true){g.setColor(Color.YELLOW);g.fill3DRect(zd.getX(), zd.getY(),5, 5,false);}if(zd.flag==false){mt.arr1.remove(zd);break;}}}/* public void baozha1(baozha bz1,Graphics g){//爆炸方法System.out.println("进入爆炸方法");while(true){if(bz1.zhouqi>20){System.out.println("图片1画图成功");g.drawImage(tp1,bz1.getX(),bz1.getY(),55,55,this);sleep one=new sleep();Thread two=new Thread(one);two.start();}if(bz1.zhouqi>10&&bz1.zhouqi<21){System.out.println("图片2画图成功");g.drawImage(tp2, bz1.getX(),bz1.getY(),55,55,this);}if(bz1.zhouqi>0&&bz1.zhouqi<11){System.out.println("图片3画图成功");g.drawImage(tp3, bz1.getX(), bz1.getY(),55,55,this);}if(bz1.zhouqi==0){arr2.remove(bz1);break;}bz1.zhouqi--;System.out.println(bz1.zhouqi);}//////////////////System.out.println(bz1.zhouqi);if(bz1.zhouqi>200){g.drawImage(tp1,bz1.getX(),bz1.getY(),55,55,this);System.out.println("图片1画图成功");}else if(bz1.zhouqi>100&&bz1.zhouqi<200){System.out.println("图片2画图成功");g.drawImage(tp2, bz1.getX(),bz1.getY(),55,55,this);}else{System.out.println("图片3画图成功");g.drawImage(tp3, bz1.getX(), bz1.getY(),55,55,this);}if(bz1.smzq==false){arr2.remove(bz1);}}*/public void disappear(zidan zd,mytank dt){switch(dt.fx){case 0:if(zd.getX()>dt.getX()&&zd.getX()<dt.getX()+35&&zd.getY()>dt.getY()&&zd.getY()<dt.ge tY()+40){dt.shengming=false;zd.flag=false;if(dt instanceof drtank){jilu.dtjs();System.out.println("数量减少");jilu.tjsl();}else{jilu.mtjs();}}break;case 1:if(zd.getX()>dt.getX()&&zd.getX()<dt.getX()+40&&zd.getY()>dt.getY()&&zd.getY()<dt.ge tY()+35){dt.shengming=false;zd.flag=false;if(dt instanceof drtank){jilu.dtjs();jilu.tjsl();}else{jilu.mtjs();}}break;case 2:if(zd.getX()>dt.getX()&&zd.getX()<dt.getX()+35&&zd.getY()>dt.getY()&&zd.getY()<dt.ge tY()+40){dt.shengming=false;zd.flag=false;if(dt instanceof drtank){jilu.dtjs();jilu.tjsl();}else{jilu.mtjs();}}break;case 3:if(zd.getX()>dt.getX()&&zd.getX()<dt.getX()+40&&zd.getY()>dt.getY()&&zd.getY()<dt.ge tY()+35){dt.shengming=false;zd.flag=false;if(dt instanceof drtank){jilu.dtjs();jilu.tjsl();}else{jilu.mtjs();}}break;}}public void drawtank(int x,int y,Graphics g,int color,int fx){switch(color){case 0:g.setColor(Color.YELLOW);break;case 1:g.setColor(Color.BLUE);}switch(fx){case 0://向上g.fill3DRect(x,y,10,40,false);g.fill3DRect(x+10,y+12,15,20,false);g.fill3DRect(x+25,y,10,40,false);g.fillOval(x+9,y+12,15,15);g.drawLine(x+17,y+12,x+17,y-10);break;case 1://向左g.fill3DRect(x,y,40,10,false);g.fill3DRect(x+12,y+10,20,15,false);g.fill3DRect(x,y+25,40,10,false);g.fillOval(x+12,y+9,15,15);g.drawLine(x+12,y+16,x-10,y+16);break;case 2://xiag.fill3DRect(x,y,10,40,false);g.fill3DRect(x+10,y+8,15,20,false);g.fill3DRect(x+25,y,10,40,false);g.fillOval(x+9,y+12,15,15);g.drawLine(x+17,y+28,x+17,y+50);break;case 3://youg.fill3DRect(x,y,40,10,false);g.fill3DRect(x+8,y+10,20,15,false);g.fill3DRect(x,y+25,40,10,false);g.fillOval(x+12,y+9,15,15);g.drawLine(x+28,y+17,x+50,y+17);break;}}public void keyPressed(KeyEvent e) {if(e.getKeyCode()==KeyEvent.VK_UP){if(mt.getY()>0){this.mt.shang();this.mt.fx=0;}//System.out.println("向上");}else if(e.getKeyCode()==KeyEvent.VK_DOWN){ if(mt.getY()+40<400){this.mt.xia();this.mt.fx=2;}}else if(e.getKeyCode()==KeyEvent.VK_LEFT){ if(mt.getX()>0){this.mt.zuo();this.mt.fx=1;}}else if(e.getKeyCode()==KeyEvent.VK_RIGHT){ if(mt.getX()+40<500){this.mt.you();this.mt.fx=3;}}if(e.getKeyCode()==KeyEvent.VK_A){if(mt.arr1.size()<8){this.mt.fszd();}}}public void run(){while(true){try{Thread.sleep(50);}catch(Exception e){}for(int i=0;i<mt.arr1.size();i++){zidan zd=mt.arr1.get(i);if(zd.flag==true){for(int j=0;j<arr.size();j++){drtank dt=arr.get(j);if(dt.shengming==true){this.disappear(zd, dt);}}}}for(int i=0;i<arr.size();i++){drtank dt=arr.get(i);for(int j=0;j<dt.dzd.size();j++){zidan zd=dt.dzd.get(j);if(zd.flag==true){if(mt.shengming==true){this.disappear(zd, mt);}}}}this.repaint();}}public void keyReleased(KeyEvent e) {}public void keyTyped(KeyEvent e) {}}class mytank{int x,y;int sp=1;int fx=0;boolean shengming=true;public int getSp() {return sp;}public void setSp(int sp) {this.sp = sp;}public int getFx() {return fx;}public void setFx(int fx) {this.fx = fx;}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 mytank(int x,int y){this.x=x;this.y=y;}}class wdtank extends mytank{zidan zd=null;Vector<zidan> arr1=new Vector<zidan>();//zidanjihepublic wdtank(int x,int y){super(x,y);sp=9;}public void fszd(){//System.out.println("\tX:"+x+"\tY:"+y);switch(fx){case 0://shangzd=new zidan(x+17,y-10,0);arr1.add(zd);//System.out.println("绘图成功0下标传递成功");break;case 1://zuozd=new zidan(x-10,y+16,1);arr1.add(zd);//System.out.println("绘图成功1下标传递成功");break;case 2://xiazd=new zidan(x+17,y+50,2);arr1.add(zd);//System.out.println("向下发射");break;case 3://youzd=new zidan(x+50,y+17,3);arr1.add(zd);break;}Thread fs=new Thread(zd);fs.start();}public void shang(){y-=sp;}public void xia(){y+=sp;}public void zuo(){x-=sp;}public void you(){x+=sp;}}class drtank extends mytank implements Runnable{int time=0;zidan zd=null;Vector<zidan> dzd=new Vector<zidan>();Vector<drtank> dtarr=new V ector<drtank>();public drtank(int x,int y){super(x,y);sp=3;}public void jieshou(Vector<drtank> dtarr){this.dtarr=dtarr;}public boolean tkpz(){boolean b=false;switch(this.fx){case 0:for(int i=0;i<dtarr.size();i++){drtank dt=dtarr.get(i);if(dt!=this){if(dt.fx==0||dt.fx==2){if(this.getX()>=dt.getX()&&this.getX()<=dt.getX()+25&&this.getY()>=dt.getY()&&this.get Y()<=dt.getY()+40){return true;}if(this.getX()+25>=dt.getX()&&this.getX()<=dt.getX()+25&&this.getY()>=dt.getY()&&this .getY()<=dt.getY()+40){return true;}}if(dt.fx==1||dt.fx==3){if(this.getX()>=dt.getX()&&this.getX()<=dt.getX()+40&&this.getY()>=dt.getY()&&this.getY()<=dt.getY()+25){return true;}if(this.getX()+25>=dt.getX()&&this.getX()+25<=dt.getX()+40&&this.getY()>=dt.getY()&&this. getX()<=dt.getY()+25){return true;}}}}break;case 1:for(int i=0;i<dtarr.size();i++){drtank dt=dtarr.get(i);if(dt!=this){if(dt.fx==0||dt.fx==2){if(this.getX()>=dt.getX()&&this.getX()<=dt.getX()+25&&this.getY()>=dt.getY()&&this.get Y()<=dt.getY()+40){return true;}if(this.getX()+40>=dt.getX()&&this.getX()+40<=dt.getX()+25&&this.getY()>=dt.getY()& &this.getY()<=dt.getY()+40){return true;}}if(dt.fx==1||dt.fx==3){if(this.getX()>=dt.getX()&&this.getX()<=dt.getX()+40&&this.getY()>=dt.getY()&&this.get Y()<=dt.getY()+25){return true;}if(this.getX()+40>=dt.getX()&&this.getX()+40<=dt.getX()+40&&this.getY()>=dt.getY()&&this. getY()<=dt.getY()+25){return true;}}}}break;case 2:for(int i=0;i<dtarr.size();i++){drtank dt=dtarr.get(i);if(dt!=this){if(dt.fx==0||dt.fx==2){if(this.getX()>=dt.getX()&&this.getX()<=dt.getX()+25&&this.getY()>=dt.getY()&&this.get Y()<=dt.getY()+40){return true;}if(this.getX()+25>=dt.getX()&&this.getX()<=dt.getX()+25&&this.getY()>=dt.getY()&&this.get Y()<=dt.getY()+40){return true;}}if(dt.fx==1||dt.fx==3){if(this.getX()>=dt.getX()&&this.getX()<=dt.getX()+40&&this.getY()>=dt.getY()&&this.get Y()<=dt.getY()+25){return true;}if(this.getX()+25>=dt.getX()&&this.getX()+25<=dt.getX()+40&&this.getY()>=dt.getY()&& this.getX()<=dt.getY()+25){return true;}}}}break;case 3:for(int i=0;i<dtarr.size();i++){drtank dt=dtarr.get(i);if(dt!=this){if(dt.fx==0||dt.fx==2){if(this.getX()>=dt.getX()&&this.getX()<=dt.getX()+25&&this.getY()>=dt.getY()&&this.get Y()<=dt.getY()+40){return true;}if(this.getX()+40>=dt.getX()&&this.getX()+40<=dt.getX()+25&&this.getY()>=dt.getY()&&this. getY()<=dt.getY()+40){return true;}}if(dt.fx==1||dt.fx==3){if(this.getX()>=dt.getX()&&this.getX()<=dt.getX()+40&&this.getY()>=dt.getY()&&this.get Y()<=dt.getY()+25){return true;}if(this.getX()+40>=dt.getX()&&this.getX()+40<=dt.getX()+40&&this.getY()>=dt.getY()&&this. getY()<=dt.getY()+25){return true;}}}}break;}return b;}public void run(){while(true){this.fx=(int)(Math.random()*4);switch(this.fx){case 0:for(int i=0;i<30;i++){if(y>0&&!tkpz()){y-=sp;}try{Thread.sleep(50);}catch(Exception e){}}break;case 1:for(int i=0;i<30;i++){if(x>0&&!tkpz()){x-=sp;}try{Thread.sleep(50);}catch(Exception e){}}break;case 2:for(int i=0;i<30;i++){if(y<360&&!tkpz()){y+=sp;}try{Thread.sleep(50);}catch(Exception e){}break;case 3:for(int i=0;i<30;i++){if(x<400&&!tkpz()){x+=sp;}try{Thread.sleep(50);}catch(Exception e){}}break;}if(this.shengming==false){break;}time++;if(time%2==0){if(shengming==true){if(dzd.size()<3){switch(fx){case 0:zd=new zidan(x+17,y-10,0);dzd.add(zd);break;case 1:zd=new zidan(x-10,y+16,1);dzd.add(zd);break;case 2:zd=new zidan(x+17,y+50,2);dzd.add(zd);break;case 3:zd=new zidan(x+50,y+17,3);dzd.add(zd);break;}Thread fs=new Thread(zd);fs.start();}}}}}}class zidan implements Runnable{int x,y,fx;int sp=8;boolean flag=true;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 zidan(int x,int y,int fx){this.x=x;this.y=y;this.fx=fx;}public void run(){//System.out.println("调用run方法子弹起始地点坐标"+"\tX:"+x+"\tY:"+y);while(true){//System.out.println("0dongledkhjksa");try{Thread.sleep(50);}catch(Exception e){}switch(fx){case 0:y-=sp;//System.out.println("run 方法子弹向上");break;case 1:x-=sp;//System.out.println("run 方法子弹向左");break;case 2:y+=sp;//System.out.println(y);//System.out.println("run 方法子弹向下");break;case 3:x+=sp; //System.out.println("run 方法子弹向右");break;}if(x<0||x>500||y<0||y>400){flag=false;break;}}}}class baozha{int x,y;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;}int zhouqi=30;//boolean smzq=true;public baozha(int x,int y){this.x=x;this.y=y;}}class jilu{//记录敌方,我方数量的方法private static int mtsl=2;private static int dtsl=10;private static int tj=0;private static FileReader fr=null;private static BufferedReader br=null;private static FileWriter fw=null;private static BufferedWriter bw=null;private static Vector<drtank> arr5=new Vector<drtank>(); private static Vector<weizhi> arr6=new Vector<weizhi>(); public static Vector<weizhi> getArr6() {return arr6;}public static void setArr6(Vector<weizhi> arr6) { jilu.arr6 = arr6;}public static Vector<drtank> getArr5() {return arr5;}public static void setArr5(Vector<drtank> arr5) { jilu.arr5 = arr5;}public static int getTj() {return tj;}public static void setTj(int tj) {jilu.tj = tj;}public static int getDtsl() {return dtsl;}public static void setDtsl(int dtsl) {jilu.dtsl = dtsl;}public static int getMtsl() {return mtsl;}public static void setMtsl(int mtsl) {jilu.mtsl = mtsl;}public static void dtjs(){dtsl--;}public static void mtjs(){mtsl--;}public static void tjsl(){tj++;}public static Vector<weizhi> duqu(){try{fr=new FileReader("d:/dtank.txt");br=new BufferedReader(fr);String s=null;System.out.println(s);//tj=Integer.parseInt(s);while((s=br.readLine())!=null){String[] sz=s.split(" ");weizhi wz=new weizhi(Integer.parseInt(sz[0]),Integer.parseInt(sz[1]),Integer.parseInt(sz[2]));arr6.add(wz);System.out.println(arr6.size()+"sdsf");}}catch(Exception e){}finally{try{fr.close();br.close();}catch(Exception e){}}//System.out.println(arr6.size());return arr6;}public static void xieru(){//存入杀敌总数try{fw=new FileWriter("d:/dtank.txt");bw=new BufferedWriter(fw);bw.write((tj+""));bw.newLine();bw.flush();}catch(Exception e){}finally{try{fw.close();bw.close();}catch(Exception e){}}}public void cunpan(){try{fw=new FileWriter("d:/dtank.txt");bw=new BufferedWriter(fw);//bw.write("敌方死亡数量为:"+(tj+""));//bw.newLine();for(int i=0;i<arr5.size();i++){drtank dt=arr5.get(i);if(dt.shengming==true){String str=dt.getX()+""+" "+dt.getY()+""+" "+dt.fx+"";bw.write(str);bw.newLine();}}bw.flush();}catch(Exception e){}finally{try{fw.close();bw.close();}catch(Exception e){}}}}class weizhi{private int x,y,fx;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 int getFx() {return fx;}public void setFx(int fx) {this.fx = fx;}public weizhi(int x,int y,int fx){this.x=x;this.y=y;this.fx=fx;}}class shengyin implements Runnable{private String sy;public String getSy() {return sy;}public void setSy(String sy) {this.sy = sy;}public shengyin(String a){this.sy=a;}public void run(){File fl=new File(sy);//把音频文件封装成数据做对象使用AudioInputStream sysrl=null;try{sysrl=AudioSystem.getAudioInputStream(fl);//从提供的File 获得音频输入流。

java坦克大战源代码

java坦克大战源代码

package com.cwj.tankGame;import javax.sound.sampled.*;import java.io*;import java.awt.*;import java.io.IOException;import java.util.*;import javax.swing,*;import javax.imageio.ImageIO;import javax.swing.*;class AePlayWave extends Thread {private String filename;public AePlayWave(String wavfile) {filename = wavfile;}public void run() {File soundFile = new File(filename);AudioInputStream audioInputStream = null;try {audioInputStream = AudioSystem.getAudioInputStream(soundFile);} catch (Exception e1) {e1.printStackTrace();return;}AudioFormat format = audioInputStream.getFormat(); SourceDataLine auline = null; info = new (SourceDataLine.class, format); try {auline = (SourceDataLine) AudioSystem.getLine(info);auline.open(format);} catch (Exception e) {e.printStackTrace();return;}auline.start();int nBytesRead = 0;//这是缓冲byte[] abData = new byte[512];try {while (nBytesRead != -1) {nBytesRead = audioInputStream.read(abData, 0, abData.length); if (nBytesRead >= 0)auline.write(abData, 0, nBytesRead);}} catch (IOException e) {e.printStackTrace();return;} finally {auline.drain();auline.close();}}}class Bomb{int x;int y;int lifeTime = 10;boolean isLive=true;public Bomb(int x,int y){this.x=x;this.y=y;}public void lifeDown(){if(lifeTime>0){lifeTime--;}else{this.isLive=false;}}}class EnemyTank extends Tank implements Runnable{int n=1;//敌方坦克转弯n次发射一颗子弹int MaxShot = 10;int runDistance = 10;//变一次方向前进的距离//定义一个向量可以访问MyPanel上所有地方坦克Vector<EnemyTank> ets =new Vector<EnemyTank>();Vector<Shot> ss = new Vector<Shot>();public void setEts(Vector<EnemyTank> v){this.ets=v;}public int abs(int x){if(x>0)return x;elsereturn -x;}public boolean isTouchOther(){switch(this.direction){case 0://上for(int i=0;i<ets.size();i++){EnemyTank t = ets.get(i);if(t!=this)//不是自己这辆坦克{if(abs(this.x-t.x)<=40&&this.y>t.y&&this.y-t.y<=40) {return true;}}}break;case 2://下for(int i=0;i<ets.size();i++){EnemyTank t = ets.get(i);if(t!=this)//不是自己这辆坦克{if(abs(this.x-t.x)<=40&&t.y>this.y&&t.y-this.y<=40) {return true;}}}break;case 1://左for(int i=0;i<ets.size();i++){EnemyTank t = ets.get(i);if(t!=this)//不是自己这辆坦克{if(abs(this.y-t.y)<=40&&this.x>t.x&&this.x-t.x<=40) {return true;}}}break;case 3://右for(int i=0;i<ets.size();i++){EnemyTank t = ets.get(i);if(t!=this)//不是自己这辆坦克{if(abs(this.y-t.y)<=40&&this.x<t.x&&t.x-this.x<=40) {return true;}}}break;}return false;}public EnemyTank(int x,int y){super(x,y);}int time=0;public void sleep(){try{Thread.sleep(50);}catch(Exception e){e.printStackTrace();}}public void run() {while(true){switch(direction){case 0:for(int i =0;i<this.runDistance;i++){if(y>20&&!this.isTouchOther())y-=speed;this.sleep();}break; case 1:for(int i =0;i<this.runDistance;i++){if(x>20&&!this.isTouchOther())x-=speed;this.sleep();}break; case 2:for(int i =0;i<this.runDistance;i++){if(y<580&&!this.isTouchOther())y+=speed;this.sleep();}break; case 3:for(int i =0;i<this.runDistance;i++){if(x<780&&!this.isTouchOther())x+=speed;this.sleep();}break; }this.direction=(int)(Math.random()*4);if(this.isLive==false){break;}else{time++;if(time%n==0)if(ss.size()<MaxShot){Shot s = new Shot(x,y);s.setDirection(direction);ss.add(s);Thread t = new Thread(s);t.start();}}}}}class MyTank extends Tank{int MAXSHOT=20;public int getMAXSHOT() {return MAXSHOT;}public void setMAXSHOT(int mAXSHOT) { MAXSHOT = mAXSHOT;}Shot shot=null;Vector<Shot> ss = new Vector<Shot>(); public MyTank(int x,int y){super(x,y);}public void fire(){if(this.isLive==true){shot = new Shot(x,y);ss.add(shot);Thread t = new Thread(shot);t.start();shot.setDirection(this.direction);}}public void moveUp(){if(y>20)y-=speed;}public void moveLeft(){if(x>20)x-=speed;}public void moveDown(){if(y<580)y+=speed;}public void moveRight(){if(x<780)x+=speed;}class Node {int x;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 int getDirection() {return direction;}public void setDirection(int direction) { this.direction = direction;}int y;int direction;public Node(int x,int y){this.x=x;this.y=y;}}class Record {//记录每关有多少敌人private static int etNum=20;private static int sum = 0;private static FileWriter fw=null;private static BufferedWriter bw = null; private static FileReader fr = null; private static BufferedReader br = null; private static Vector<Node> nodes=null; public static Vector<Node> getNodes() { return nodes;public static void setNodes(Vector<Node> nodes) { Record.nodes = nodes;}public static Vector<EnemyTank> ets = null;public static Vector<EnemyTank> getEts() {return ets;}public static void setEts(Vector<EnemyTank> ets) { Record.ets = ets;}public static void restoreRecord(){try {nodes = new Vector<Node>();File file = new File("e:\\tankGame.txt");if(!file.isDirectory()){if(file.createNewFile())System.out.println("成功创建文件e:\\tankGame.txt"); }fr = new FileReader("e:\\tankGame.txt");br = new BufferedReader(fr);String strSum = br.readLine();if(strSum!=null)sum = Integer.parseInt(strSum);else return;String str="";while((str=br.readLine())!=null){String []xyd=str.split(" ");int x,y,direction;x = Integer.parseInt(xyd[0]);y = Integer.parseInt(xyd[1]);direction = Integer.parseInt(xyd[2]);Node node = new Node(x,y);node.setDirection(direction);nodes.add(node);}for(int i=0;i<nodes.size();i++){System.out.println(nodes.get(i).x+" "+nodes.get(i).y+" "+nodes.get(i).direction); }} catch (Exception e) {e.printStackTrace();}finally{try {if(br!=null)br.close();if(fr!=null)fr.close();} catch (IOException e) {e.printStackTrace();}}}public static void keepRecord(){try {fw = new FileWriter("e:\\tankGame.txt");bw = new BufferedWriter(fw);bw.write(sum+"\r\n");for(int i =0;i<ets.size();i++){EnemyTank et = ets.get(i);if(et.isLive==true){String record = et.x+" "+et.y+" "+et.getDirection()+"\r\n";bw.write(record);}}} catch (Exception e) {e.printStackTrace();}finally{try {if(bw!=null)bw.close();if(fw!=null)fw.close();} catch (IOException e) {e.printStackTrace();}}}public static int getSum() {return sum;}public static void setSum(int sum) { Record.sum = sum;}public static void addSum(){sum++;}public static int getEtNum() {return etNum;}public static void setEtNum(int etNum) { Record.etNum = etNum;}public static int getMyLife() {return myLife;}public static void setMyLife(int myLise) { Record.myLife = myLise;}//生命数private static int myLife=3;public static void reduceEtNum(){etNum--;}public static void reduceMyLife(){myLife--;}}class Shot implements Runnable{int x;int speed=5;int y;int direction;boolean isLive=true;public void run(){while(true){try{Thread.sleep(100);}catch(Exception e){e.printStackTrace();}switch(this.direction){case 0:y-=speed;break;case 1:x-=speed;break;case 2:y+=speed;break;case 3:x+=speed;break;}if(x<0||x>800||y<0||y>600){this.isLive=false;break;}}//while}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 int getDirection() {return direction;}public void setDirection(int direction) { this.direction = direction;}public Shot(int x,int y){this.x=x;this.y=y;}}class Tank{boolean isLive=true;int x=0;int y=0;int color;public int getColor() {return color;}public void setColor(int color) {this.color = color;}int speed=3;int direction=0;//0上1左2下3右public int getSpeed() {return speed;}public void setSpeed(int speed) { this.speed = speed;}public int getDirection() {return direction;}public void setDirection(int direction) { this.direction = direction;}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;}}public class TankGame extends JFrame implements ActionListener{ MyPanel mp=null;MyStartPanel msp = null;JMenuBar jmb =null;JMenu jm1=null;JMenuItem jmi11 =null;JMenuItem jmi12 = null;JMenuItem jmi13 = null;JMenuItem jmi14 = null;public static void main(String[]args){TankGame t = new TankGame();}public TankGame(){/*mp=new MyPanel();this.add(mp);Thread t = new Thread(mp);t.start();this.addKeyListener(mp);*/jmb = new JMenuBar();jm1 = new JMenu("游戏(G)");jm1.setMnemonic('G');jmi11 = new JMenuItem("开始游戏(N)");jmi11.addActionListener(this);jmi11.setActionCommand("newgame");jmi11.setMnemonic('N');jmi12 = new JMenuItem("退出游戏(E)");jmi12.addActionListener(this);jmi12.setActionCommand("exitgame");jmi12.setMnemonic('E');jmi13 = new JMenuItem("退出并保存(O)");jmi13.addActionListener(this);jmi13.setActionCommand("exitandsave");jmi13.setMnemonic('O');jmi14 = new JMenuItem("继续游戏(S)");jmi14.addActionListener(this);jmi14.setActionCommand("continue");jmi14.setMnemonic('S');jm1.add(jmi11);jm1.add(jmi13);jm1.add(jmi14);jm1.add(jmi12);jmb.add(jm1);this.setJMenuBar(jmb);msp = new MyStartPanel();Thread t = new Thread(msp);t.start();this.add(msp);this.setSize(900, 700);this.setLocationRelativeTo(null);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setTitle("坦克大战欢迎加qq1036624975交流学习编程爱好者学习交流群294787264");this.setVisible(true);}public void actionPerformed(ActionEvent e) {if(e.getActionCommand().equals("newgame")){if(mp!=null)this.remove(mp);mp = new MyPanel("newGame");Thread t = new Thread(mp);t.start();this.remove(msp);this.add(mp);this.addKeyListener(mp);this.setVisible(true);AePlayWave apw = new AePlayWave("e://tank.wav"); new Thread(apw).start();}else if(e.getActionCommand().equals("exitgame")){System.exit(0);}else if(e.getActionCommand().equals("exitandsave")) {Record.setEts(mp.et);Record.keepRecord();System.exit(0);}else if(e.getActionCommand().equals("continue")){Record.restoreRecord();if(mp!=null)this.remove(mp);mp = new MyPanel("oldGame");Thread t = new Thread(mp);t.start();this.remove(msp);this.add(mp);this.addKeyListener(mp);this.setVisible(true);}}}class MyStartPanel extends JPanel implements Runnable {int count=0;public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 800, 600);if(count%6==0)g.setColor(Color.YELLOW);else if(count%6==1)g.setColor(Color.BLUE);else if(count%6==2)g.setColor(Color.CYAN);else if(count%6==3)g.setColor(Color.GREEN);else if(count%6==4)g.setColor(Color.ORANGE);else if(count%6==5)g.setColor(Color.PINK);g.setFont(new Font("黑体",Font.PLAIN,100));g.drawString("第一关",250,300);g.setFont(new Font("黑体",Font.PLAIN,20));g.drawString("w上s下a左d右j发射子弹", 0, 20);if(count>20000)count=0;}public void run() {while(true){try {Thread.sleep(300);} catch (Exception e) {e.printStackTrace();}count++;this.repaint();}}}class MyPanel extends JPanel implements KeyListener,Runnable {Image bomb1=null;Image bomb2=null;Image bomb3=null;MyTank mt = null;//我的坦克Vector<EnemyTank>et=new Vector<EnemyTank>();Vector<Bomb>bombs = new Vector<Bomb>();Vector<Node>nodes =null;int enemyTankNum=20;public MyPanel(String ifNew){Record.restoreRecord();mt = new MyTank(300,570);mt.setSpeed(7);mt.setColor(0);//初始化敌人的坦克if(ifNew.equals("newGame")){for(int i =0;i<enemyTankNum;i++){EnemyTank tank = null;if(i<10){tank=new EnemyTank((i+1)*70,20);}else{tank = new EnemyTank(((i-9))*70,80);}tank.setDirection(2);Thread t = new Thread(tank);t.start();Shot s = new Shot(tank.x,tank.y);s.setDirection(tank.direction);new Thread(s).start();tank.ss.add(s);tank.setColor(1);et.add(tank);tank.setEts(et);}}else if(ifNew.equals("oldGame")){nodes=Record.getNodes();for(int i =0;i<nodes.size();i++){Node node = nodes.get(i);EnemyTank tank = null;tank = new EnemyTank(node.getX(),node.getY()); tank.setDirection(node.getDirection());Thread t = new Thread(tank);t.start();Shot s = new Shot(tank.x,tank.y);s.setDirection(tank.direction);new Thread(s).start();tank.ss.add(s);tank.setColor(1);et.add(tank);tank.setEts(et);}}//三张图片,组成一颗炸弹try {bomb1=ImageIO.read(new File("image/bomb_1.gif"));bomb2=ImageIO.read(new File("image/bomb_2.gif"));bomb3=ImageIO.read(new File("image/bomb_3.gif"));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//以下方式加载图片第一次爆炸效果不明显/*bomb1=Toolkit.getDefaultToolkit().getImage("image/bomb_1.gif"); bomb2=Toolkit.getDefaultToolkit().getImage("image/bomb_2.gif"); bomb3=Toolkit.getDefaultToolkit().getImage("image/bomb_3.gif");*/ }public void showMessage(Graphics g){this.paintTank(825, 20, g, 0, 1);this.paintTank(825, 80, g, 0, 0);g.setColor(Color.BLACK);g.drawString("x"+Record.getEtNum(),850,20);g.drawString("x"+Record.getMyLife(), 850, 80);g.setFont(new Font("华文彩云",Font.BOLD,20));g.drawString("总成绩", 2, 620);g.drawString(""+Record.getSum(), 76, 620);}public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 800, 600);this.showMessage(g);if(mt.isLive==true)paintTank(mt.getX(),mt.getY(),g,mt.getDirection(),mt.getColor());//画敌人坦克for(int i=0;i<et.size();i++){EnemyTank t = et.get(i);if(t.isLive==true){paintTank(t.getX(),t.getY(),g,t.getDirection(),t.getColor());for(int j = 0;j<t.ss.size();j++)//画子弹{if(s.isLive==true){g.setColor(Color.RED);g.fillRect(s.getX(), s.getY(), 5,5);}else{t.ss.remove(s);}}}else{et.remove(t);}}//爆炸效果for(int i=0;i<bombs.size();i++){Bomb b = bombs.get(i);if(b.lifeTime>6){g.drawImage(bomb1,b.x,b.y,40,40,this);}else if(b.lifeTime>3){g.drawImage(bomb2,b.x,b.y,40,40,this);}else{g.drawImage(bomb3,b.x,b.y,40,40,this);}b.lifeDown();if(b.lifeTime==0){bombs.remove(b);}}for(int i =0;i<mt.ss.size();i++)//我的画子弹{Shot s = mt.ss.get(i);if(s!=null&&s.isLive==true){g.setColor(Color.YELLOW);g.fillRect(s.getX(), s.getY(),5, 5);}if(s.isLive==false) //子弹清空,才能打下一发子弹{}}}//被攻击public void hitMyTank(){for(int i=0;i<et.size();i++){EnemyTank e=et.get(i);for(int j=0;j<e.ss.size();j++){Shot enemyShot = e.ss.get(j); boolean res=false;res = this.isHitTank(enemyShot, mt); if(res==true)Record.reduceMyLife();}}}//攻击敌方坦克public void hitEnemyTank(){for(int i=0;i<mt.ss.size();i++){Shot shot = mt.ss.get(i);if(shot.isLive==true){for(int j =0;j<et.size();j++){EnemyTank etank = et.get(j);if(etank.isLive==true){boolean res=false;res=this.isHitTank(shot, etank);if(res==true){Record.reduceEtNum();Record.addSum();}}}}}}//判断子弹是否击中坦克public boolean isHitTank(Shot shot,Tank etank){boolean res=false;if(shot.x>etank.x-20&&shot.x<etank.x+20&&shot.y>etank.y-20&&shot.y<etank.y+20&&et ank.isLive==true)//子弹击中{shot.isLive=false;etank.isLive=false;Bomb bomb = new Bomb(etank.getX()-20,etank.getY()-20);bombs.add(bomb);res = true;}return res;}public void paintTank(int x,int y,Graphics g,int direction,int type){switch(type)//判断坦克类型{case 0:g.setColor(Color.yellow);//自己的break;case 1:g.setColor(Color.RED);//敌人的break;}switch(direction){case 0://上g.fillRect(x-20, y-20, 40, 40);g.fill3DRect(x-5, y-20, 10, 20,false);break;case 1://左g.fillRect(x-20, y-20, 40, 40);g.fill3DRect(x-20, y-5, 20, 10,false);break;case 2://下g.fillRect(x-20, y-20, 40, 40);g.fill3DRect(x-5, y, 10, 20,false);break;case 3://右g.fillRect(x-20, y-20, 40, 40);g.fill3DRect(x, y-5, 20, 10,false);break;}}@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stub}@Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stubif(e.getKeyCode()==KeyEvent.VK_J)//发射子弹{if(this.mt.ss.size()<this.mt.getMAXSHOT()) {this.mt.fire();}}if(e.getKeyCode()==KeyEvent.VK_W){mt.setDirection(0);this.mt.moveUp();}else if(e.getKeyCode()==KeyEvent.VK_A) {mt.setDirection(1);this.mt.moveLeft();}else if(e.getKeyCode()==KeyEvent.VK_S) {mt.setDirection(2);this.mt.moveDown();}else if(e.getKeyCode()==KeyEvent.VK_D) {mt.setDirection(3);this.mt.moveRight();}this.repaint();}@Overridepublic void keyReleased(KeyEvent e) {// TODO Auto-generated method stub}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(50);//50毫秒重绘一次} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.hitEnemyTank();//判断己方坦克是否击中敌方坦克this.hitMyTank();//判断敌方坦克是否击中己方坦克this.repaint();}}}。

Java游戏开发之坦克大战代码

Java游戏开发之坦克大战代码

Java游戏开发之坦克大战代码标题:Java游戏开发之坦克大战代码关键词:Java坦克大战,坦克大战Java代码这是一个Java坦克大战的源码,实现了大部分功能,是学习Java绘图技术的好例子主类:package com.qq.TankGame;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Paint;import java.awt.Panel;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Vector;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JTextArea;/////**// * 功能:java绘图// * @author Administrator// *// */public class TankGame extends JFrame implements ActionListener{MyPanel mp = null;myStartPanel msp = null;EnemyTask em = null;JMenuBar jmb = null;JMenu jm = null;JMenuItem jmi1 = null;JMenuItem jmi2 = null;JMenuItem jmi3 = null;public static void main(String[] args) {TankGame tankGame = new TankGame();}public TankGame(){jmb = new JMenuBar();jm = new JMenu("游戏(G)");jm.setMnemonic('G');jmi1 = new JMenuItem("开始游戏(S)");jmi1.setMnemonic('S');jmi1.addActionListener(this);jmi1.setActionCommand("newGame");jmi2 = new JMenuItem("继续游戏(O)");jmi2.setMnemonic('O');jmi3 = new JMenuItem("退出游戏(X)");jmi3.setMnemonic('X');jmi3.addActionListener(this);jmi3.setActionCommand("exit");//启动mp线程//em = new EnemyTask();//mp = new MyPanel();msp = new myStartPanel();this.setJMenuBar(jmb);this.add(msp);//this.add(mp);jmb.add(jm);jm.add(jmi1);jm.add(jmi2);jm.add(jmi3);this.setSize(600,500);//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true);//this.addKeyListener(mp);Thread t1 = new Thread(msp);t1.start();// Thread t = new Thread(mp);// t.start();}@Overridepublic void actionPerformed(ActionEvent arg0) {if(arg0.getActionCommand().equals("newGame")){mp = new MyPanel();Thread t = new Thread(mp);t.start();this.remove(msp);this.remove(mp);this.add(mp);this.setVisible(true);this.addKeyListener(mp);//Recoder.getRecording();}else if(arg0.getActionCommand()== "exit"){//Recoder.KeepRecording();Recoder.KeepExit();//KeepExit();System.exit(0);}}}class myStartPanel extends JPanel implements Runnable{ int times = 0;public void paint(Graphics g ){super.paint(g);g.fillRect(0, 0, 400, 300);if(times%2 ==0){g.setColor(Color.BLUE);Font f = new Font("华文新魏", Font.BOLD, 30);g.setFont(f);g.drawString("stage:1", 150, 150);}}@Overridepublic void run() {while(true){try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}this.repaint();times ++;}}}class MyPanel extends JPanel implements KeyListener,Runnable{ int [] TanksX = new int[20];int [] TanksY = new int[20];int [] ShotsX = new int[100];int [] ShotsY = new int[100];// int [][]Tanks = new int[20][2];// int [][]Shots = new int[20][2];int [] ETdirects = new int[20];int [] HeroShotsX = new int[10];int [] HeroShotsY = new int[10];static Hero hero = null;EnemyTask et = null;shot s = null;boolean isPaintShot = true;int a = 0, b = 0 , c = 0;int [] directs = new int [10];static //敌人坦克集合Vector<EnemyTask> ets = new Vector<EnemyTask>();int enSize = 3; //敌人坦克初始数量int enSizes = 5; //敌人坦克画面总数量int hintEnemyTanks = 0;//击中敌人坦克数量public void showInfo(Graphics g ){//画提示信息//画出提出坦克this.drawTank(80, 330, g, 0, 1);this.drawTank(160, 330, g, 0, 0);g.setColor(Color.BLACK);g.drawString(Recoder.getEnNum() + "", 105, 350);g.drawString(Recoder.getMyLife() + "", 185, 350);//画出成绩g.setColor(Color.BLACK);Font f = new Font("宋体", Font.BOLD, 15);g.setFont(f);g.drawString("你的总成绩:", 400, 20);this.drawTank(410, 30, g, 0, 1);g.drawString((20 - Recoder.getEnNum()) + "", 435, 50);}public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 400, 300);this.showInfo(g);//画出提示信息//自己坦克if(hero.isLive == true){this.drawTank(hero.getX(), hero.getY(), g, hero.direct, hero.type); }else{if(Recoder.getMyLife() > 0){hero = new Hero(30, 270 ,0,0,10 , true);hero.isLive = true;}}//画出敌人坦克for(int i = 0; i <ets.size(); i++){EnemyTask et = ets.get(i);if(!et.isLive){ets.remove(i);if(Recoder.getEnNum() >0){this.drawTank(50, 0, g, 1, 1);ets.add(et);//et.isLive = true;Thread t = new Thread(et);t.start();}// if(Recoder.getEnNum() > 0){// et.isLive = true;// }}if(et.isLive){this.drawTank(et.getX(), et.getY(),g, et.direct, et.type);System.out.println("et.ss.size()"+et.ss.size());for(int j = 0; j < et.ss.size(); j++){//敌人坦克子弹s = et.ss.get(j);if(s.isLive){if(isPaintShot){g.fill3DRect(s.x, s.y, 5, 10, false);}}else{et.ss.remove(j);}}}// if(!et.isLive){// ets.remove(i);// }}//画出子弹for(int i = 0; i< hero.ss.size(); i++){if(hero.ss.get(i)!= null && hero.ss.get(i).isLive == true){ g.fill3DRect(hero.ss.get(i).x, hero.ss.get(i).y, 5, 10, false); }if(hero.ss.get(i).isLive == false){hero.ss.remove(hero.ss.get(i));}}}// public void hintTank2(shot s , Hero et){// switch (et.direct) {// case 0:// case 1:// if(s.x < et.x + 20 && s.x > et.x// && s.y < et.y + 30 && s.y > et.y){// s.isLive = false;// et.isLive = false;// }// //break;// case 2:// case 3:// if(s.x < et.x + 30 && s.x > et.x// && s.y < et.y + 20 && s.y > et.y){// s.isLive = false;// et.isLive = false;// }// //break;////// default://// break;// }//// }public boolean hintTank(shot s , Tank et){boolean b = false;switch (et.direct) {case 0:case 1:if(s.x < et.x + 20 && s.x > et.x&& s.y < et.y + 30 && s.y > et.y){s.isLive = false;et.isLive = false;b = true;}break;case 2:case 3:if(s.x < et.x + 30 && s.x > et.x&& s.y < et.y + 20 && s.y > et.y){s.isLive = false;et.isLive = false;b = true;}break;// default:// break;}return b;}public void drawTank (int x , int y , Graphics g , int direct , int type){ switch(type){//坦克类型case 0:g.setColor(Color.RED);break;case 1:g.setColor(Color.BLUE);break;}switch (direct) {case 0://向上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,x + 10, y + 15);break;case 1://向下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 + 30 ); break;case 2://向左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 , y + 10,x + 15,y + 10 );break;case 3://向右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 + 30 , y + 10); break;default:break;}}public MyPanel (){hero = new Hero(30, 270 ,0,0,10 , true);//tanks = new tank(100,100, 2 ,1);//初始化敌人坦克Recoder.setHero(hero);for(int i = 0; i < enSize; i++){//创建敌人坦克的对象Recoder.getRecording();EnemyTask et = new EnemyTask((i + 1)*50, 0, 1, 1, 5 ,true); et.setEts(ets);Recoder.setEtss(ets);//传ets到RecoderThread t = new Thread(et);t.start();shot s = new shot(et.x + 10 , et.y + 30, et.direct);et.ss.add(s);Thread t2 = new Thread(s);t2.start();ets.add(et);//加入到集合中//et.setColor(1);}Recoder.setEnSize(enSize);}@Overridepublic void keyPressed(KeyEvent arg0) {// TODO Auto-generated method stubif(arg0.getKeyCode() == KeyEvent.VK_S){//hero.setX(hero.getX() ++ 1);// int i= hero.getY();// i += hero.speed;// hero.setY(i);this.hero.MoveDown();hero.setD(1);}if(arg0.getKeyCode() == KeyEvent.VK_W){//hero.setX(hero.getX() ++ 1);// int i= hero.getY();// i -= hero.speed;// hero.setY(i);hero.MoveUp();hero.setD(0);}if(arg0.getKeyCode() == KeyEvent.VK_D){//hero.setX(hero.getX() ++ 1);// int i= hero.getX();// i += hero.speed;// hero.setX(i);hero.MoveRight();hero.setD(3);}if(arg0.getKeyCode() == KeyEvent.VK_A){//hero.setX(hero.getX() ++ 1);// int i= hero.getX();// i -= hero.speed;// hero.setX(i);hero.MoveLeft();hero.setD(2);}//判断是否按下Jif(arg0.getKeyCode() == KeyEvent.VK_J){if(hero.ss.size() <= 4){this.hero.shotEnemy();//System.out.println("j");}}if(arg0.getKeyCode() == KeyEvent.VK_SPACE){//空格暂停 if(hero.speed != 0){a = hero.speed ;hero.speed = 0;for(int i = 0; i < ets.size(); i ++){//System.out.println("aaaaaaaaaaaaaa");EnemyTask et = ets.get(i);//System.out.println("speed" + et.speed);b = et.speed;et.speed = 0;directs[i] = et.direct;//System.out.println(et.direct);//System.out.println(directs[i]);//et.direct = 0;et.isdirects = false;for(int j = 0 ; j < et.ss.size(); j ++){shot s = et.ss.get(j);c = s.speed;s.speed = 0;System.out.println("aa");}}//System.out.println("b1 =" + b);isPaintShot = false;}else{hero.speed = a;//System.out.println("a2 =" + a);for(int i = 0; i < ets.size(); i ++){//System.out.println("bbbbbbbbbbbbbbbbbbb");EnemyTask et = ets.get(i);et.isdirects = true;et.speed = b;et.direct = directs[i];for(int j = 0 ; j < et.ss.size(); j ++){shot s = et.ss.get(j);s.speed = c;isPaintShot = true;}}s.isShot = true;}}if(arg0.getKeyCode() == KeyEvent.VK_K){this.KeepExit();System.exit(0);}if(arg0.getKeyCode() == KeyEvent.VK_L){this.GetKeeper();}this.repaint();}@Overridepublic void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void run() {//每隔100mswhile(true){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.hintEnemyTank();this.hintMyTank();// for(int i = 0; i < et.ss.size(); i ++){// shot myshot = et.ss.get(i);// if(et.isLive == true){//// if(hero.isLive = true){// this.hintTank2(myshot, hero);// }//// }// }this.repaint();}}private void hintMyTank() {for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);for(int j = 0; j < et.ss.size(); j++ ){shot s = et.ss.get(j);if(s != null){if(hero.isLive){this.hintTank(s, hero);if(this.hintTank(s, hero)){//判断是否击中,返回true则hero数量减一Recoder.setMyLife(Recoder.getMyLife() - 1 );}}}}}}private void hintEnemyTank() {for(int i = 0; i < hero.ss.size(); i ++){shot myshot = hero.ss.get(i);if(myshot.isLive == true){for(int j = 0; j < ets.size(); j ++){EnemyTask et = ets.get(j);if(et.isLive = true){this.hintTank(myshot, et);if(this.hintTank(myshot, et)){hintEnemyTanks ++;Recoder.setEnNum(Recoder.getEnNum() - 1);}}}}}}private void KeepExit(){int [] heros = new int[]{hero.getX(),hero.getY(),hero.direct,};for(int i = 0 ; i < ets.size(); i ++){EnemyTask et = ets.get(i);TanksX[i] = et.getX();TanksY[i] = et.getY();ETdirects [i] = et.direct;for(int j = 1 ; j < et.ss.size(); j++){shot s = et.ss.get(j);ShotsX[j] = s.x;ShotsY[j] = s.y;}}for(int i = 0 ; i < hero.ss.size(); i++ ){shot s = hero.ss.get(i);HeroShotsX[i] = s.x ;HeroShotsY[i] = s.y;}BufferedWriter bw = null;try {bw = new BufferedWriter(new FileWriter("d:\\aa\\TanksX.txt")); for(int i = 0 ; i < enSize ; i ++){bw.write(TanksX[i] + "\r\n");bw.write(TanksY[i] + "\r\n");}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public void GetKeeper (){//继续游戏时还原数据BufferedReader br = null ;try {br = new BufferedReader(new FileReader("d:\\aa\\TanksX.txt")); for(int i = 0; i < enSize*2 ; i ++){if(i % 2 !=0){TanksY[i] = Integer.parseInt(br.readLine());System.out.println("TanksY" + TanksY[i]);}else{TanksX[i] = Integer.parseInt(br.readLine());System.out.println("TanksX" + TanksX[i]);}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}//class tank extends Tank{//// public tank(int x, int y, int direct,int type) {// super(x, y, direct,type);// // TODO Auto-generated constructor stub// }////}下面是工具类:package com.qq.TankGame;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Vector;class Recoder{/****/private static Vector<EnemyTask> ets = new Vector<EnemyTask>(); public static Vector<EnemyTask> getEts() {return ets;}public static void setEtss(Vector<EnemyTask> ets) {Recoder.ets = ets;}private static int enSize ;public static int getEnSize() {return enSize;}public static void setEnSize(int enSize) {Recoder.enSize = enSize;}private static Hero hero ;public static Hero getHero() {return hero;}public static void setHero(Hero hero) { Recoder.hero = hero;}public static void KeepExit(){//System.out.println(hero.getX());int [] TanksX = new int[20];int [] TanksY = new int[20];int [] ShotsX = new int[100];int [] ShotsY = new int[100];int [] ETdirects = new int[20];int [] HeroShotsX = new int[10];int [] HeroShotsY = new int[10];int [] heros = new int[]{hero.getX(),hero.getY(),hero.direct};for(int i = 0 ; i < ets.size(); i ++){EnemyTask et = ets.get(i);TanksX[i] = et.getX();TanksY[i] = et.getY();ETdirects [i] = et.direct;for(int j = 1 ; j < et.ss.size(); j++){shot s = et.ss.get(j);ShotsX[j] = s.x;ShotsY[j] = s.y;}}for(int i = 0 ; i < hero.ss.size(); i++ ){ shot s = hero.ss.get(i);HeroShotsX[i] = s.x ;HeroShotsY[i] = s.y;}BufferedWriter bw = null;BufferedWriter bw1 = null ;try {bw = new BufferedWriter(new FileWriter("d:\\aa\\TanksX.txt"));for(int i = 0 ; i < enSize ; i ++){bw.write(TanksX[i] + "\r\n");bw.write(TanksY[i] + "\r\n");}bw1 = new BufferedWriter(new FileWriter("d:\\aa\\KeepRecoding.txt")); bw1.write((20 - getEnNum()) + "\r\n" );} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {bw1.close();bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}private static int enNum = 5;public static int getEnNum() {return enNum;}public static void setEnNum(int enNum) {Recoder.enNum = enNum;}public static int getMyLife() {return myLife;}public static void setMyLife(int myLife) {Recoder.myLife = myLife;}private static int myLife = 3;private static BufferedReader br = null;public static void getRecording(){try {br = new BufferedReader(new FileReader("d:\\aa\\KeepRecoding.txt")); String n ;while((n = br.readLine()) != null ){String a = n;enNum = 20 - Integer.parseInt(n);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}private static BufferedWriter bw = null;public static void KeepRecording (){try {bw = new BufferedWriter(new FileWriter("d:\\aa\\KeepRecoding.txt")); bw.write((20 - getEnNum()) + "\r\n" );} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {bw.close();//先开后关//new FileWriter("d:\\aa\\KeepRecoding.txt").close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public class Tank {int x = 0 ;int y = 0;int direct = 0; //方向int type = 0 ;//类型int speed = 30;//速度int color;boolean isLive;public int getColor() {return color;}public void setColor(int color) {this.color = color;}public int getS() {return speed;}public void setS(int speed) {this.speed = speed;}public Tank(int x , int y , int direct , int type, int speed, boolean isLive){ this.x = x;this.y = y;this.direct = direct;this.type= type;this.speed = speed;this.isLive = isLive;}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 int getD() {return direct;}public void setD(int direct) {this.direct = direct;}public int getT() {return type;}public void setT(int type) {this.type = type;}}class EnemyTask extends Tank implements Runnable{Vector<shot> ss = new Vector<shot>();Vector<EnemyTask> ets = new Vector<EnemyTask>();boolean isdirects = true;public EnemyTask(int x, int y, int direct, int type, int speed ,boolean isLive) {super(x, y, direct, type, speed, isLive);// TODO Auto-generated constructor stub}public boolean isTouchOhterTank (){boolean b = false;switch (this.direct) {case 0://此坦克向上for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);if(et != this){if(et.direct == 0 || et.direct == 1){//上或下if((this.x>=et.x && this.x <= et.x + 20//第一个点x在内&& this.y>=et.y && this.y <= et.y + 30)//第一个点y在内||(this.x + 20>=et.x && this.x+ 20 <= et.x + 20//第二个点x在内&& this.y >=et.y && this.y <= et.y + 30)//第二个点y在内){b = true;}}if(et.direct == 2 || et.direct == 3){//左或右if((this.x>=et.x && this.x <= et.x + 30//第一个点x在内&& this.y>=et.y && this.y <= et.y + 20)//第一个点y在内||(this.x + 20>=et.x && this.x+ 20 <= et.x + 30//第二个点x在内&& this.y >=et.y && this.y <= et.y + 20)//第二个点y在内){b = true;}}}}break;case 1://向下for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);if(et != this){if(et.direct == 0 || et.direct == 1){//上或下if((this.x>=et.x && this.x <= et.x + 20//第一个点x在内&& this.y + 30>=et.y && this.y + 30 <= et.y + 30)//第一个点y在内||(this.x + 20>=et.x && this.x+ 20 <= et.x + 20//第二个点x在内&& this.y + 30>=et.y && this.y + 30 <= et.y + 30)//第二个点y在内){b = true;}}if(et.direct == 2 || et.direct == 3){//左或右if((this.x>=et.x && this.x <= et.x + 30//第一个点x在内&& this.y + 30 >=et.y && this.y + 30 <= et.y + 20)//第一个点y在内||(this.x + 20 >=et.x && this.x+ 20 <= et.x + 30//第二个点x在内&& this.y + 30 >=et.y && this.y + 30 <= et.y + 20)//第二个点y在内){b = true;}}}}break;case 2:for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);if(et != this){if(et.direct == 0 || et.direct == 1){//上或下if((this.x>=et.x && this.x <= et.x + 20//第一个点x在内&& this.y>=et.y && this.y <= et.y + 30)//第一个点y在内||(this.x >=et.x && this.x<= et.x + 20//第二个点x在内&& this.y + 20 >=et.y && this.y + 20 <= et.y + 30)//第二个点y在内){b = true;}}if(et.direct == 2 || et.direct == 3){//左或右if((this.x>=et.x && this.x <= et.x + 30//第一个点x在内&& this.y>=et.y && this.y <= et.y + 20)//第一个点y在内||(this.x >=et.x && this.x<= et.x + 30//第二个点x在内&& this.y + 20>=et.y && this.y + 20 <= et.y + 20)//第二个点y在内){b = true;}}}}break;case 3:for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);if(et != this){if(et.direct == 0 || et.direct == 1){//上或下if((this.x + 30>=et.x && this.x + 30 <= et.x + 20//第一个点x在内&& this.y>=et.y && this.y <= et.y + 30)//第一个点y在内||(this.x + 30 >=et.x && this.x+ 30 <= et.x + 20//第二个点x在内&& this.y + 20 >=et.y && this.y + 20 <= et.y + 30)//第二个点y在内){b = true;}}if(et.direct == 2 || et.direct == 3){//左或右if((this.x + 30>=et.x && this.x + 30 <= et.x + 30//第一个点x在内&& this.y>=et.y && this.y <= et.y + 20)//第一个点y在内||(this.x + 30>=et.x && this.x+ 30 <= et.x + 30//第二个点x在内&& this.y + 20>=et.y && this.y + 20 <= et.y + 20)//第二个点y在内){b = true;}}}}break;default:break;}return b ;}@Overridepublic void run() {int a = (int) (Math.random() * 10 + 2);//连动步数int times = 0;while(true){try {Thread.sleep(300);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//if(x > 0 && x < 400 - 30 & y > 0 && y < 300 - 30){ //if(!this.isTouchOhterTank()){switch(this.direct){case 0://System.out.println(isTouchOhterTank());for(int i = 0 ;i < a ; i++){if(y - this.speed > 0 && !this.isTouchOhterTank()){y -= this.speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 1:for(int i = 0 ;i < a ; i++){if(y + speed < 300 - 30 && !this.isTouchOhterTank()){ y += this.speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 2:for(int i = 0 ;i < a ; i++){if(x - speed > 0 && !this.isTouchOhterTank()){x -= this.speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 3:for(int i = 0 ;i < a ; i++){if(x + speed < 400 - 30 && !this.isTouchOhterTank()){ x += this.speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;}//}times ++;if(times % 2 == 0){if(isLive){if(ss.size() < 3){shot s = null;switch (direct) {case 0://向上s = new shot(x + 10 , y ,0);ss.add(s);break;case 1://向下s = new shot(x + 10 , y + 30 , 1);ss.add(s);break;case 2://向左s = new shot(x , y + 10 , 2);ss.add(s);break;case 3://右s = new shot(x + 30 , y + 10 , 3);ss.add(s);break;default:break;}Thread t = new Thread(s);t.start();}}}//}// //随机改变方向// public void changeDirect(){//// }if(isdirects){this.direct = (int) (Math.random() * 4); }if(this.isLive == false){break;}if(ss.size() < 3){}}}public void setEts(Vector<EnemyTask> ets) { this.ets = ets;}// @Override// public void run() {// while(true){// try {// Thread.sleep(50);// } catch (InterruptedException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }//// y ++ ;// System.out.println(y);// }//// }}class Hero extends Tank{//public Hero(int x , int y, int direct, int type,int speed, boolean isLive){super(x, y, direct, type,speed , isLive);}Vector<shot> ss = new Vector<shot>();shot s = null;//开火public void shotEnemy(){//System.out.println("shotEnemy");if(Recoder.getMyLife() > 0){//生命没有了,不能发子弹 switch (this.direct) {case 0://向上s = new shot(x + 10 , y ,0);ss.add(s);break;case 3://右s = new shot(x + 30 , y + 10 , 3);ss.add(s);break;case 1://向下s = new shot(x + 10 , y + 30 , 1);ss.add(s);break;case 2://向左s = new shot(x , y + 10 , 2);ss.add(s);break;default:break;}Thread t = new Thread(s);t.start();}}//向上,下,左,右public void MoveUp(){if(y - this.speed > 0){y -= speed;}}public void MoveDown(){if(y + this.speed < 300 -30){y += speed;}}public void MoveLeft(){if(x - this.speed > 0){x -= speed;}}public void MoveRight(){if(x + this.speed < 400 -30){x += speed;}}}class shot implements Runnable{int x ,y;int direct;int speed = 20; //子弹速度boolean isShot = true;boolean isLive = true;//子弹是否活着 public shot(int x,int y, int direct){this.x = x;this.y = y;this.direct = direct;}@Overridepublic void run() {while(true){try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if(isShot){switch (direct) {case 0://向上y -= speed;break;case 1://下y += speed;break;case 2://右x -= speed;break;case 3://左x += speed;break;default:break;}}//System.out.println(x + " " + y);if(x < 0 || x > 400 || y < 0 || y > 300){ //System.out.println("this.islive = false");this.isLive = false;break;}}} }。

JAVA实现经典游戏坦克大战的示例代码

JAVA实现经典游戏坦克大战的示例代码

JAVA实现经典游戏坦克⼤战的⽰例代码⽬录前⾔主要设计功能截图代码实现总结前⾔⼩时候⼤家都玩过坦克⼤战吧,熟悉的旋律和丰富的关卡陪伴了我们⼀整个寒暑假,还记得传说中的经典坦克⼤战吗?那些怀旧的记忆,伴随着我们⼀起⾛过来的经典坦克⼤战,刚开始那战战兢兢,屡屡被敌⼈坦克击毁的情景历历在⽬。

现在好了,再也不⽤担⼼敌⼈坦克了,可以横冲直撞,横扫敌⼈坦克了。

快哉《坦克⼤战》游戏以坦克战⽃为主题,⽤java语⾔实现,采⽤了swing技术进⾏了界⾯化处理,设计思路⽤了⾯向对象思想。

主要需求可以⽣成不同的地图,消灭地图上的所有坦克为胜利;可以设置关卡地图,不断增加难度。

主要设计1、要有难度关卡:第⼀关,第⼆关,第三关,第四关,第五关;第⼀关地图最简单,第五关地图最难;2、坦克要有⾎条,打多次才会死3、地图要我有我⽅坦克四辆(相当于4条命)和多辆敌⽅坦克4、我⽅坦克的炮弹数量是固定的,设置为5005、地图右边显⽰基本信息6、地图上要在砖块,铁块,河流功能截图游戏开始页⾯代码实现窗⼝布局public class GameFrame extends JFrame {/*** serialVersionUID*/private static final long serialVersionUID = -1176914786963603304L;public GameFrame() {super();this.setSize(800, 700);this.setTitle("坦克⼤战");this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);this.setResizable(false);// 显⽰器屏幕⼤⼩Dimension screenSizeInfo = Toolkit.getDefaultToolkit().getScreenSize();int leftTopX = ((int) screenSizeInfo.getWidth() - this.getWidth()) / 2;int leftTopY = ((int) screenSizeInfo.getHeight() - this.getHeight()) / 2;// 设置显⽰的位置在屏幕中间this.setLocation(leftTopX, leftTopY);}}地图渲染核⼼算法@Servicepublic class PaintService {@Autowiredprivate GameContext context;private Brick rightBrick = new Brick(700, 50);private Iron rightIron = new Iron(700, 50);private Water rightWater = new Water(700, 50);/*** 画出东西(包括坦克、障碍物。

坦克大战java程序

坦克大战java程序

import java.awt.*;import java.awt.event.*;import java.util.*;import javax.swing.*;public class TankBattles extends JFrame implements ActionListener {StartPanel sp = null;FightPanel fp = null;Image img = null;JMenuBar jmb = null;JMenu jm1 = null;JMenuItem jmi1 = null;JMenuItem jmi2 = null;JMenuItem jmi3 = null;public static void main(String[] args) {// TODO Auto-generated method stubTankBattles tb = new TankBattles();}public TankBattles() {sp = new StartPanel();jmb = new JMenuBar();jm1 = new JMenu("游戏");jmi1 = new JMenuItem("新游戏");jmi2 = new JMenuItem("保存");jmi3 = new JMenuItem("退出");jmi1.addActionListener(this);jmi1.setActionCommand("newGame");jmi2.addActionListener(this);jmi2.setActionCommand("save");jmi3.addActionListener(this);jmi3.setActionCommand("exit");jm1.add(jmi1);jm1.add(jmi2);jm1.add(jmi3);jmb.add(jm1);this.setJMenuBar(jmb);this.add(sp);img = Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/MyTank_Up.png"));this.setIconImage(img);this.setTitle("TankBattles");this.setSize(500, 500);this.setLocation(400, 300);this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getActionCommand().equals("newGame")) {fp = new FightPanel();Thread t = new Thread(fp);t.start();this.remove(sp);this.add(fp);this.addKeyListener(fp);this.setVisible(true);} else if (e.getActionCommand().equals("save")) {} else if (e.getActionCommand().equals("exit")) {System.exit(0);}}}class StartPanel extends JPanel {public void paint(Graphics g) {g.setColor(Color.BLACK);g.fillRect(0, 0, 500, 500);}}class FightPanel extends JPanel implements KeyListener, Runnable {// 用于监控按键状态boolean up = false;boolean down = false;boolean left = false;boolean right = false;boolean space = false;MyTank mt = null;Vector<EnemyTank> ets = new Vector<EnemyTank>();int n;public FightPanel() {// 创建我的坦克mt = new MyTank(400, 300, 0, 0);// 敌方坦克数量n = 5;// 创建敌方坦克for (int i = 0; i < n; i++) {EnemyTank et = new EnemyTank(55 + i * 50, 55, 1, 1);ets.add(et);et.setEts(ets);et.setMt(mt);Thread t = new Thread(et);t.start();}mt.setEts(ets);}public void paint(Graphics g) {g.setColor(Color.BLACK);g.fillRect(0, 0, 500, 500);// 绘制敌人坦克for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (et.isLive()) {this.drawTank(et.getX(), et.getY(), g, et.getDirect(), et.getType());} else {ets.remove(i);}}// 绘制我方坦克if (mt.isLive()) {this.drawTank(mt.getX(), mt.getY(), g, mt.getDirect(), mt.getType());} else {g.setColor(Color.RED);g.setFont(new Font("Tahoma", Font.BOLD, 50));g.drawString("GAME VOER", 100, 200);}if (ets.size() == 0) {g.setColor(Color.RED);g.setFont(new Font("Tahoma", Font.BOLD, 50));g.drawString("YOU WIN", 130, 200);}// 绘制我方子弹if (mt.bullet != null) {g.setColor(Color.YELLOW);for (int i = 0; i < mt.bullets.size(); i++) {Bullet bullet = mt.bullets.get(i);if (bullet.isLive()) {g.drawRect(bullet.getX() - 1, bullet.getY() - 1, 1, 1);} else {mt.bullets.remove(i);}}}// 绘制敌方子弹for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (et.bullet != null) {g.setColor(Color.YELLOW);for (int j = 0; j < et.bullets.size(); j++) {Bullet bullet = et.bullets.get(j);if (bullet.isLive()) {g.drawRect(bullet.getX() - 1, bullet.getY() - 1, 1, 1);} else {et.bullets.remove(j);}}}}}public void drawTank(int x, int y, Graphics g, int direct, int type) { switch (type) {case 0:g.setColor(Color.RED);break;case 1:g.setColor(Color.GREEN);break;}switch (direct) {case 0:g.drawRect(x, y, 40, 40);g.drawLine(x + 20, y, x + 20, y + 20);g.drawLine(x + 20, y, x + 15, y + 5);g.drawLine(x + 20, y, x + 25, y + 5);break;case 1:g.drawRect(x, y, 40, 40);g.drawLine(x + 20, y + 20, x + 20, y + 40);g.drawLine(x + 20, y + 40, x + 15, y + 35);g.drawLine(x + 20, y + 40, x + 25, y + 35);break;case 2:g.drawRect(x, y, 40, 40);g.drawLine(x, y + 20, x + 20, y + 20);g.drawLine(x, y + 20, x + 5, y + 15);g.drawLine(x, y + 20, x + 5, y + 25);break;case 3:g.drawRect(x, y, 40, 40);g.drawLine(x + 20, y + 20, x + 40, y + 20);g.drawLine(x + 40, y + 20, x + 35, y + 15);g.drawLine(x + 40, y + 20, x + 35, y + 25);break;}}@Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stubif (e.getKeyCode() == KeyEvent.VK_UP) {up = true;} else if (e.getKeyCode() == KeyEvent.VK_DOWN) { down = true;} else if (e.getKeyCode() == KeyEvent.VK_LEFT) { left = true;} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { right = true;}if (e.getKeyCode() == KeyEvent.VK_SPACE) {space = true;}// 设置暂停和继续if (e.getKeyCode() == KeyEvent.VK_P) {mt.setSpeed(0);for (int i = 0; i < mt.bullets.size(); i++) {Bullet bullet = mt.bullets.get(i);bullet.setSpeed(0);}for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);et.setSpeed(0);for (int j = 0; j < et.bullets.size(); j++) {Bullet bullet = et.bullets.get(j);bullet.setSpeed(0);}}} else if (e.getKeyCode() == KeyEvent.VK_C) {mt.setSpeed(2);for (int i = 0; i < mt.bullets.size(); i++) {Bullet bullet = mt.bullets.get(i);bullet.setSpeed(6);}for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);et.setSpeed(2);for (int j = 0; j < et.bullets.size(); j++) {Bullet bullet = et.bullets.get(j);bullet.setSpeed(6);}}}}@Overridepublic void keyReleased(KeyEvent e) {// TODO Auto-generated method stubif (e.getKeyCode() == KeyEvent.VK_UP) {up = false;} else if (e.getKeyCode() == KeyEvent.VK_DOWN) { down = false;} else if (e.getKeyCode() == KeyEvent.VK_LEFT) { left = false;} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) { right = false;}if (e.getKeyCode() == KeyEvent.VK_SPACE) {space = false;}}@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stub}@Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 监控移动和射击if (up) {if (!mt.touchEnemyTank()) {mt.moveUp();}mt.turnUp();} else if (down) {if (!mt.touchEnemyTank()) {mt.moveDown();}mt.turnDown();} else if (left) {if (!mt.touchEnemyTank()) {mt.moveLeft();}mt.turnLeft();} else if (right) {if (!mt.touchEnemyTank()) {mt.moveRight();}mt.turnRight();}if (space) {if (mt.getSpeed() != 0) {int i = mt.bullets.size() - 1;if (i < 0) {this.mt.fire();} else {Bullet bullet = mt.bullets.get(i);if (bullet.getDistance() >= 10) {this.mt.fire();}}}}// 判断是否击中敌方坦克for (int i = 0; i < mt.bullets.size(); i++) {Bullet bullet = mt.bullets.get(i);bullet.hitEnemyTank(ets);}// 判断我方坦克是否被击中for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);for (int j = 0; j < et.bullets.size(); j++) {Bullet bullet = et.bullets.get(j);bullet.hitMyTank(mt);}}// 重绘this.repaint();if (mt.isLive() != true || ets.size() == 0) {break;}}}}class Bullet implements Runnable {int x;int y;int direct;int speed;int distance;boolean live;public Bullet(int x, int y, int direct) {this.x = x;this.y = y;this.direct = direct;this.speed = 6;this.distance = 0;this.live = true;}public void hitEnemyTank(Vector<EnemyTank> ets) {for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (x >= et.getX() && x <= et.getX() + 40 && y >= et.getY() && y <= et.getY() + 40) { this.live = false;et.setLive(false);}}}public void hitMyTank(MyTank mt) {if (x >= mt.getX() && x <= mt.getX() + 40 && y >= mt.getY() && y <= mt.getY() + 40) { this.live = false;mt.setLive(false);}}@Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}switch (this.direct) {case 0:y = y - speed;distance++;break;case 1:y = y + speed;distance++;break;case 2:x = x - speed;distance++;break;case 3:x = x + speed;distance++;break;}if (x < 0 || x > 500 || y < 0 || y > 500) {this.live = false;break;}}}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 int getDirect() {return direct;}public void setDirect(int direct) {this.direct = direct;}public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public int getDistance() {return distance;}public void setDistance(int distance) {this.distance = distance;}public boolean isLive() {return live;}public void setLive(boolean live) {this.live = live;}}class Tank {int x;int y;int speed;int direct;Vector<Bullet> bullets = new Vector<Bullet>();Bullet bullet = null;boolean live;int type;public Tank(int x, int y, int direct, int type) {this.x = x;this.y = y;this.speed = 2;this.direct = direct;this.type = type;this.live = true;}public void fire() {switch (this.direct) {case 0:bullet = new Bullet(x + 20, y, direct);bullets.add(bullet);break;case 1:bullet = new Bullet(x + 20, y + 40, direct);bullets.add(bullet);break;case 2:bullet = new Bullet(x, y + 20, direct);bullets.add(bullet);break;case 3:bullet = new Bullet(x + 40, y + 20, direct);bullets.add(bullet);break;}Thread t = new Thread(bullet);t.start();}public void turnUp() {if (speed != 0) {direct = 0;}}public void turnDown() {if (speed != 0) {direct = 1;}}public void turnLeft() {if (speed != 0) {direct = 2;}}public void turnRight() {if (speed != 0) {direct = 3;}}public void moveUp() {if (y >= speed) {y -= speed;}}public void moveDown() {if (y <= 405 - speed) {y += speed;}}public void moveLeft() {if (x >= speed) {x -= speed;}}public void moveRight() {if (x <= 452 - speed) {x += 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 int getSpeed() {return speed;}public void setSpeed(int speed) { this.speed = speed;}public int getDirect() {return direct;}public void setDirect(int direct) {this.direct = direct;}public Vector<Bullet> getBullets() {return bullets;}public void setBullets(Vector<Bullet> bullets) { this.bullets = bullets;}public Bullet getBullet() {return bullet;}public void setBullet(Bullet bullet) {this.bullet = bullet;}public boolean isLive() {return live;}public void setLive(boolean live) {this.live = live;}public int getType() {return type;}public void setType(int type) {this.type = type;}}class MyTank extends Tank {Vector<EnemyTank> ets = new Vector<EnemyTank>();public MyTank(int x, int y, int direct, int type) {super(x, y, direct, type);}// 判断是否碰到敌方坦克public boolean touchEnemyTank() {switch (this.direct) {case 0:for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (this.x >= et.x && this.x <= et.x + 40 && this.y >= et.y && this.y <= et.y + 40) {return true;}if (this.x + 40 >= et.x && this.x + 40 <= et.x + 40 && this.y >= et.y && this.y <= et.y + 40) {return true;}}break;case 1:for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (this.x >= et.x && this.x <= et.x + 40 && this.y + 40 >= et.y && this.y + 40 <= et.y + 40) {return true;}if (this.x + 40 >= et.x && this.x + 40 <= et.x + 40 && this.y + 40 >= et.y && this.y + 40 <= et.y + 40) {return true;}}break;case 2:for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (this.x >= et.x && this.x <= et.x + 40 && this.y >= et.y && this.y <= et.y + 40) {return true;}if (this.x >= et.x && this.x <= et.x + 40 && this.y + 40 >= et.y && this.y + 40 <=et.y + 40) {return true;}}break;case 3:for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (this.x + 40 >= et.x && this.x + 40 <= et.x + 40 && this.y >= et.y && this.y <= et.y + 40) {return true;}if (this.x + 40 >= et.x && this.x + 40 <= et.x + 40 && this.y + 40 >= et.y && this.y + 40 <= et.y + 40) {return true;}}break;}return false;}public Vector<EnemyTank> getEts() {return ets;}public void setEts(Vector<EnemyTank> ets) {this.ets = ets;}}class EnemyTank extends Tank implements Runnable {Vector<EnemyTank> ets = new Vector<EnemyTank>();MyTank mt = null;public EnemyTank(int x, int y, int direct, int type) {super(x, y, direct, type);}// 判断是否碰到其他敌方坦克public boolean touchOtherEnemyTank() {switch (this.direct) {case 0:for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (et != this) {if (this.x >= et.x && this.x <= et.x + 40 && this.y >= et.y && this.y <= et.y + 40) {return true;}if (this.x + 40 >= et.x && this.x + 40 <= et.x + 40 && this.y >= et.y && this.y <= et.y + 40) {return true;}}}break;case 1:for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (et != this) {if (this.x >= et.x && this.x <= et.x + 40 && this.y + 40 >= et.y && this.y + 40 <= et.y + 40) {return true;}if (this.x + 40 >= et.x && this.x + 40 <= et.x + 40 && this.y + 40 >= et.y && this.y + 40 <= et.y + 40) {return true;}}}break;case 2:for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (et != this) {if (this.x >= et.x && this.x <= et.x + 40 && this.y >= et.y && this.y <= et.y + 40) {return true;}if (this.x >= et.x && this.x <= et.x + 40 && this.y + 40 >= et.y && this.y + 40 <= et.y + 40) {return true;}}}break;for (int i = 0; i < ets.size(); i++) {EnemyTank et = ets.get(i);if (et != this) {if (this.x + 40 >= et.x && this.x + 40 <= et.x + 40 && this.y >= et.y && this.y <= et.y + 40) {return true;}if (this.x + 40 >= et.x && this.x + 40 <= et.x + 40 && this.y + 40 >= et.y && this.y + 40 <= et.y + 40) {return true;}}}break;}return false;}// 判断是否碰到我的坦克public boolean touchMyTank() {switch (this.direct) {case 0:if (this.x >= mt.x && this.x <= mt.x + 40 && this.y >= mt.y && this.y <= mt.y + 40) { return true;}if (this.x + 40 >= mt.x && this.x + 40 <= mt.x + 40 && this.y >= mt.y && this.y <= mt.y + 40) {return true;}break;case 1:if (this.x >= mt.x && this.x <= mt.x + 40 && this.y + 40 >= mt.y && this.y + 40 <= mt.y + 40) {return true;}if (this.x + 40 >= mt.x && this.x + 40 <= mt.x + 40 && this.y + 40 >= mt.y && this.y + 40 <= mt.y + 40) {return true;}break;case 2:if (this.x >= mt.x && this.x <= mt.x + 40 && this.y >= mt.y && this.y <= mt.y + 40) { return true;if (this.x >= mt.x && this.x <= mt.x + 40 && this.y + 40 >= mt.y && this.y + 40 <= mt.y + 40) {return true;}break;case 3:if (this.x + 40 >= mt.x && this.x + 40 <= mt.x + 40 && this.y >= mt.y && this.y <= mt.y + 40) {return true;}if (this.x + 40 >= mt.x && this.x + 40 <= mt.x + 40 && this.y + 40 >= mt.y && this.y + 40 <= mt.y + 40) {return true;}break;}return false;}@Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {if (speed != 0) {this.direct = (int) (Math.random() * 4);}switch (this.direct) {case 0:for (int i = 0; i < 30; i++) {if (!this.touchOtherEnemyTank() && !this.touchMyTank()) {this.moveUp();}if (y < speed || this.touchOtherEnemyTank() || this.touchMyTank()) {break;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 1:for (int i = 0; i < 30; i++) {if (!this.touchOtherEnemyTank() && !this.touchMyTank()) {this.moveDown();}if (y > 405 - speed || this.touchOtherEnemyTank() || this.touchMyTank()) {break;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 2:for (int i = 0; i < 30; i++) {if (!this.touchOtherEnemyTank() && !this.touchMyTank()) {this.moveLeft();}if (x < speed || this.touchOtherEnemyTank() || this.touchMyTank()) {break;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 3:for (int i = 0; i < 30; i++) {if (!this.touchOtherEnemyTank() && !this.touchMyTank()) {this.moveRight();}if (x > 452 - speed || this.touchOtherEnemyTank() || this.touchMyTank()) {break;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;}if (speed != 0) {this.fire();}if (this.isLive() != true) {break;}}}public Vector<EnemyTank> getEts() {return ets;}public void setEts(Vector<EnemyTank> ets) {this.ets = ets;}public MyTank getMt() {return mt;}public void setMt(MyTank mt) {this.mt = mt;}}。

JAVA实现坦克大战1.0版本

JAVA实现坦克大战1.0版本

JAVA实现坦克⼤战1.0版本 1package tankGame;2import java.awt.*;3import javax.swing.*;4import java.awt.event.*;5import java.util.*;6/**7 * 功能:我⽅坦克可以发⼦弹8 *9 * */10public class MyTankGame1 extends JFrame {1112public static void main(String[] args) {13// TODO Auto-generated method stub14 MyTankGame1 mtg =new MyTankGame1();15 }16//构造函数17public MyTankGame1(){18 MyPanel mp=new MyPanel();1920//线程启动21 Thread t=new Thread(mp);22 t.start();2324this.add(mp);25this.addKeyListener(mp);//注册监听26this.setSize(400,300);27this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);28this.setVisible(true);29 }3031 }3233//我的⾯板34class MyPanel extends JPanel implements KeyListener,Runnable{35 Hero hero=null;//定义我的坦克36 Vector<Enermy> enermy=new Vector<Enermy>() ;//定义敌⼈的坦克组37int enSize=3;38//构造函数39public MyPanel(){40 hero=new Hero(100,100);4142for(int i=0;i<enSize;i++){43//创建⼀辆敌⼈的坦克对象44 Enermy en=new Enermy((i+1)*50, 0);45 en.setColor(0);46 en.setDerect(3);47//加⼊48 enermy.add(en);49 }5051 }52public void paint(Graphics g){//重新paint53super.paint(g);54 g.fillRect(0, 0, 400, 300);55//画出我的坦克56this.drawTank(hero.getX(), hero.getY(), g,this.hero.derect, 1);57//画出⼦弹58if(hero.s!=null&&hero.s.isLive==true){59 g.fillOval(hero.s.x ,hero.s.y, 2, 2);60 }6162//画出敌⼈的坦克63for(int i=0;i<enermy.size();i++){64this.drawTank(enermy.get(i).getX(), enermy.get(i).getY(), g, enermy.get(i).derect, 0);65//System.out.println(enermy.get(i).derect);//默认值为066 }67 }68public void drawTank(int x,int y,Graphics g,int direct,int type){69//判断是什么类型的坦克,敌⼈的还是我⽅的70switch(type){71case 0:72 g.setColor(Color.CYAN);73break;74case 1:75 g.setColor(Color.yellow);76break;77 }78//判断⽅向79switch(direct){80//坦克头向上81case 0:82//画出我的坦克,到时再封装为⼀个函数 83//画出左边的矩形84 g.fill3DRect(x, y, 5, 30,false);85//画出有右边的矩形86 g.fill3DRect(x+15, y, 5, 30,false);87//画出中间的矩形88 g.fill3DRect(x+5, y+5, 10, 20,false);89//画出圆形90 g.fillOval(x+5, y+10, 10, 10);91//画炮头92 g.drawLine(x+10, y-5, x+10, y+15);93break;9495//坦克头向右96case 1:9798//画出上边的矩形99 g.fill3DRect(x, y, 30, 5,false);100//画出下边的矩形101 g.fill3DRect(x, y+15, 30, 5,false);102//画出中间的矩形103 g.fill3DRect(x+5, y+5, 20, 10,false);104//画出圆形105 g.fillOval(x+10, y+5, 10, 10);106//画炮头107 g.drawLine(x+15, y+10, x+35, y+10); 108break;109110//坦克头向下111case 2:112113 g.fill3DRect(x, y, 5, 30,false);114//画出有右边的矩形115 g.fill3DRect(x+15, y, 5, 30,false);116//画出中间的矩形117 g.fill3DRect(x+5, y+5, 10, 20,false);118//画出圆形119 g.fillOval(x+5, y+10, 10, 10);120//画炮头121 g.drawLine(x+10, y+15,x+10, y+35); 122break;123124//坦克头向左125case 3:126127//画出上边的矩形128 g.fill3DRect(x, y, 30, 5,false);129//画出下边的矩形130 g.fill3DRect(x, y+15, 30, 5,false);131//画出中间的矩形132 g.fill3DRect(x+5, y+5, 20, 10,false);133//画出圆形134 g.fillOval(x+10, y+5, 10, 10);135//画炮头136 g.drawLine( x-5, y+10,x+15, y+10);137break;138 }139140141 }142 @Override143public void keyPressed(KeyEvent e) {144// TODO Auto-generated method stub145if(e.getKeyCode()==KeyEvent.VK_W){146//设置我的坦克⽅向147this.hero.setDerect(0);148this.hero.moveUp();149 }else if (e.getKeyCode()==KeyEvent.VK_D){ 150this.hero.setDerect(1);151this.hero.moveRight();152 }else if (e.getKeyCode()==KeyEvent.VK_S){ 153this.hero.setDerect(2);154this.hero.moveDown();155 }else if (e.getKeyCode()==KeyEvent.VK_A){ 156this.hero.setDerect(3);157this.hero.moveLeft();158 }159this.repaint();160//判断玩家是否按下j161if(e.getKeyCode()==KeyEvent.VK_J){162//开⽕,调⽤shotEnermy163this.hero.shotEnermy();164 }165166 }167 @Override168public void keyReleased(KeyEvent e) { 169// TODO Auto-generated method stub 170171 }172 @Override173public void keyTyped(KeyEvent e) {174// TODO Auto-generated method stub 175176 }177 @Override178public void run() {//实现每隔100ms去重绘179// TODO Auto-generated method stub 180while(true){181try {182 Thread.sleep(100);183 } catch (InterruptedException e) {184// TODO Auto-generated catch block 185 e.printStackTrace();186 }187this.repaint();188 }189 }190 }成员类1package tankGame;2//⼦弹类3class Shot implements Runnable{4int x,y,direct;5int speed=1;6boolean isLive=true;7public Shot(int x,int y,int direct){8this.x=x;9this.y=y;10this.direct=direct;11 }12 @Override13public void run() {14// TODO Auto-generated method stub15while(true){16try {17 Thread.sleep(50);18 } catch (InterruptedException e) {19// TODO Auto-generated catch block20 e.printStackTrace();21 }22switch(direct){23case 0:24 y-=speed;25break;26case 1:27 x+=speed;28break;29case 2:30 y+=speed;31break;32case 3:33 x-=speed;34break;35 }36 System.out.println("X"+x+"Y"+y);37if (x<0||x>400||y<0||y>300){38this.isLive=false;39break;40 }41 }42 }43 }44//坦克类45class Tank46 {47int x=0;//坦克的横坐标48int y=0;//坦克的纵坐标49int derect;//0上 1右 2下 3左50int speed=1;//设置坦克的速度51int color;//设置坦克颜⾊52public int getColor() {53return color;54 }55public void setColor(int color) {56this.color = color;57 }58public int getDerect() {59return derect;60 }61public void setDerect(int derect) {62this.derect = derect;63 }64public int getX() {65return x;66 }67public void setX(int x) {68this.x = x;69 }70public int getY() {71return y;72 }73public void setY(int y) {74this.y = y;75 }7677public Tank(int x,int y){78this.x=x;79this.y=y;80 }81 }82class Hero extends Tank{83 Shot s=null;//⼦弹是和坦克关联的84public Hero (int x,int y){85super(x,y);86 }87public void shotEnermy(){//⼦弹和坦克⽅向相关 8889switch(this.derect){90case 0:91 s=new Shot(x+10,y-9,0);92break;93case 1:94 s=new Shot(x+38,y+9,1);95break;96case 2:97 s=new Shot(x+10,y+37,2);98break;99100case 3:101 s=new Shot(x-9,y+9,3);102break;103 }104 Thread t=new Thread(s);105 t.start();106 }107//坦克向上移动108public void moveUp(){109 y-=speed;110 }111//坦克向右移动112public void moveRight(){113 x+=speed;114 }//坦克向下移动115public void moveDown(){116 y+=speed;117 }118//坦克向左移动119public void moveLeft(){120 x-=speed;121 }122123124 }125class Enermy extends Tank{126public Enermy (int x,int y){127super(x,y);128 }129 }效果如下:。

java写的坦克大战简易版

java写的坦克大战简易版

MyTankGame2.javapackage test;import javax.swing.*;import java.awt.*;import java.awt.event.*;//import java.io.*;import java.util.*;class MyTankGame2 extends JFrame implements ActionListener {MyPanel mp=null;//定义一个开始的面板MyStartPanel msp=null;//做出我需要的菜单JMenuBar jmb=null;//开始游戏JMenu jm1=null;JMenuItem jmi1=null;//退出系统JMenuItem jmi2=null;//存盘退出JMenuItem jmi3=null;JMenuItem jmi4=null;public static void main(String[] args){//System.out.println("Hello World!");MyTankGame2 mtg=new MyTankGame2();}//构造方法public MyTankGame2(){//创建菜单及菜单选项jmb=new JMenuBar();jm1=new JMenu("游戏(G)");//设置助记符jm1.setMnemonic('G');jmi1=new JMenuItem("开始新游戏(N)");jmi2=new JMenuItem("退出游戏(E)");jmi3=new JMenuItem("存盘退出游戏");jmi4=new JMenuItem("继续上局游戏");jmi4.addActionListener(this);jmi4.setActionCommand("continueGame");jmi3.addActionListener(this);jmi3.setActionCommand("saveExit");jmi2.setMnemonic('E');//对jmi1进行响应jmi1.addActionListener(this);jmi1.setActionCommand("newGame");jmi2.addActionListener(this);jmi2.setActionCommand("exit");jm1.add(jmi1);jm1.add(jmi2);jm1.add(jmi3);jm1.add(jmi4);jmb.add(jm1);msp=new MyStartPanel();Thread t=new Thread(msp);t.start();this.setJMenuBar(jmb);this.add(msp);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(600,450);this.setVisible(true);}@Overridepublic void actionPerformed(ActionEvent e) {//对用户不同的点击进行不同的处理if(e.getActionCommand().equals("newGame")){mp=new MyPanel("newGame");Thread t=new Thread(mp);t.start();//先删除旧的面板this.remove(msp);this.add(mp);//注册监听this.addKeyListener(mp);//显示this.setVisible(true);}else if(e.getActionCommand().equals("exit")){//保存击毁敌人的数量Recorder.keepRecording();System.exit(0);}//对存盘退出做处理else if(e.getActionCommand().equals("saveExit")){//工作Recorder re=new Recorder();re.setEts(mp.ets);//保存击毁敌人的数量和敌人的坐标re.keepRecAndEnemyTank();//退出System.exit(0);}else if(e.getActionCommand().equals("continueGame")){ //mp=new MyPanel("con");//mp.flag=;Thread t=new Thread(mp);t.start();//先删除旧的面板this.remove(msp);this.add(mp);//注册监听this.addKeyListener(mp);//显示this.setVisible(true);}}}class MyStartPanel extends JPanel implements Runnable{ int times=0;public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 400, 300);//提示信息if(times%2==0){g.setColor(Color.yellow);//开关信息的字体Font myFont=new Font("华文新魏",Font.BOLD,30);g.setFont(myFont);g.drawString("stage:1", 150, 140);}}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){//休眠try {Thread.sleep(100);} catch (Exception e) {// TODO: handle exception}times++;//重画this.repaint();}}}//我的面板class MyPanel extends JPanel implements KeyListener,Runnable {//定义我的坦克Hero hero=null;//判断继续上局还是新游戏//定义敌人的坦克组Vector<EnemyTank> ets=new Vector<EnemyTank>();Vector<Node> nodes=new Vector<Node>();//定义炸弹集合Vector<Bomb> bombs=new Vector<Bomb>();int enSize=5;//定义三张图片Image image1=null;Image image2=null;Image image3=null;//构造方法public MyPanel(String flag){//恢复记录Recorder.getRecording();hero=new Hero(30,231);if(flag.equals("newGame")){//初始化敌人的坦克for(int i=0;i<enSize;i++){//创建一辆敌人的坦克对象EnemyTank et=new EnemyTank((i+1)*50,0);et.setColor(0);et.setDirect(2);//将MyPanel的敌人坦克向量交给该敌人坦克et.setEts(ets);//启动敌人的坦克Thread t=new Thread(et);t.start();//给敌人的坦克添加一颗子弹Shot s=new Shot(et.x+10, et.y+30, 2,1);et.ss.add(s);new Thread(s).start();ets.add(et);//加入}}else{nodes=new Recorder().getNodesAndEnNums();//初始化敌人的坦克for(int i=0;i<nodes.size();i++){Node node=nodes.get(i);//创建一辆敌人的坦克对象EnemyTank et=new EnemyTank(node.x,node.y);et.setColor(0);et.setDirect(node.direct);//将MyPanel的敌人坦克向量交给该敌人坦克et.setEts(ets);//启动敌人的坦克Thread t=new Thread(et);t.start();//给敌人的坦克添加一颗子弹Shot s=new Shot(et.x+10, et.y+30, 2,1);et.ss.add(s);new Thread(s).start();ets.add(et);//加入}}/*try {image1=ImageIO.read(new File("/bomb_1.gif"));image2=ImageIO.read(new File("/bomb_2.gif"));image3=ImageIO.read(new File("/bomb_3.gif"));} catch (Exception e) {e.printStackTrace();// TODO: handle exception}*///播放开战声音AePlayWave apw=new AePlayWave("F:\\myjava\\day9\\坦克大战\\TankGamae13\\src\\111.wav");apw.start();//初始化图片image1=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource( "/bomb_1.gif"));image2=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource( "/bomb_2.gif"));image3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource( "/bomb_3.gif"));}//画出提示信息public void showInfo(Graphics g){//画出提示信息坦克(该坦克不参与战斗)this.drawTank(100, 320, g, 0, 0);g.setColor(Color.black);g.drawString(Recorder.getEnNum()+"", 128, 343);this.drawTank(165, 320, g, 0, 1);g.setColor(Color.black);g.drawString(Recorder.getMyLife()+"", 195, 343);//画出玩家的总成绩g.setColor(Color.black);Font f=new Font("宋体",Font.BOLD,20);g.setFont(f);g.drawString("您的总成绩", 410, 25);this.drawTank(420, 60, g, 0, 0);g.setColor(Color.black);g.drawString(Recorder.getAllEnNum()+"", 455, 80);}//重写paint函数public void paint(Graphics g){super.paint(g);g.fillRect(0,0,400,300);//画出提示信息this.showInfo(g);//画出自己的坦克if(hero.isLive){this.drawTank(hero.getX(),hero.getY(),g,hero.getDirect(),1);}//从ss中取出每一颗子弹并绘制for(int i=0;i<hero.ss.size();i++){Shot myShot =hero.ss.get(i);//画出子弹if(myShot!=null&&myShot.isLive==true){g.draw3DRect(myShot.x, myShot.y, 1, 1, false);}if(myShot.isLive==false){//从ss中删除掉该子弹hero.ss.remove(myShot);}}//画出炸弹for(int i=0;i<bombs.size();i++){Bomb b=bombs.get(i);if(b.life>6){g.drawImage(image1, b.x, b.y, 30, 30,this);}else if(b.life>3){g.drawImage(image2, b.x, b.y, 30, 30,this);}else{g.drawImage(image3, b.x, b.y, 30, 30,this);}//让b的生命值减小b.lifeDown();if(b.life==0){//把炸弹从向量中去掉bombs.remove(b);}}//画出敌人的坦克for(int i=0;i<ets.size();i++){ EnemyTank et=ets.get(i);if(et.isLive){this.drawTank(et.getX(),et.getY(), g, et.getDirect(), 0);//顺便画出敌人的子弹for(int j=0;j<et.ss.size();j++){//取出子弹Shot enemyShot=et.ss.get(j);if(enemyShot.isLive){g.draw3DRect(enemyShot.x, enemyShot.y, 1, 1, false);}else{//如果死亡了,就从Vextor中删除掉et.ss.remove(enemyShot);}}}}}//判断我的子弹是否会击中敌人的坦克public void hitEnemyTank(){//判断是否会击中for(int i=0;i<hero.ss.size();i++){//取出子弹Shot myShot=hero.ss.get(i);//判断子弹是否有效if(myShot.isLive){//取出每一个敌人坦克与之匹配for(int j=0;j<ets.size();j++){//取出坦克EnemyTank et=ets.get(j);if(et.isLive){if(this.hitTank(myShot, et)){ //减少敌人数量Recorder.reduceEnNum();//增加我的记录Recorder.addEnEnum();}}}}}}//我是否被击中public void hitMe(){//取出每一个敌人的坦克for(int i=0;i<this.ets.size();i++){//取出坦克EnemyTank et=ets.get(i);//取出每颗子弹for(int j=0;j<et.ss.size();j++){//取出子弹Shot enemyShot=et.ss.get(j);if(hero.isLive){if(this.hitTank(enemyShot, hero)){//待写}}}}}//画出一个专门判断子弹是否击中敌人坦克的函数public boolean hitTank(Shot s ,Tank et){boolean b2=false;//判断该坦克的方向switch(et.direct){//敌人坦克的方向是向上或者向下case 0:case 2:if(s.x>et.x&&s.x<et.x+20&&s.y>et.y&&s.y<et.y+30){//击中//子弹死亡s.isLive=false;//敌人坦克死亡et.isLive=false;b2=true;//System.out.println("hytfyfrujyg");//创建一颗炸弹放入VectorBomb b=new Bomb(et.x, et.y);bombs.add(b);}break;case 1:case 3:if(s.x>et.x&&s.x<et.x+30&&s.y>et.y&&s.y<et.y+20){//击中//子弹死亡s.isLive=false;//敌人坦克死亡et.isLive=false;b2=true;Bomb b=new Bomb(et.x, et.y);bombs.add(b);}break;}return b2;}//画出坦克的函数(扩展)public void drawTank(int x,int y,Graphics g,int direction,int type) {//判断类型switch(type){case 0:g.setColor(Color.CYAN);break;case 1:g.setColor(Color.yellow);break;}//判断方向switch(direction){//向上走case 0://g.setColor(Color.CYAN);//画出我的坦克(到时再封装成一个函数)//1.画出左边的矩形g.fill3DRect(x,y,5,30,false);//2.画出右边边的矩形g.fill3DRect(x+15,y,5,30,false);//3画出中间的矩形g.fill3DRect(x+5,y+5,10,20,false);//4画圆形g.fillOval(x+5,y+10,10,10);//5.画出线g.drawLine(x+10,y+15,x+10,y);break;case 1://向右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+30, y+10);break;case 2://向下g.fill3DRect(x,y,5,30,false);//2.画出右边边的矩形g.fill3DRect(x+15,y,5,30,false);//3画出中间的矩形g.fill3DRect(x+5,y+5,10,20,false);//4画圆形g.fillOval(x+5,y+10,10,10);//5.画出线g.drawLine(x+10,y+15,x+10,y+30);break;case 3://向左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, y+10);break;}}@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stub}@Override//w上,s下,a左,右边public void keyPressed(KeyEvent e) {// TODO Auto-generated method stubif(e.getKeyCode()==KeyEvent.VK_W){//设置我的坦克的方向上this.hero.setDirect(0);if(this.hero.y>0){this.hero.moveUp();}}else if(e.getKeyCode()==KeyEvent.VK_D){//设置我的坦克的方向右边this.hero.setDirect(1);if(this.hero.x<370){this.hero.moveRight();}}else if(e.getKeyCode()==KeyEvent.VK_S){//设置我的坦克的方向 xia边this.hero.setDirect(2);if(this.hero.y<=271){this.hero.moveDown();}}else if(e.getKeyCode()==KeyEvent.VK_A){//设置我的坦克的方向左边this.hero.setDirect(3);if(this.hero.x>0){this.hero.moveLeft();}}if(e.getKeyCode()==KeyEvent.VK_K){//玩家按了一个k键,开火if(this.hero.ss.size()<=5){this.hero.shotEnemy();}}//必须用repaintPanelthis.repaint();}@Overridepublic void keyReleased(KeyEvent e) {// TODO Auto-generated method stub }@Overridepublic void run() {// TODO Auto-generated method stub//每隔100毫秒去重画while(true){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.hitEnemyTank();this.hitMe();//重绘this.repaint();}}}Members.javapackage test;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 AePlayWave extends Thread {private String filename;public AePlayWave(String wavfile) {filename = wavfile;}public void run() {File soundFile = new File(filename);AudioInputStream audioInputStream = null;try {audioInputStream = AudioSystem.getAudioInputStream(soundFile);} catch (Exception e1) {e1.printStackTrace();return;}AudioFormat format = audioInputStream.getFormat();SourceDataLine auline = null; info = new (SourceDataLine.class, format);try {auline = (SourceDataLine) AudioSystem.getLine(info);auline.open(format);} catch (Exception e) {e.printStackTrace();return;}auline.start();int nBytesRead = 0;byte[] abData = new byte[512];try {while (nBytesRead != -1) {nBytesRead = audioInputStream.read(abData, 0, abData.length);if (nBytesRead >= 0)auline.write(abData, 0, nBytesRead);}} catch (IOException e) {e.printStackTrace();return;} finally {auline.drain();auline.close();}}}class Node//恢复点{int x,y,direct;public Node(int x,int y,int direct){this.x=x;this.y=y;this.direct=direct;}}//记录类,同时也可以保存一些设置class Recorder{//记录每关有多少敌人private static int enNum=5;//设置我有多少可用的人private static int myLife=3;//记录总共消灭了多少敌人private static int allEnNum=0;//从文件中恢复记录点static Vector<Node> nodes=new Vector<Node>();private static FileWriter fw=null;private static BufferedWriter bw=null;private static FileReader fr=null;private static BufferedReader br=null;private Vector <EnemyTank> ets=new Vector<EnemyTank>();public Vector<EnemyTank> getEts() {return ets;}public void setEts(Vector<EnemyTank> ets) {this.ets = ets;}//完成读取任务public Vector<Node> getNodesAndEnNums(){try {fr=new FileReader("F:\\myRecording.txt");br=new BufferedReader(fr);String n="";//先读取第一行n=br.readLine();allEnNum=Integer.parseInt(n);while((n=br.readLine())!=null){String []xyz=n.split(" ");Node node=new Node(Integer.parseInt(xyz[0]),Integer.parseInt(xyz[1]),Integer.parseInt(xyz[2]));nodes.add(node);}} catch (Exception e) {e.printStackTrace();// TODO: handle exception}finally{try {br.close();fr.close();} catch (Exception e2) {// TODO: handle exception}}return nodes;}//保存击毁敌人坦克的数量和敌人坦克的坐标,方向public void keepRecAndEnemyTank(){try {//创建fw=new FileWriter("F:\\myRecording.txt");bw=new BufferedWriter(fw);bw.write(allEnNum+"\r\n");//保存当前还活着的坐标和方向for(int i=0;i<ets.size();i++){//取出第一个坦克EnemyTank et=ets.get(i);if(et.isLive){String record=et.x+" "+et.y+" "+et.direct;//写入到文件bw.write(record+"\r\n");}}} catch (Exception e) {// TODO: handle exception}finally{//关闭流try {bw.close();fw.close();} catch (Exception e2) {// TODO: handle exception}}}//从文件中读取记录public static void getRecording(){try {fr=new FileReader("F:\\myRecording.txt");br=new BufferedReader(fr);String n=br.readLine();allEnNum=Integer.parseInt(n);} catch (Exception e) {e.printStackTrace();// TODO: handle exception}finally{try {br.close();fr.close();} catch (Exception e2) {// TODO: handle exception}}}//把玩家击毁敌人的坦克数量保存到文件中public static void keepRecording(){try {//创建fw=new FileWriter("F:\\myRecording.txt");bw=new BufferedWriter(fw);bw.write(allEnNum+"\r\n");} catch (Exception e) {// TODO: handle exception}finally{//关闭流try {bw.close();fw.close();} catch (Exception e2) {// TODO: handle exception}}}public static int getAllEnNum() {return allEnNum;}public static void setAllEnNum(int allEnNum) { Recorder.allEnNum = allEnNum;}public static int getEnNum() {return enNum;}public static void setEnNum(int enNum) {Recorder.enNum = enNum;}public static int getMyLife() {return myLife;}public static void setMyLife(int myLife) { Recorder.myLife = myLife;}//减少敌人数public static void reduceEnNum(){enNum--;}//消灭敌人public static void addEnEnum(){allEnNum++;}}//炸弹类class Bomb{int x,y;//炸弹的生命int life=9;boolean isLive=true;public Bomb(int x,int y){this.x=x;this.y=y;}//减少生命值public void lifeDown(){if(life>0){life--;}else{this.isLive=false;}}}//子弹类class Shot implements Runnable{int x,y;int direct;int speed=1;//是否还活着boolean isLive=true;public Shot(int x,int y,int direct,int speed) {this.x=x;this.y=y;this.direct=direct;this.speed=speed;}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}switch(direct){case 0://向上y-=speed;break;case 1://向右x+=speed;break;case 2://下y+=speed;break;case 3:x-=speed;break;}//子弹何时死亡if(x<0||x>400||y<0||y>300){this.isLive=false;break;}//System.out.println(x+""+y);}}}//坦克类class Tank{int x=0;int y=0;//定义方向的值0上,右2,下3,左int direct=0;//坦克的速度int speed=1;int color=0;boolean isLive=true;public int getColor() {return color;}public void setColor(int color) {this.color = color;}public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public int getDirect() {return direct;}public void setDirect(int direct) {this.direct = direct;}public Tank(int x,int y){this.x=x;this.y=y;}public int getX(){return x;}public int getY(){return y;}public void setX(int x){this.x=x;}public void setY(int y){this.y=y;}}//敌人的坦克 ,做成线程class EnemyTank extends Tank implements Runnable {//boolean isLive=true;int times=0;//定义一个向量,可以访问到MyPanel上所有敌人的坦克Vector<EnemyTank> ets=new Vector<EnemyTank>();//定义一个向量,可以存放敌人的子弹Vector <Shot> ss=new Vector<Shot>();//敌人添加子弹应当在刚刚创建坦克和敌人的坦克子弹死亡之后public EnemyTank(int x, int y){super(x, y);}//得到MyPanel的敌人坦克向量public void setEts(Vector<EnemyTank>vv){this.ets=vv;}//判断是否碰到了别人的敌人的坦克public boolean isTouchOtherEnemy(){boolean b=false;//..。

坦克大战游戏编程实现

坦克大战游戏编程实现

坦克大战游戏编程实现游戏编程实现坦克大战坦克大战是一款经典的电子游戏,在游戏中,玩家将控制一个坦克,通过操作坦克的移动和攻击,与其他玩家或电脑进行战斗。

本文将介绍如何使用编程语言实现坦克大战游戏。

设计思路在实现坦克大战游戏之前,首先需要明确游戏的基本要素和规则。

玩家将操作一个坦克,通过键盘或操纵杆控制坦克的移动和攻击。

游戏画面由地图、坦克、子弹等元素构成。

坦克可以向前、向后、向左、向右移动,可以发射子弹进行攻击。

玩家需要躲避敌方坦克的攻击,同时尽可能击败敌方坦克。

编程实现坦克的移动和攻击可以通过编程语言来实现。

以下是使用Java语言来编写坦克大战游戏的示例代码:```javapublic class TankGame extends JFrame {private Tank tank; // 玩家坦克private List<Tank> enemyTanks; // 敌方坦克列表private List<Bullet> bullets; // 子弹列表public TankGame() {// 初始化游戏窗口this.setSize(800, 600);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true);// 初始化玩家坦克tank = new Tank(400, 500);// 初始化敌方坦克列表enemyTanks = new ArrayList<>();enemyTanks.add(new Tank(100, 100));enemyTanks.add(new Tank(300, 200));// 初始化子弹列表bullets = new ArrayList<>();// 添加键盘监听器,控制坦克移动和攻击this.addKeyListener(new KeyListener() {@Overridepublic void keyPressed(KeyEvent e) {int keycode = e.getKeyCode();switch (keycode) {case KeyEvent.VK_UP:tank.moveUp();break;case KeyEvent.VK_DOWN: tank.moveDown();break;case KeyEvent.VK_LEFT: tank.moveLeft();break;case KeyEvent.VK_RIGHT: tank.moveRight();break;case KeyEvent.VK_SPACE: bullets.add(tank.fire());break;default:break;}// 重新绘制游戏画面repaint();}@Overridepublic void keyReleased(KeyEvent e) { }@Overridepublic void keyTyped(KeyEvent e) { }});}// 绘制游戏画面public void paint(Graphics g) {super.paint(g);// 绘制玩家坦克tank.draw(g);// 绘制敌方坦克for (Tank enemyTank : enemyTanks) { enemyTank.draw(g);}// 绘制子弹for (Bullet bullet : bullets) {bullet.draw(g);}}public static void main(String[] args) {new TankGame();}}```在上述示例代码中,我们创建了一个继承自JFrame的主窗口,并在窗口中添加了一个玩家坦克、敌方坦克和子弹的列表。

JAVA 坦克大战中的子弹代码 Tank

JAVA 坦克大战中的子弹代码 Tank
br = false;
break;
}
}
}
}
public void mydraw(Graphics g){
Color c = g.getColor();
g.setColor(Color.pink);
g.fillRect(x, y, 50, 50);
g.setColor(c);
move();
this.x = x;
this.y = y;
}
/*
* 无参的构造函数
*/
public void move(){
switch(tkdir){
case L:
x = x - 5;
break;
case LU:
x = Байду номын сангаас - 5;
tkdir = myTankDir.RD;
if(!bl&&!bu&&!br&&bd)
tkdir = myTankDir.D;
if(bl&&!bu&&!br&&bd)
tkdir = myTankDir.LD;
if(!bl&&!bu&&!br&&!bd)
tkdir = myTankDir.STOP;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
class Tank {
int x ;
int y ;

JAVA课程设计坦克大战(含代码)

JAVA课程设计坦克大战(含代码)

Java程序课程设计任务书项目名称:坦克大战游戏的设计与开发英文名:Tank Battle1、主要内容:1、基于java的游戏开发与设计的分析;2、坦克大战游戏的架构搭建与设计实现;3、游戏可以通过用户可以注册新用户,修改自己的密码、个人资料。

2、具体要求1、系统的功能要求:(一)实现玩家试玩游戏功能,屏蔽用户注册和登陆功能(空功能)(二)玩家具备一个或者两个备选坦克战车(三)玩家可以选择一个到两个关卡进行作战(四)玩家可以选择两个敌对阵营中的一个加入,与其他AI战车坦克并肩作战(五)胜利判定条件为:时间制、全杀制(可选)(六)至少提供两个可以自由切换的视角(七)至少提供一种炮弹类型(八)假定项目:如果用户注册,登陆功能能够顺利做好,则提供一个玩家分数上传和排行榜功能。

2、学习并掌握以下技术:数据库的JDBC连接,JA V A编程语言,MySQL数据库的应用;JSP的开发与运用3、熟练使用以下开发工具:JCreator,Myeclipse ,MySQL ,PowerDesigner 等3、进度安排:12月28日~ 12 月29 日:查阅资料,完成文献综述,任务书;12月29 日~ 12月31日:进行系统的需求分析与设计;1月1日~ 1月3日:根据分析进行各个模块程序的设计与创建;1月4日~ 1 月6日:完成各个模块的程序编写;1月7 日~ 1 月8 日:完成全部程序的编写及系统测试;1月9日~ 1 月10日:完成课程设计报告的编写,答辩;摘要随着Java语言的不断发展和壮大,现在的Java已经广泛的应用于各个领域,包括医药,汽车工业,手机行业,游戏,等等地方。

Java游戏的开发为满足人们娱乐所需而设计。

本游戏为坦克大战游戏,是基于Java的图形用户界面而开发的,可以放松心情的小游戏。

游戏从系统操作简便、界面友好、灵活、上手即会的基本要求出发,完成整款游戏的开发。

游戏更设置了暂停、计分、音乐、速度,用户信息保存等功能,可以根据自己的爱好,挑战更高难度,为用户带来愉悦的体验。

JAVA课程设计坦克大战(含代码)

JAVA课程设计坦克大战(含代码)

Java程序课程设计任务书项目名称:坦克大战游戏的设计与开发英文名:Tank Battle1、主要内容:1、基于java的游戏开发与设计的分析;2、坦克大战游戏的架构搭建与设计实现;3、游戏可以通过用户可以注册新用户,修改自己的密码、个人资料。

2、具体要求1、系统的功能要求:(一)实现玩家试玩游戏功能,屏蔽用户注册和登陆功能(空功能)(二)玩家具备一个或者两个备选坦克战车(三)玩家可以选择一个到两个关卡进行作战(四)玩家可以选择两个敌对阵营中的一个加入,与其他AI战车坦克并肩作战(五)胜利判定条件为:时间制、全杀制(可选)(六)至少提供两个可以自由切换的视角(七)至少提供一种炮弹类型(八)假定项目:如果用户注册,登陆功能能够顺利做好,则提供一个玩家分数上传和排行榜功能。

2、学习并掌握以下技术:数据库的JDBC连接,JA V A编程语言,MySQL数据库的应用;JSP的开发与运用3、熟练使用以下开发工具:JCreator,Myeclipse ,MySQL ,PowerDesigner 等3、进度安排:12月28日~ 12 月29 日:查阅资料,完成文献综述,任务书;12月29 日~ 12月31日:进行系统的需求分析与设计;1月1日~ 1月3日:根据分析进行各个模块程序的设计与创建;1月4日~ 1 月6日:完成各个模块的程序编写;1月7 日~ 1 月8 日:完成全部程序的编写及系统测试;1月9日~ 1 月10日:完成课程设计报告的编写,答辩;摘要随着Java语言的不断发展和壮大,现在的Java已经广泛的应用于各个领域,包括医药,汽车工业,手机行业,游戏,等等地方。

Java游戏的开发为满足人们娱乐所需而设计。

本游戏为坦克大战游戏,是基于Java的图形用户界面而开发的,可以放松心情的小游戏。

游戏从系统操作简便、界面友好、灵活、上手即会的基本要求出发,完成整款游戏的开发。

游戏更设置了暂停、计分、音乐、速度,用户信息保存等功能,可以根据自己的爱好,挑战更高难度,为用户带来愉悦的体验。

java 坦克大战游戏教程完整代码

java 坦克大战游戏教程完整代码

项目:用java做的坦克大战效果图:进入《坦克大战》游戏主界面点击开始菜单,即可进入游戏:使用W/A/S/D控制坦克移动,使用J发射子弹消灭所有坦克游戏获得胜利,被击中后,游戏将会结束:完整代码见下文,需要准备一个进入坦克大战的音乐声音,放在TankVs.java代码文件的同路径的shengyin文件夹下。

(没有也可以)代码运行方法:1,在以及配置好java JDK的情况下,将下面的完整的代码复制到并粘贴到记事本内,并将后缀.txt改为.java,文件命名为TankVs.java。

2,运行cmd,使用javac TankVs.java命令编译该java文件,编译成功后,使用java TankVs 命令即可运行游戏。

//以下为完整的坦克游戏代码import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.util.*;import java.io.*;import javax.sound.sampled.*;//导入声音类包public class TankVs extends JFrame implements ActionListener,Runnable{OverPanel op=null;WinPanel wp=null;FirstPanel fmp=null;MyPanel mp=null;JMenuBar jmb=null;JMenu jm=null;JMenuItem jmi=null;public static void main(String[] args){TankVs tk1=new TankVs();}public TankVs(){fmp=new FirstPanel();jmb=new JMenuBar();jm=new JMenu("开始");jmi=new JMenuItem("开始游戏");jm.add(jmi);jmb.add(jm);this.setJMenuBar(jmb);this.add(fmp);jmi.addActionListener(this);//添加单击事件监听this.setSize(1000,800);this.setLocation(200,100);this.setTitle("坦克大战");//文件的路径自己改一下this.setIconImage(new ImageIcon("D:\\JAVA\\高级\\坦克大战\\image\\tank.jpg").getImage());this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setResizable(false);this.setVisible(true);Thread t=new Thread(fmp);t.start();}public void actionPerformed(ActionEvent e){if(fmp!=null){this.remove(fmp);}if(op!=null){this.remove(op);}if(wp!=null){this.remove(wp);}mp=new MyPanel();mp.repaint();this.addKeyListener(mp);//添加键盘事件监听this.add(mp);Thread t=new Thread(mp);t.start();this.setVisible(true);Thread t1=new Thread(this);t1.start();shengyin sy=new shengyin(".\\shengyin\\tank.wav");sy.start();}public void run(){while(true){try{Thread.sleep(50);}catch(Exception e){}if(this.mp.dtk.size()==0){try{Thread.sleep(1000);}catch(Exception e){}this.wp=new WinPanel();this.add(wp);this.remove(mp);this.setVisible(true);}if(this.mp.mt.shengming==false){try{Thread.sleep(1000);}catch(Exception e){}this.op=new OverPanel();this.add(op);this.remove(mp);this.setVisible(true);}}}}class FirstPanel extends JPanel implements Runnable{int times=0;public void paint(Graphics g){super.paint(g);g.fillRect(0,0,800,600);if(times%2==0){g.setColor(Color.yellow);Font myFont=new Font("华文行楷",Font.BOLD,80);g.setFont(myFont);g.drawString("坦克大战",230,300);}}public void run(){while(true){try{Thread.sleep(500);}catch(Exception e){}times++;this.repaint();}}}class OverPanel extends JPanel{public void paint(Graphics g){super.paint(g);g.fillRect(0,0,800,600);g.setColor(Color.yellow);g.setFont(new Font("Cambria",Font.BOLD,80));g.drawString("GAME OVER",200,300);}}class WinPanel extends JPanel{public void paint(Graphics g){super.paint(g);g.fillRect(0,0,800,600);g.setColor(Color.yellow);g.setFont(new Font("Cambria",Font.BOLD,80));g.drawString("YOU WIN",200,300);}}class MyPanel extends JPanel implements KeyListener,Runnable{WoTank mt=null;Vector<DiTank> dtk=new Vector<DiTank>();//集合类+泛型,Vector适用与多线程,int tks=12;public MyPanel(){mt=new WoTank(260,500);mt.setSudu(8);for(int i=0;i<tks;i++){DiTank dt=new DiTank((750/(tks-1))*i,20);dt.setSudu(2);dtk.add(dt);Thread t=new Thread(dt);//启动敌人坦克线程t.start();}}public void paint(Graphics g){super.paint(g);g.fillRect(0,0,800,600);if(mt.shengming==true){this.drawTank(mt.getX(),mt.getY(),g,mt.getFangxiang(),0);//绘制我方坦克}for(int i=0;i<dtk.size();i++){DiTank dt=dtk.get(i);this.drawTank(dt.getX(),dt.getY(),g,dt.getFangxiang(),1);if(dt.zd.shengming==true){g.setColor(Color.white);g.fill3DRect(dt.zd.x,dt.zd.y,3,3,false);//绘制敌方坦克}}for(int i=0;i<mt.aa.size();i++)//绘制子弹{Zidan zd=mt.aa.get(i);if(zd.shengming==true && mt.shengming==true){g.setColor(Color.red);g.fill3DRect(zd.x,zd.y,3,3,false);}if(zd.shengming==false){mt.aa.remove(zd);}}}public void drawTank(int x,int y,Graphics g,int fangxiang,int leixing){switch(leixing){case 0://我的坦克g.setColor(Color.yellow);break;case 1://敌人的坦克g.setColor(Color.green);break;}switch(fangxiang){case 0://上方向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://左方向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 2://下方向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 3://右方向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+33,y+10);break;}}public void keyTyped(KeyEvent e){}public void keyReleased(KeyEvent e){}public void keyPressed(KeyEvent e){if(mt.shengming==true){if(e.getKeyCode()==KeyEvent.VK_W){this.mt.setFangxiang(0);this.mt.xiangshang();}else if(e.getKeyCode()==KeyEvent.VK_A)this.mt.setFangxiang(1);this.mt.xiangzuo();}else if(e.getKeyCode()==KeyEvent.VK_S){this.mt.setFangxiang(2);this.mt.xiangxia();}else if(e.getKeyCode()==KeyEvent.VK_D){this.mt.setFangxiang(3);this.mt.xiangyou();}if(e.getKeyCode()==KeyEvent.VK_J){if(mt.aa.size()<8)//允许我的坦克同时存在8颗子弹{this.mt.fszd();Thread t=new Thread(this);//启动画板线程t.start();}}}this.repaint();}public void run(){while(mt.zd.shengming==true ||dtk.size()>0){try{Thread.sleep(50);}catch(Exception e){}for(int i=0;i<mt.aa.size();i++){Zidan zd=mt.aa.get(i);for(int j=0;j<dtk.size();j++){DiTank dt=dtk.get(j);this.jzdf(zd,dt);}for(int i=0;i<dtk.size();i++){DiTank dt=dtk.get(i);this.jzwf(dt.zd,mt);}this.repaint();//System.out.println("线程1");}}public void jzdf(Zidan zd,DiTank dt)//击中敌方{switch(dt.fangxiang){case 0:case 2:if(zd.x>dt.getX() && zd.x<dt.getX()+20 && zd.y>dt.getY() && zd.y<dt.getY()+30){zd.shengming=false;dt.shengming=false;mt.aa.remove(zd);dtk.remove(dt);}break;case 1:case 3:if(zd.x>dt.getX() && zd.x<dt.getX()+30 && zd.y>dt.getY() && zd.y<dt.getY()+20){zd.shengming=false;dt.shengming=false;mt.aa.remove(zd);dtk.remove(dt);}break;}}public void jzwf(Zidan zd,WoTank mt)//击中我方{if(mt.shengming==true){switch(mt.fangxiang){case 0:case 2:if(zd.x>mt.getX() && zd.x<mt.getX()+20 && zd.y>mt.getY() && zd.y<mt.getY()+30){zd.shengming=false;mt.shengming=false;}break;case 1:case 3:if(zd.x>mt.getX() && zd.x<mt.getX()+30 && zd.y>mt.getY() && zd.y<mt.getY()+20){zd.shengming=false;mt.shengming=false;}break;}}}}class Tank{private int x=0,y=0;int fangxiang=0;int sudu=1;boolean shengming=true;public int getSudu(){return sudu;}public void setSudu(int sudu){this.sudu=sudu;}public int getFangxiang(){return fangxiang;}public void setFangxiang(int fangxiang){this.fangxiang=fangxiang;}public int getX(){return x;}public int getY(){return y;}public void setX(int x){this.x=x;}public void setY(int y){this.y=y;}public Tank(int x,int y){this.x=x;this.y=y;}}class WoTank extends Tank{Zidan zd=new Zidan();Vector<Zidan> aa=new Vector<Zidan>();public WoTank(int x,int y){super(x,y);}public void xiangshang(){if(getY()-sudu>0){this.setY(this.getY()-sudu);}}public void xiangzuo(){if(getX()-sudu>0){this.setX(this.getX()-sudu);}}public void xiangxia(){if(getY()+sudu<520){this.setY(this.getY()+sudu);}}public void xiangyou(){if(getX()+sudu<750){this.setX(this.getX()+sudu);}}public void fszd(){switch(this.fangxiang){case 0:zd=new Zidan(super.getX()+10,super.getY(),super.getFangxiang(),true);break;case 1:zd=new Zidan(super.getX(),super.getY()+10,super.getFangxiang(),true);break;case 2:zd=new Zidan(super.getX()+10,super.getY()+30,super.getFangxiang(),true);break;case 3:zd=new Zidan(super.getX()+30,super.getY()+10,super.getFangxiang(),true);break;}aa.add(zd);Thread t=new Thread(zd);//启动子弹线程t.start();}}class Zidan implements Runnable{int x;int y;int fangxiang;int sudu=8;public boolean shengming=false;public Zidan(){}public Zidan(int x,int y,int fangxiang,boolean shengming){this.x=x;this.y=y;this.fangxiang=fangxiang;this.shengming=shengming;}public void run(){while(true){try{Thread.sleep(50);//凡是线程下的死循环,都要有个睡眠}catch(Exception e){}switch(fangxiang){case 0:y-=sudu;break;case 1:x-=sudu;break;case 2:y+=sudu;break;case 3:x+=sudu;break;}if(x<0 ||y<0 ||x>800 ||y>600){this.shengming=false;break;}//System.out.println("线程2");}}}class DiTank extends Tank implements Runnable{Zidan zd=new Zidan();public DiTank(int x,int y){super(x,y);}public void run(){while(this.shengming=true){try{Thread.sleep(50);}catch(Exception e){}this.fangxiang=(int)(Math.random()*4);switch(this.fangxiang){case 0:for(int i=0;i<30;i++){if(getY()-sudu<0) {break;}this.setY(this.getY()-sudu);try{Thread.sleep(50);}catch(Exception e){}}break;case 1:for(int i=0;i<30;i++)if(getX()-sudu<0) {break;}this.setX(this.getX()-sudu);try{Thread.sleep(50);}catch(Exception e){}}break;case 2:for(int i=0;i<30;i++){if(getY()+sudu>520) {break;}this.setY(this.getY()+sudu);try{Thread.sleep(50);}catch(Exception e){}}break;case 3:for(int i=0;i<30;i++){if(getX()+sudu>750) {break;}this.setX(this.getX()+sudu);try{Thread.sleep(50);}catch(Exception e){}}break;}if(this.zd.shengming==false){switch(fangxiang){case 0:zd=new Zidan(super.getX()+10,super.getY(),super.getFangxiang(),true);break;zd=new Zidan(super.getX(),super.getY()+10,super.getFangxiang(),true);break;case 2:zd=newZidan(super.getX()+10,super.getY()+30,super.getFangxiang(),true);break;case 3:zd=newZidan(super.getX()+30,super.getY()+10,super.getFangxiang(),true);break;}Thread t=new Thread(zd);t.start();}}}}class shengyin extends Thread//播放声音的类{private String wjm;public shengyin(String ypwj){wjm=ypwj;}public void run(){File wjl=new File(wjm);AudioInputStream ypsrl=null;//AudioInputStream类:音频输入流try{ypsrl=AudioSystem.getAudioInputStream(wjl);}catch(Exception e){}AudioFormat format=ypsrl.getFormat();SourceDataLine aqsj=null; info=new (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();}}}。

坦克大战java

坦克大战java

Java坦克大战图片版V3.4(加入各种类型墙的图片)【严重模仿90坦克】作者:Magci 日期:2008-04-25 06:49 PM字体大小: 小中大3.4版更新内容:加入各种类型墙的图片:1.石墙:炮弹、坦克都不能穿透;1.砖墙:炮弹能打掉,坦克不能穿透;3.河流:炮弹能穿透,坦克不能穿透;4.草地:炮弹、坦克都能穿透。

TankClient.java:程序代码package .ahau.mgc.tankwar;import java.awt.*;import java.awt.event.*;import java.util.*;import java.util.List;/*** 此类用于创建游戏窗体* @author Magci**/public class TankClient extends Frame {public static final int WINDOW_Y = 100;/*** 窗体宽度*/public static final int WINDOW_WIDTH = 800; /*** 窗体高度*/public static final int WINDOW_HEIGHT = 600; /*** 坦克起始位置左上角X坐标*/public static final int Tank_X = 400;/*** 坦克起始位置左上角Y坐标*/public static final int Tank_Y = 540;/*** 窗体刷新率*/public static final int REFRESH_RATE = 50; /*** 墙起始点X坐标*/public static final int WALL_X = 4;/*** 墙起始点Y坐标*/public static int WALL_Y = 75;//窗体左上角X坐标private int windowX = 0;//窗体左上角Y坐标private int windowY = 0;//敌方坦克总数量private int tankAllNum;//敌方坦克同时出现的最大数量private int tankMaxNum;//当前敌方坦克数量private int tankNum = 0;//我方坦克总数量private int myTankNum;//用于双缓冲的图片Image offScreenImage = null;//我方坦克Tank myTank = null;//存放敌方坦克的容器List<Tank> enemyTanks = new ArrayList<Tank>();//存放炮弹的容器List<Missile> missiles = new ArrayList<Missile>();//存放爆炸的容器List<Explode> explodes = new ArrayList<Explode>();//存放爆炸的容器List<Wall> walls = new ArrayList<Wall>();//宝物Treasure trea = null;//用于生成随机数Random rand = new Random();public static void main(String[] args) {// 创建一个窗体new TankClient("TankClient", 20, 5, 3);}/*** 根据标题,敌我坦克数量创建一个窗体* @param title 窗体标题* @param tankAllNum 敌方坦克总数量* @param tankMaxNum 敌方坦克同时出现的最大数量* @param myTankNum 我方坦克总数量*/public TankClient(String title, int tankAllNum, int tankMaxNum, int myTankNum) { super(title);this.tankAllNum = tankAllNum;this.tankMaxNum = tankMaxNum;this.myTankNum = myTankNum;windowX = Integer.parseInt(PropertyMgr.getProperty("windowX"));windowY = Integer.parseInt(PropertyMgr.getProperty("windowY"));this.setBounds(windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT); this.setResizable(false);this.setBackground(Color.BLACK);this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {setVisible(false);System.exit(0);}});this.addKeyListener(new KeyMonitor());this.setVisible(true);myTank = new Tank(Tank_X, Tank_Y, 4, true, this);//加入敌方坦克for (int i = 0; i < tankMaxNum; i++) {Tank enemyTank = new Tank(22 + 180 * i, 40, 4, false, this);enemyTanks.add(enemyTank);this.tankNum ++;}//加入墙String sytle = null;for (int i = 0; i < 29; i++) {for (int j = 0; j < 44; j++) {if (i == 0) {if (j % 10 == 1 || j % 10 == 2) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "stone", this); walls.add(wall);}}if (i > 0 && i < 10) {if (j != 4 && j != 5 && j != 20 && j != 21 && j != 39 && j != 40) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "tile", this); walls.add(wall);}}if (i >= 10 && i < 12) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "grass", this);walls.add(wall);}if (i >= 12 && i < 14) {if (j > 10 && j < 34) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "river", this); walls.add(wall);} else {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "grass", this); walls.add(wall);}}if (i >= 14 && i < 16) {if (j == 0 || j == 1 || j == 42 || j == 43) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "stone", this); walls.add(wall);}}if (i >= 16 && i < 18) {if (j % 8 < 4) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "stone", this); walls.add(wall);}}if (i >= 18 && i < 25) {if (j % 10 < 8) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "tile", this); walls.add(wall);}}if (i >= 25 && i < 29) {if (j < 8) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "grass", this); walls.add(wall);}if (j > 35) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "river", this); walls.add(wall);}if (i > 26 && (j == 16 || j == 17 || j == 28 || j == 29)) {Wall wall = new Wall(WALL_X + j * 18, WALL_Y + i * 18, "tile", this); walls.add(wall);}}}}// 启动重画线程PaintThread pt = new PaintThread();Thread t = new Thread(pt);t.start();}/*** 在窗体中画出游戏界面*/public void paint(Graphics g) {if (this == null)return;Color c = g.getColor();g.setColor(Color.RED);if (!myTank.isLive()) {if (-- this.myTankNum > 0) {myTank = new Tank(Tank_X, Tank_Y, 4, true, this); } else {g.drawString("GameOver!", 350, 280);g.drawString("按F2键重新开始..", 340, 300);return;}}if (tankAllNum == 0) {g.drawString(".:恭喜过关!:.", 350, 280);g.drawString("按F2键重新开始..", 340, 300);return;}g.setColor(c);this.reinforceTank();this.drawMissiles(g);this.drawMyTank(g);this.drawEnemyTanks(g);this.drawWalls(g);this.drawExplodes(g);this.drawTreasure(g);this.drawMessage(g);}/*** 重写update方法,先将窗体上的图形画在图片对象上,再一次性显示*/public void update(Graphics g) {if (offScreenImage == null) {offScreenImage = this.createImage(WINDOW_WIDTH, WINDOW_HEIGHT); }Graphics gImage = offScreenImage.getGraphics();Color c = gImage.getColor();gImage.setColor(Color.BLACK);gImage.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);gImage.setColor(c);paint(gImage);g.drawImage(offScreenImage, 0, 0, null);}/*** 用线程重画,每隔一段时间重画窗体* @author Magci**/private class PaintThread implements Runnable {/*** 每隔REFRESH_RATE毫秒重画一次窗体*/public void run() {while (true) {repaint();try {Thread.sleep(REFRESH_RATE);} catch (InterruptedException e) {e.printStackTrace();}}}}/*** 监听键盘事件,按方向键控制坦克移动* @author Magci**/private class KeyMonitor extends KeyAdapter {/*** 处理按键被按下事件*/public void keyPressed(KeyEvent e) {myTank.keyPressed(e);}/*** 处理按键被松开事件*/public void keyReleased(KeyEvent e) {myTank.keyReleased(e);}}/*** 敌方坦克增援*/public void reinforceTank() {if (tankNum < tankMaxNum && tankAllNum > tankNum) {int i = rand.nextInt(10);Tank enemyTank = new Tank(50 + 150 * i, 40, 4, false, this);if (!enemyTank.collidesWithTank(myTank, true) && !enemyTank.collidesWithTanks (enemyTanks, true)) {enemyTanks.add(enemyTank);this.tankNum ++;}}}/*** 加入墙* @param g Graphics对象*/public void drawWalls(Graphics g) {for (int i = 0; i < walls.size(); i++) { Wall wall = walls.get(i);wall.draw(g);}}/*** 画我方坦克* @param g Graphics对象*/public void drawMyTank(Graphics g) { if (myTank != null) {myTank.draw(g);if (trea != null)myTank.eatTreasure(trea);}}/*** 画敌方坦克* @param g Graphics对象*/public void drawEnemyTanks(Graphics g) {for (int i = 0; i < enemyTanks.size(); i++) {Tank enemyTank = enemyTanks.get(i);enemyTank.draw(g);enemyTank.collidesWithTank(myTank, false);enemyTank.collidesWithTanks(enemyTanks, false); }}/*** 画炮弹* @param g Graphics对象*/public void drawMissiles(Graphics g) {for (int i = 0; i < missiles.size(); i++) {Missile m = missiles.get(i);if (m != null) {m.draw(g);m.hitTanks(enemyTanks);m.hitTank(myTank);m.hitMissiles(missiles);}}}/*** 加入爆炸* @param g Graphics对象*/public void drawExplodes(Graphics g) {for (int i=0; i < explodes.size(); i++) { Explode e = explodes.get(i);e.draw(g);}}/*** 出现宝物* @param g Graphics对象*/public void drawTreasure(Graphics g) {if (rand.nextInt(100) == 0)trea = null;if (rand.nextInt(300) == 0) {int x = rand.nextInt(785);int y = rand.nextInt(555);trea = new Treasure(x, y, this);}if (trea != null) {trea.collidesWithWalls(walls);trea.draw(g);}}/*** 打印信息* @param g Graphics对象*/public void drawMessage(Graphics g) {Color c = g.getColor();g.setColor(Color.YELLOW);g.drawString("EnemyTanks Count: " + enemyTanks.size(), 10, 50);g.drawString("All EnemyTanks Count: " + this.tankAllNum, 10, 70);g.drawString("MyTank Count: " + this.myTankNum, 10, 90);g.drawString("MyTank Life: " + myTank.getLife(), 10, 110);g.setColor(c);}/*** 返回敌方坦克总数量* @return 敌方坦克总数量*/public int getTankAllNum() {return tankAllNum;}/*** 设置敌方坦克总数量* @param tankAllNum 敌方坦克总数量*/public void setTankAllNum(int tankAllNum) {this.tankAllNum = tankAllNum;}/*** 返回当前敌方坦克数量* @return 返回当前敌方坦克数量*/public int getTankNum() {return tankNum;}/*** 设置当前敌方坦克数量* @param tankNum 当前敌方坦克数量*/public void setTankNum(int tankNum) { this.tankNum = tankNum;}}Tank.java:程序代码package .ahau.mgc.tankwar; import java.awt.*;import java.awt.event.*;import java.util.*;import java.util.List;/*** 此类用于创建一个坦克* @author Magci**/public class Tank {/*** 坦克水平垂直移动时X、Y轴上的速度*/public static final int SPEED = 4;/*** 坦克45度移动时X、Y轴上的速度*/public static final int XYSPEED = (int) (Math.sqrt(2) * SPEED / 2); /*** 坦克的宽度*/public static final int WIDTH = 30;/*** 坦克的高度*/public static final int HEIGHT = 30;/*** 炮筒长度*/public static final int PT_LENGTH = 20;/*** 45度炮筒的X、Y坐标偏移量*/public static final int PT_XY = (int) (Math.sqrt(2) * PT_LENGTH) / 2; /*** 坦克初始生命值*/public static final int LIFE = 100;// 坦克左上角位置private int x, y;// 标记方向键的状态:true表示被按下,false表示被松开private boolean bL = false, bU = false, bR = false, bD = false;/*** 坦克方向*/public Direction dir = Direction.STOP;/*** 坦克炮筒方向*/public Direction ptDir = Direction.U;TankClient tc = null;//标记敌我坦克,true表示我方坦克,false表示敌方坦克private boolean good;//标记坦克生命状态private boolean live = true;private Random rand = new Random();//地方坦克改变一次方向需要的步数private int step = rand.nextInt(10) + 3;//坦克的上一个位置private int lastX = -1, lastY = -1;//坦克的生命值private int life = LIFE;//坦克生命条LifeBar lb = new LifeBar();//方向数private int dirNum = 8;//判断是否初始化private boolean init = false;private static Toolkit tk = Toolkit.getDefaultToolkit();private static Image[] tankImgs;private static Map<String,Image> imgs = new HashMap<String,Image>();static {tankImgs = new Image[] {tk.getImage(Tank.class.getClassLoader().getResource("images/myTankL.gif")),tk.getImage(Tank.class.getClassLoader().getResource("images/myTankU.gif")),tk.getImage(Tank.class.getClassLoader().getResource("images/myTankR.gif")),tk.getImage(Tank.class.getClassLoader().getResource("images/myTankD.gif")),tk.getImage(Tank.class.getClassLoader().getResource("images/enemyTankL.gif")), tk.getImage(Tank.class.getClassLoader().getResource("images/enemyTankU.gif")), tk.getImage(Tank.class.getClassLoader().getResource("images/enemyTankR.gif")),tk.getImage(Tank.class.getClassLoader().getResource("images/enemyTankD.gif")) };imgs.put("myTankL", tankImgs[0]);imgs.put("myTankU", tankImgs[1]);imgs.put("myTankR", tankImgs[2]);imgs.put("myTankD", tankImgs[3]);imgs.put("enemyTankL", tankImgs[4]);imgs.put("enemyTankU", tankImgs[5]);imgs.put("enemyTankR", tankImgs[6]);imgs.put("enemyTankD", tankImgs[7]);}/*** 根据坦克位置和敌我状态创建一个坦克* @param x 坦克左上角X坐标* @param y 坦克左上角Y坐标* @param good 坦克的敌我状态*/public Tank(int x, int y, boolean good) {this.x = x;this.y = y;this.good = good;}/*** 根据坦克位置,敌我状态和当前游戏窗体创建一个坦克* @param x 坦克左上角X坐标* @param y 坦克左上角Y坐标* @param good 坦克的敌我状态* @param tc 当前游戏窗体*/public Tank(int x, int y, boolean good, TankClient tc) {this(x, y, good);this.tc = tc;}/*** 根据坦克位置,敌我状态和当前游戏窗体创建一个坦克* @param x 坦克左上角X坐标* @param y 坦克左上角Y坐标* @param dirNum 方向数* @param good 坦克的敌我状态* @param tc 当前游戏窗体*/public Tank(int x, int y, int dirNum, boolean good, TankClient tc) { this(x, y, good, tc);this.dirNum =dirNum;}/*** 在窗体上画出坦克* @param g Graphics对象*/public void draw(Graphics g) {if (!this.live) {if (!this.good)tc.enemyTanks.remove(this);tc.setTankNum(tc.getTankNum() - 1);tc.setTankAllNum(tc.getTankAllNum() - 1); return;}Color c = g.getColor();if (good)g.setColor(Color.RED);elseg.setColor(Color.BLUE);this.drawTank(g);if (good)lb.draw(g);g.setColor(c);//敌方坦克定位if (!good) {if (step == 0) {Direction[] dirs = Direction.values();int i = rand.nextInt(5);dir = dirs[i];if (rand.nextInt(20) == 0)dir = Direction.D;step = rand.nextInt(10) + 3;}step --;if (!this.hasMyMissile())fire();}move();}/*** 方向键被按下后标记被按下的键* @param e 键盘事件*/public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode();switch (keyCode) {case KeyEvent.VK_LEFT:bL = true;break;case KeyEvent.VK_UP:bU = true;break;case KeyEvent.VK_RIGHT:bR = true;break;case KeyEvent.VK_DOWN:bD = true;break;case KeyEvent.VK_CONTROL:if (!this.hasMyMissile())fire();break;case KeyEvent.VK_A:superFire();break;case KeyEvent.VK_F2:tc = new TankClient("TankClient", 50, 10, 3); break;}locateDirection();}/*** 方向键被松开后标记被松开的键* @param e 键盘事件*/public void keyReleased(KeyEvent e) {int keyCode = e.getKeyCode();switch (keyCode) {case KeyEvent.VK_LEFT:bL = false;break;case KeyEvent.VK_UP:bU = false;break;case KeyEvent.VK_RIGHT:bR = false;break;case KeyEvent.VK_DOWN:bD = false;break;}locateDirection();}/*** 根据按下的键定位方向*/public void locateDirection() {if (dirNum == 4 || dirNum ==8) { if (bL && !bU && !bR && !bD) dir = Direction.L;if (!bL && bU && !bR && !bD) dir = Direction.U;if (!bL && !bU && bR && !bD) dir = Direction.R;if (!bL && !bU && !bR && bD) dir = Direction.D;}if (dirNum == 8) {if (bL && bU && !bR && !bD)dir = Direction.LU;if (!bL && bU && bR && !bD)dir = Direction.RU;if (!bL && !bU && bR && bD)dir = Direction.RD;if (bL && !bU && !bR && bD)dir = Direction.LD;}if (!bL && !bU && !bR && !bD) dir = Direction.STOP;}/*** 根据方向移动坦克*/public void move() {lastX = x;lastY = y;switch (dir) {case L:x -= SPEED;break;case LU:x -= XYSPEED;y -= XYSPEED;break;case U:y -= SPEED;break;case RU:x += XYSPEED;y -= XYSPEED;break;case R:x += SPEED;break;case RD:x += XYSPEED;y += XYSPEED;break;case D:y += SPEED;break;case LD:x -= XYSPEED;y += XYSPEED;break;case STOP:break;}if (dir != Direction.STOP)ptDir = dir;//控制坦克不出界if (x < 0)x = 0;if (y < 30)y = 30;if (x > TankClient.WINDOW_WIDTH - this.WIDTH) x = TankClient.WINDOW_WIDTH - this.WIDTH; if (y > TankClient.WINDOW_HEIGHT - this.HEIGHT) y = TankClient.WINDOW_HEIGHT - this.HEIGHT; }/*** 根据坦克的位置和炮筒的方向发射炮弹*/public void fire() {int mW = 0;int mH = 0;if (!this.live)return;if (ptDir == Direction.U || ptDir == Direction.D) {mW = Missile.WIDTH / 2;mH = Missile.HEIGHT / 2;} else if (ptDir == Direction.L || ptDir == Direction.R) { mW = Missile.HEIGHT / 2;mH = Missile.WIDTH / 2;}int x = this.x + Tank.WIDTH / 2 - mW;int y = this.y + Tank.HEIGHT / 2 - mH;Missile m = new Missile(x, y, this.good, ptDir, this, tc); tc.missiles.add(m);}/*** 根据方向画坦克* @param g Graphics对象*/public void drawTank(Graphics g) {if (good) {switch (ptDir) {case L:g.drawImage(imgs.get("myTankL"), x, y, null);break;case LU:break;case U:g.drawImage(imgs.get("myTankU"), x, y, null);break;case RU:break;case R:g.drawImage(imgs.get("myTankR"), x, y, null);break;case RD:break;case D:g.drawImage(imgs.get("myTankD"), x, y, null);break;case LD:break;}} else {switch (ptDir) {case L:g.drawImage(imgs.get("enemyTankL"), x, y, null); break;case LU:break;case U:g.drawImage(imgs.get("enemyTankU"), x, y, null);break;case RU:break;case R:g.drawImage(imgs.get("enemyTankR"), x, y, null);break;case RD:break;case D:g.drawImage(imgs.get("enemyTankD"), x, y, null);break;case LD:break;}}}/*** 返回坦克的矩形碰撞区域* @return 坦克的矩形碰撞区域*/public Rectangle getRect() {Rectangle rect = new Rectangle(x, y, this.WIDTH, this.HEIGHT); return rect;}/*** 返回坦克的生命状态* @return 坦克的生命状态*/public boolean isLive() {return live;}/*** 设置坦克的生命状态* @param live 坦克的生命状态*/public void setLive(boolean live) { this.live = live;}/*** 返回坦克的敌我状态* @return 坦克的敌我状态*/public boolean isGood() {return good;}/*** 设置坦克的方向* @param dir 坦克的方向*/public void setDir(Direction dir) {this.dir = dir;}/*** 坦克回到上一个位置*/public void stay() {if (x != -1 && y != -1) {this.x = stX;this.y = stY;} else {tc.enemyTanks.remove(this);tc.setTankAllNum(tc.getTankAllNum() - 1);tc.setTankNum(tc.getTankNum() - 1);}}/*** 判断是否与其他坦克相撞* @param t 坦克* @param newTank 是否新坦克* @return 坦克是否与其他坦克相撞*/public boolean collidesWithTank(Tank t, boolean newTank) {if (this.live && t.isLive() && t != this && this.getRect().intersects(t.getRect())) { if (!newTank) {this.stay();t.stay();}return true;}return false;}/*** 依次判断其他所有坦克是否与该坦克相撞* @param tanks 存放坦克的容器* @param newTank 是否新坦克* @return 坦克是否与其他坦克相撞*/public boolean collidesWithTanks(List<Tank> tanks, boolean newTank) { for (int i = 0; i < tanks.size(); i++) {Tank t = tanks.get(i);this.collidesWithTank(t, newTank);}return false;}/*** 发射超级炮弹(四个方向同时开火)*/public void superFire() {if (!this.live)return;int x = 0, y = 0, mW = 0, mH = 0;Direction[] dirs = Direction.values();for (int i = 0; i < 5; i++) {if (ptDir == Direction.U || ptDir == Direction.D) {mW = Missile.WIDTH / 2;mH = Missile.HEIGHT / 2;} else if (ptDir == Direction.L || ptDir == Direction.R) { mW = Missile.HEIGHT / 2;mH = Missile.WIDTH / 2;}x = this.x + Tank.WIDTH / 2 - mW;y = this.y + Tank.HEIGHT / 2 - mH;if (dirs[i] != Direction.STOP) {Missile m = new Missile(x, y, this.good, dirs[i], this, tc); tc.missiles.add(m);}}}/*** 返回坦克的生命值* @return 坦克的生命值*/public int getLife() {return life;}/*** 设置坦克的生命值* @param life 坦克的生命值*/public void setLife(int life) {this.life = life;}/*** 创建生命条* @author Magci**/class LifeBar {/*** 在坦克上方画生命条* @param g Graphics对象*/public void draw(Graphics g) {Color c = g.getColor();g.setColor(Color.RED);g.drawRect(x, y - 10, WIDTH, 5);g.fillRect(x, y - 10, WIDTH * life / 100, 5);g.setColor(c);}}/*** 判断坦克是否碰到宝物* @param trea 宝物* @return 坦克是否碰到宝物*/public boolean eatTreasure(Treasure trea) {if (this.live && trea.isLive() && this.getRect().intersects(trea.getRect())) { trea.setLive(false);this.life = LIFE;return true;}return false;}/*** 返回坦克左上角X坐标* @return 坦克左上角X坐标*/public int getX() {return x;}/*** 设置坦克左上角X坐标* @param x*/public void setX(int x) {this.x = x;}/*** 返回坦克左上角Y坐标* @return 坦克左上角Y坐标*/public int getY() {return y;}/*** 设置坦克左上角Y坐标* @param y 坦克左上角Y坐标*/public void setY(int y) {this.y = y;}/*** 判断是否有该坦克发射的炮弹* @return 是否有该坦克发射的炮弹*/public boolean hasMyMissile() {for (int i = 0; i < tc.missiles.size(); i++) { Missile m = tc.missiles.get(i);if (m.getT() == this)return true;}return false;}}Missile.java:程序代码package .ahau.mgc.tankwar; import java.awt.*;import java.util.List;import java.util.*;/*** 此类用于创建炮弹* @author Magci**/public class Missile {/*** 炮弹宽度*/public static final int WIDTH = 30; /*** 炮弹长度*/public static final int HEIGHT = 30; /*** 炮弹水平垂直发射时X、Y轴上的速度 */public static final int SPEED = 15;/*** 炮弹45度发射时X、Y轴上的速度*/public static final int XYSPEED = (int) (Math.sqrt(2) * SPEED / 2);// 炮弹左上角位置private int x, y;Direction ptDir;TankClient tc = null;Tank t;//标记炮弹是否存在private boolean live = true;//标记炮弹的敌我状态private boolean good;//标记是否初始化private boolean init = false;private static Toolkit tk = Toolkit.getDefaultToolkit();private static Image[] missileImgs;private static Map<String, Image> imgs = new HashMap<String, Image>();static {missileImgs = new Image[] {tk.getImage(Missile.class.getClassLoader().getResource("images/missileL.gif")), tk.getImage(Missile.class.getClassLoader().getResource("images/missileU.gif")), tk.getImage(Missile.class.getClassLoader().getResource("images/missileR.gif")), tk.getImage(Missile.class.getClassLoader().getResource("images/missileD.gif")) };imgs.put("L",missileImgs[0]);imgs.put("U",missileImgs[1]);imgs.put("R",missileImgs[2]);imgs.put("D",missileImgs[3]);}/*** 根据坦克位置、炮筒方向、坦克敌我状态、发射炮弹的坦克、当前窗体创建炮弹* @param x 坦克中心X坐标* @param y 坦克中心Y坐标* @param good 坦克敌我状态* @param ptDir 炮筒方向* @param t 发射炮弹的坦克* @param tc 当前窗体*/public Missile(int x, int y, boolean good, Direction ptDir, Tank t, TankClient tc) { this.x = x;this.y = y;this.good = good;this.ptDir = ptDir;this.t = t;this.tc = tc;}/*** 在窗体上画出炮弹* @param g Graphics对象*/public void draw(Graphics g) {if (!this.live) {tc.missiles.remove(this);return;}if (!init) {for(int i = 0; i < missileImgs.length; i++)g.drawImage(missileImgs[i], -100, -100, null); init = true;}Color c = g.getColor();if (this.good)g.setColor(Color.RED);elseg.setColor(Color.BLACK);this.drawMissile(g);g.setColor(c);move();}/*** 根据炮筒方向发射炮弹*/public void move() {switch (ptDir) {case L:x -= SPEED;break;case LU:x -= XYSPEED; y -= XYSPEED; break;case U:y -= SPEED;break;case RU:x += XYSPEED; y -= XYSPEED; break;case R:x += SPEED; break;case RD:x += XYSPEED; y += XYSPEED; break;case D:y += SPEED; break;case LD:x -= XYSPEED; y += XYSPEED; break;}//判断炮弹是否出界if (x < 0 || x > TankClient.WINDOW_WIDTH || y < 0 || y > TankClient.WINDOW_HE IGHT) {live = false;}}/*** 返回炮弹的矩形碰撞区域* @return 炮弹的矩形碰撞区域*/public Rectangle getRect() {int w = 0, h = 0;if (ptDir == Direction.U || ptDir == Direction.D) {w = this.WIDTH;h = this.HEIGHT;} else if (ptDir == Direction.L || ptDir == Direction.R) {w = this.HEIGHT;h = this.WIDTH;}Rectangle rect = new Rectangle(x, y, w, h);return rect;}/*** 判断是否击中坦克* @param t 坦克* @return 是否击中坦克*/public boolean hitTank(Tank t) {if (this.getRect().intersects(t.getRect()) && t.isLive() && this.live && t.isGood() != thi s.good) {if (t.isGood()) {t.setLife(t.getLife() - 20);if (t.getLife() <= 0)t.setLive(false);} else {t.setLive(false);}this.live = false;Explode e = new Explode(x, y, tc);tc.explodes.add(e);return true;}return false;}/*** 依次判断所有的敌方坦克是否被该炮弹击中* @param enemyTanks 敌方坦克* @return 否击中敌方坦克*/public boolean hitTanks(List<Tank> enemyTanks) {for (int i = 0; i < enemyTanks.size(); i++) {Tank enemyTank = enemyTanks.get(i);if (hitTank(enemyTank))return true;}return false;}/*** 设置炮弹左上角的X坐标* @return 炮弹左上角的X坐标*/public int getX() {return x;}/*** 设置炮弹左上角的Y坐标* @return 炮弹左上角的Y坐标*/public int getY() {return y;}/*** 判断炮弹是否击中对方炮弹* @param m 炮弹* @return 炮弹是否击中对方炮弹*/public boolean hitMissile(Missile m) {if (this.live && m.isLive() && this.good != m.isGood() && this.getRect().intersects(m. getRect())) {this.live = false;m.setLive(false);return true;}return false;}/*** 依次判断对方所有的炮弹是否被该炮弹击中* @param missiles 存放炮弹的容器* @return 炮弹是否击中对方炮弹*/public boolean hitMissiles(List<Missile> missiles) { for (int i = 0; i < missiles.size(); i++) {Missile m = missiles.get(i);if (hitMissile(m))return true;}return false;}/*** 返回炮弹的敌我状态* @return 炮弹的敌我状态*/public boolean isGood() {return good;}/*** 返回炮弹的生命状态* @return 炮弹的生命状态*/public boolean isLive() {return live;}/*** 设置炮弹的生命状态* @param live 炮弹的生命状态*/public void setLive(boolean live) { this.live = live;}/*** 返回发射该炮弹的坦克* @return 发射该炮弹的坦克*/public Tank getT() {return t;}/*** 根据方向画炮弹* @param g Graphics对象*/public void drawMissile(Graphics g) {switch (ptDir) {case L:g.drawImage(imgs.get("L"), x, y, null); break;case LU:break;case U:g.drawImage(imgs.get("U"), x, y, null); break;case RU:break;case R:g.drawImage(imgs.get("R"), x, y, null); break;case RD:break;case D:g.drawImage(imgs.get("D"), x, y, null); break;case LD:break;}}}Explode.java:程序代码package .ahau.mgc.tankwar;import java.awt.*;/*** 此类用于创建爆炸* @author Magci**/public class Explode {private int x, y;private int step = 0;private boolean live = true;private int radius = 10;TankClient tc;private static Toolkit tk = Toolkit.getDefaultToolkit();private static Image[] imgs = {tk.getImage(Explode.class.getClassLoader().getResource("images/0.gif")), tk.getImage(Explode.class.getClassLoader().getResource("images/1.gif")), tk.getImage(Explode.class.getClassLoader().getResource("images/2.gif")), tk.getImage(Explode.class.getClassLoader().getResource("images/3.gif")), tk.getImage(Explode.class.getClassLoader().getResource("images/4.gif")), tk.getImage(Explode.class.getClassLoader().getResource("images/5.gif"))。

坦克大战java源代码

坦克大战java源代码

有些图片路径会出错要注意package com.tankgame;import java.util.Vector;//坦克类class Tank{int x=0;int y=0;int color=0;int speed=1;int direct=0;boolean isLive=true;public Tank(int x,int y){this.x=x;this.y=y;}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 int getDirect() {return direct;}public void setDirect(int direct) {this.direct = direct;}public int getColor() {return color;}public void setColor(int color) {this.color = color;}}//我的坦克class Hero extends Tank{Shot shot=null;Vector<Shot> shotm=new V ector<Shot>();public Hero(int x,int y){super(x,y);this.color=5;}//坦克具有一个打击敌人的方法public void shotenemy(int x,int y,int direct){switch(direct){case 0:shot=new Shot(this.x+10,this.y,0);shotm.add(shot);break;case 1:shot=new Shot(this.x+30,this.y+10,1);shotm.add(shot);break;case 2:shot=new Shot(this.x+10,this.y+30,2);shotm.add(shot);break;case 3:shot=new Shot(this.x,this.y+10,3);shotm.add(shot);break;}Thread th=new Thread(shot);th.start();}//调整速度public void moveup(){y-=speed;}public void moveright(){x+=speed;}public void movedown(){y+=speed;}public void moveleft(){x-=speed;}}//敌人的坦克class EnemyTank extends Tank implements Runnable {Vector<Shot>ensh=new Vector<Shot>();Vector<EnemyTank>ets=new Vector<EnemyTank>();public EnemyTank(int x, int y){super(x, y);this.setColor(2);this.setDirect(2);}//获取MPanel上的敌人坦克public void setets(Vector<EnemyTank> vv){this.ets=vv;}//判断敌人的坦克是否碰撞public boolean isTouch(){boolean b=false;EnemyTank et=null;switch(direct){case 0:for(int i=0;i<ets.size();i++){et=ets.get(i);if(et!=this){if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.x<=et.x+20&&this.y<=et.y+30&&this.y>et.y){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+20&&this.y<=et.y+30&&this.y>et.y){return true;}}if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.x<=et.x+30&&this.y<=et.y+20&&this.y>et.y){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+30&&this.y<=et.y+20&&this.y>et.y){return true;}}}}break;case 1:for(int i=0;i<ets.size();i++){et=ets.get(i);if(et!=this){if(et.direct==0||et.direct==2){if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y<=et.y+30&&this.y>et.y){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y+20<=et.y+30&&this.y+20>et.y){return true;}}if(et.direct==1||et.direct==3){if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y<=et.y+20&&this.y>et.y){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y+20<=et.y+20&&this.y+20>et.y){return true;}}}}break;case 2:for(int i=0;i<ets.size();i++){et=ets.get(i);if(et!=this){if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.x<=et.x+20&&this.y+30<=et.y+30&&this.y+30>et.y){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+20&&this.y+30<=et.y+30&&this.y+30>et.y){return true;}}if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.x<=et.x+30&&this.y+30<=et.y+20&&this.y+30>et.y){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+30&&this.y+30<=et.y+20&&this.y+30>et.y){return true;}}}}break;case 3:for(int i=0;i<ets.size();i++){et=ets.get(i);if(et!=this){if(et.direct==0||et.direct==2){if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y<=et.y+30&&this.y>et.y){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y+20<=et.y+30&&this.y+20>et.y){return true;}}if(et.direct==1||et.direct==3){if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y<=et.y+20&&this.y>et.y){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y+20<=et.y+20&&this.y+20>et.y){return true;}}}}break;}return b;}public void run() {while(true){switch(this.direct){case 0:for(int i=0;i<30;i++){if(y>0&&this.isTouch()==false)y-=this.speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 1:for(int i=0;i<30;i++){if(x<365&&this.isTouch()==false)x+=this.speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 2:for(int i=0;i<30;i++){if(y<270&&this.isTouch()==false)y+=this.speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 3:for(int i=0;i<30;i++){if(x>0&&this.isTouch()==false)x-=this.speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;}this.direct=(int)(Math.random()*4);if(this.isLive==false){break;}if(ensh.size()<5){Shot es=null;switch(this.direct){case 0:es=new Shot(this.getX()+10,this.getY(),0);ensh.add(es);break;case 1:es=new Shot(this.getX()+30,this.getY()+10,1);ensh.add(es);break;case 2:es=new Shot(this.getX()+10,this.getY()+30,2);ensh.add(es);break;case 3:es=new Shot(this.getX(),this.getY()+10,3);ensh.add(es);break;}Thread th=new Thread(es);th.start();}}}}//炸弹类class Bomb{int x;int y;int lift=9;boolean isLive=true;public Bomb(int x,int y){this.x=x;this.y=y;}//炸弹的生命值public void liftdown(){if(lift>0){lift--;}else{isLive=false;}}}//子弹类class Shot implements Runnable{int shotX;int shotY;int direct;int shotspeed=1;boolean isLive=true;public Shot(int x,int y,int direct){this.shotX=x;this.shotY=y;this.direct=direct;}public int getShotX() {return shotX;}public void setShotX(int shotX) {this.shotX = shotX;}public int getShotY() {return shotY;}public void setShotY(int shotY) {this.shotY = shotY;}public int getShotspeed() {return shotspeed;}public void setShotspeed(int shotspeed) {this.shotspeed = shotspeed;}public void run(){while(true){try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}switch(direct){case 0:shotY-=shotspeed;break;case 1:shotX+=shotspeed;break;case 2:shotY+=shotspeed;break;case 3:shotX-=shotspeed;break;}if(shotX<0||shotX>400||shotY<0||shotY>300){isLive=false;break;}}}}/*** 功能:坦克大战4.0*/package com.tankgame4;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.Vector;import java.io.*;import javax.swing.*;import javax.imageio.*;public class MyTankGame4 extends JFrame implements ActionListener{MyPanel mp=null;MyStartPanel msp=null;//菜单定义JMenuBar jmb=null;JMenu jm1=null;JMenuItem jmi1=null;public static void main(String[] args) {// TODO Auto-generated method stubMyTankGame4 mtg=new MyTankGame4();}//构造函数public MyTankGame4(){//创建菜单jmb=new JMenuBar();jm1=new JMenu("Game(G)");jm1.setMnemonic('G');jmi1=new JMenuItem("New Game(N)");jmi1.setMnemonic('N');jmi1.addActionListener(this);jmi1.setActionCommand("New Game");jm1.add(jmi1);jmb.add(jm1);this.setJMenuBar(jmb);msp=new MyStartPanel();Thread st=new Thread(msp);st.start();this.add(msp);this.setTitle("坦克大战");this.setSize(400, 300);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}public void actionPerformed(ActionEvent arg0) {if(arg0.getActionCommand().equals("New Game")){this.remove(msp);mp=new MyPanel();Thread mt=new Thread(mp);mt.start();this.add(mp);this.addKeyListener(mp);this.setVisible(true);}}//游戏开始面板class MyStartPanel extends JPanel implements Runnable{int times=0;public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 400, 300);if(times%2==0){Font myfont=new Font("行楷",Font.BOLD,30);g.setFont(myfont);g.setColor(Color.yellow);g.drawString("第一关", 130, 130);}this.repaint();}public void run() {while(true){try {Thread.sleep(300);times++;} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}//我的面板class MyPanel extends JPanel implements KeyListener,Runnable {//定义一个我的坦克Hero hero=null;EnemyTank et=null;Image image1=null;Image image2=null;Image image3=null;Image im=null;Vector<Bomb> bombs =new Vector<Bomb>();Vector<EnemyTank> etm =new Vector<EnemyTank>();int ensize=5;public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 400, 300);g.drawImage(im, 0, 0, 400, 300,this);//画出自己的坦克if(hero.isLive==true){this.drawTank(this.hero.getX(), this.hero.getY(),g, this.hero.getDirect(),this.hero.getColor() );}//画出子弹for(int i=0;i<hero.shotm.size();i++){Shot myshot=hero.shotm.get(i);if(myshot!=null&&myshot.isLive==true){g.fill3DRect(myshot.getShotX(),myshot.getShotY(), 2, 2, false);}if(myshot.isLive==false)hero.shotm.remove(myshot);}//画出炸弹for(int i=0;i<bombs.size();i++){Bomb b=bombs.get(i);if(b.lift>6){g.drawImage(image1, b.x, b.y, 30, 30, this);}else if(b.lift>3){g.drawImage(image2, b.x, b.y, 30, 30, this);}else{g.drawImage(image3, b.x, b.y, 30, 30, this);}b.liftdown();if(b.lift==0)bombs.remove(b);}//画出敌人的坦克for(int i=0;i<etm.size();i++){et=etm.get(i);if(et!=null&&et.isLive==true){this.drawTank(et.getX(), et.getY(),g, et.getDirect(), et.getColor());}//画出敌人的子弹for(int j=0;j<et.ensh.size();j++){Shot enshot=et.ensh.get(j);if(enshot.isLive==true){g.fill3DRect(enshot.getShotX(),enshot.getShotY(), 2, 2, false);// System.out.println("第"+i+"辆坦克的第"+j+"颗子弹的Y="+enshot.getShotY());}else{et.ensh.remove(enshot);}}}}//判断子弹是否击中坦克的函数public void hitTank(Shot s,Tank t){switch(t.getDirect()){case 0:case 2:if(s.getShotX()>t.getX()&&s.getShotX()<t.getX()+20&&s.getShotY()>t.getY()&&s.getShotY()<t.getY()+30) {s.isLive=false;t.isLive=false;Bomb b=new Bomb(t.getX(),t.getY());bombs.add(b);}break;case 1:case 3:if(s.getShotX()>t.getX()&&s.getShotX()<t.getX()+30&&s.getShotY()>t.getY()&&s.getShotY()<t.getY()+20) {s.isLive=false;t.isLive=false;Bomb b=new Bomb(t.getX(),t.getY());bombs.add(b);}}}//画出坦克的函数public void drawTank(int xx,int yy,Graphics g,int direct,int type){//判断什么颜色类型的坦克switch(type){case 0:g.setColor(Color.CY AN);break;case 1:g.setColor(Color.pink);break;case 2:g.setColor(Color.red);break;case 3:g.setColor(Color.green);break;case 4:g.setColor(Color.blue);break;case 5:g.setColor(Color.yellow);break;}//判断什么方向的坦克switch(direct){//向上case 0:g.fill3DRect(xx, yy, 5, 30, false);g.fill3DRect(xx+15, yy, 5, 30, false);g.fill3DRect(xx+5, yy+5, 10, 20, false);g.fillOval(xx+5, yy+10, 10, 10);g.drawLine(xx+10, yy+15, xx+10, yy);break;//向右case 1:g.fill3DRect(xx, yy, 30, 5, false);g.fill3DRect(xx, yy+15, 30, 5, false);g.fill3DRect(xx+5, yy+5, 20, 10, false);g.fillOval(xx+10, yy+5, 10, 10);g.drawLine(xx+15, yy+10, xx+30, yy+10);break;//向下case 2:g.fill3DRect(xx, yy, 5, 30, false);g.fill3DRect(xx+15, yy, 5, 30, false);g.fill3DRect(xx+5, yy+5, 10, 20, false);g.fillOval(xx+5, yy+10, 10, 10);g.drawLine(xx+10, yy+15, xx+10, yy+30);break;//向左case 3:g.fill3DRect(xx, yy, 30, 5, false);g.fill3DRect(xx, yy+15, 30, 5, false);g.fill3DRect(xx+5, yy+5, 20, 10, false);g.fillOval(xx+10, yy+5, 10, 10);g.drawLine(xx+15, yy+10, xx, yy+10);break;}}public MyPanel(){hero=new Hero(100,100);im=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/28951278.jpg"));//创建敌人坦克for(int i=0;i<ensize;i++){et=new EnemyTank((i+1)*50,0);Shot enshot=new Shot(et.getX()+10,et.getY()+30,et.getDirect());Thread eth=new Thread(enshot);eth.start();et.ensh.add(enshot);Thread th=new Thread(et);th.start();etm.add(et);et.setets(etm);}// try {// image1=ImageIO.read(new File("bomb_1.gif"));// image2=ImageIO.read(new File("bomb_2.gif"));// image3=ImageIO.read(new File("bomb_3.gif"));// } catch (IOException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }image1=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_1.gif"));image2=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_2.gif"));image3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_3.gif"));}//控制坦克移动public void keyPressed(KeyEvent arg0) {// TODO Auto-generated method stubif(arg0.getKeyCode()==KeyEvent.VK_DOWN){this.hero.setDirect(2);this.hero.movedown();}else if(arg0.getKeyCode()==KeyEvent.VK_UP){this.hero.setDirect(0);this.hero.moveup();}else if(arg0.getKeyCode()==KeyEvent.VK_LEFT){this.hero.setDirect(3);this.hero.moveleft();}else if(arg0.getKeyCode()==KeyEvent.VK_RIGHT){this.hero.setDirect(1);this.hero.moveright();}else if(arg0.getKeyCode()==KeyEvent.VK_P){hero.speed=0;et.speed=0;}//发射子弹(连发5枚子弹)if(hero.shotm.size()<=4){if(arg0.getKeyCode()==KeyEvent.VK_SPACE){hero.shotenemy(hero.getX(),hero.getY(),hero.getDirect());}}//控制坦克不能跑出边界if(this.hero.getX()<0)this.hero.setX(0);if(this.hero.getY()<0)this.hero.setY(0);if(this.hero.getX()>365)this.hero.setX(365);if(this.hero.getY()>270)this.hero.setY(270);//面板重绘this.repaint();}public void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}public void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}public void run() {while(true){try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//不停地调用敌人是否打中自己坦克函数for(int i=0;i<etm.size();i++){et=etm.get(i);for(int j=0;j<et.ensh.size();j++){Shot enshot=et.ensh.get(j);if(enshot.isLive==true&&hero.isLive==true){this.hitTank(enshot, hero);}}}//不停地调用是否打中敌人坦克函数for(int i=0;i<hero.shotm.size();i++){Shot s=hero.shotm.get(i);if(s!=null&&s.isLive==true){for(int j=0;j<etm.size();j++){EnemyTank et=etm.get(j);if(et!=null&&et.isLive==true){this.hitTank(s, et);}}}}//面板重绘this.repaint();}}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

有些图片路径会出错要注意package com.tankgame;import java.util.Vector;//坦克类class Tank{int x=0;int y=0;int color=0;int speed=1;int direct=0;boolean isLive=true;public Tank(int x,int y){this.x=x;this.y=y;}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 int getDirect() {return direct;}public void setDirect(int direct) {this.direct = direct;}public int getColor() {return color;}public void setColor(int color) {this.color = color;}}//我的坦克class Hero extends Tank{Shot shot=null;Vector<Shot> shotm=new V ector<Shot>();public Hero(int x,int y){super(x,y);this.color=5;}//坦克具有一个打击敌人的方法public void shotenemy(int x,int y,int direct){switch(direct){case 0:shot=new Shot(this.x+10,this.y,0);shotm.add(shot);break;case 1:shot=new Shot(this.x+30,this.y+10,1);shotm.add(shot);break;case 2:shot=new Shot(this.x+10,this.y+30,2);shotm.add(shot);break;case 3:shot=new Shot(this.x,this.y+10,3);shotm.add(shot);break;}Thread th=new Thread(shot);th.start();}//调整速度public void moveup(){y-=speed;}public void moveright(){x+=speed;}public void movedown(){y+=speed;}public void moveleft(){x-=speed;}}//敌人的坦克class EnemyTank extends Tank implements Runnable {Vector<Shot>ensh=new Vector<Shot>();Vector<EnemyTank>ets=new Vector<EnemyTank>();public EnemyTank(int x, int y){super(x, y);this.setColor(2);this.setDirect(2);}//获取MPanel上的敌人坦克public void setets(Vector<EnemyTank> vv){this.ets=vv;}//判断敌人的坦克是否碰撞public boolean isTouch(){boolean b=false;EnemyTank et=null;switch(direct){case 0:for(int i=0;i<ets.size();i++){et=ets.get(i);if(et!=this){if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.x<=et.x+20&&this.y<=et.y+30&&this.y>et.y){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+20&&this.y<=et.y+30&&this.y>et.y){return true;}}if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.x<=et.x+30&&this.y<=et.y+20&&this.y>et.y){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+30&&this.y<=et.y+20&&this.y>et.y){return true;}}}}break;case 1:for(int i=0;i<ets.size();i++){et=ets.get(i);if(et!=this){if(et.direct==0||et.direct==2){if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y<=et.y+30&&this.y>et.y){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y+20<=et.y+30&&this.y+20>et.y){return true;}}if(et.direct==1||et.direct==3){if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y<=et.y+20&&this.y>et.y){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y+20<=et.y+20&&this.y+20>et.y){return true;}}}}break;case 2:for(int i=0;i<ets.size();i++){et=ets.get(i);if(et!=this){if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.x<=et.x+20&&this.y+30<=et.y+30&&this.y+30>et.y){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+20&&this.y+30<=et.y+30&&this.y+30>et.y){return true;}}if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.x<=et.x+30&&this.y+30<=et.y+20&&this.y+30>et.y){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+30&&this.y+30<=et.y+20&&this.y+30>et.y){return true;}}}}break;case 3:for(int i=0;i<ets.size();i++){et=ets.get(i);if(et!=this){if(et.direct==0||et.direct==2){if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y<=et.y+30&&this.y>et.y){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y+20<=et.y+30&&this.y+20>et.y){return true;}}if(et.direct==1||et.direct==3){if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y<=et.y+20&&this.y>et.y){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y+20<=et.y+20&&this.y+20>et.y){return true;}}}}break;}return b;}public void run() {while(true){switch(this.direct){case 0:for(int i=0;i<30;i++){if(y>0&&this.isTouch()==false)y-=this.speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 1:for(int i=0;i<30;i++){if(x<365&&this.isTouch()==false)x+=this.speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 2:for(int i=0;i<30;i++){if(y<270&&this.isTouch()==false)y+=this.speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 3:for(int i=0;i<30;i++){if(x>0&&this.isTouch()==false)x-=this.speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;}this.direct=(int)(Math.random()*4);if(this.isLive==false){break;}if(ensh.size()<5){Shot es=null;switch(this.direct){case 0:es=new Shot(this.getX()+10,this.getY(),0);ensh.add(es);break;case 1:es=new Shot(this.getX()+30,this.getY()+10,1);ensh.add(es);break;case 2:es=new Shot(this.getX()+10,this.getY()+30,2);ensh.add(es);break;case 3:es=new Shot(this.getX(),this.getY()+10,3);ensh.add(es);break;}Thread th=new Thread(es);th.start();}}}}//炸弹类class Bomb{int x;int y;int lift=9;boolean isLive=true;public Bomb(int x,int y){this.x=x;this.y=y;}//炸弹的生命值public void liftdown(){if(lift>0){lift--;}else{isLive=false;}}}//子弹类class Shot implements Runnable{int shotX;int shotY;int direct;int shotspeed=1;boolean isLive=true;public Shot(int x,int y,int direct){this.shotX=x;this.shotY=y;this.direct=direct;}public int getShotX() {return shotX;}public void setShotX(int shotX) {this.shotX = shotX;}public int getShotY() {return shotY;}public void setShotY(int shotY) {this.shotY = shotY;}public int getShotspeed() {return shotspeed;}public void setShotspeed(int shotspeed) {this.shotspeed = shotspeed;}public void run(){while(true){try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}switch(direct){case 0:shotY-=shotspeed;break;case 1:shotX+=shotspeed;break;case 2:shotY+=shotspeed;break;case 3:shotX-=shotspeed;break;}if(shotX<0||shotX>400||shotY<0||shotY>300){isLive=false;break;}}}}/*** 功能:坦克大战4.0*/package com.tankgame4;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.Vector;import java.io.*;import javax.swing.*;import javax.imageio.*;public class MyTankGame4 extends JFrame implements ActionListener{MyPanel mp=null;MyStartPanel msp=null;//菜单定义JMenuBar jmb=null;JMenu jm1=null;JMenuItem jmi1=null;public static void main(String[] args) {// TODO Auto-generated method stubMyTankGame4 mtg=new MyTankGame4();}//构造函数public MyTankGame4(){//创建菜单jmb=new JMenuBar();jm1=new JMenu("Game(G)");jm1.setMnemonic('G');jmi1=new JMenuItem("New Game(N)");jmi1.setMnemonic('N');jmi1.addActionListener(this);jmi1.setActionCommand("New Game");jm1.add(jmi1);jmb.add(jm1);this.setJMenuBar(jmb);msp=new MyStartPanel();Thread st=new Thread(msp);st.start();this.add(msp);this.setTitle("坦克大战");this.setSize(400, 300);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}public void actionPerformed(ActionEvent arg0) {if(arg0.getActionCommand().equals("New Game")){this.remove(msp);mp=new MyPanel();Thread mt=new Thread(mp);mt.start();this.add(mp);this.addKeyListener(mp);this.setVisible(true);}}}//游戏开始面板class MyStartPanel extends JPanel implements Runnable{int times=0;public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 400, 300);if(times%2==0){Font myfont=new Font("行楷",Font.BOLD,30);g.setFont(myfont);g.setColor(Color.yellow);g.drawString("第一关", 130, 130);}this.repaint();}public void run() {while(true){try {Thread.sleep(300);times++;} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}//我的面板class MyPanel extends JPanel implements KeyListener,Runnable {//定义一个我的坦克Hero hero=null;EnemyTank et=null;Image image1=null;Image image2=null;Image image3=null;Image im=null;Vector<Bomb> bombs =new Vector<Bomb>();Vector<EnemyTank> etm =new Vector<EnemyTank>();int ensize=5;public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 400, 300);g.drawImage(im, 0, 0, 400, 300,this);//画出自己的坦克if(hero.isLive==true){this.drawTank(this.hero.getX(), this.hero.getY(),g, this.hero.getDirect(),this.hero.getColor() );}//画出子弹for(int i=0;i<hero.shotm.size();i++){Shot myshot=hero.shotm.get(i);if(myshot!=null&&myshot.isLive==true){g.fill3DRect(myshot.getShotX(),myshot.getShotY(), 2, 2, false);}if(myshot.isLive==false)hero.shotm.remove(myshot);}//画出炸弹for(int i=0;i<bombs.size();i++){Bomb b=bombs.get(i);if(b.lift>6){g.drawImage(image1, b.x, b.y, 30, 30, this);}else if(b.lift>3){g.drawImage(image2, b.x, b.y, 30, 30, this);}else{g.drawImage(image3, b.x, b.y, 30, 30, this);}b.liftdown();if(b.lift==0)bombs.remove(b);}//画出敌人的坦克for(int i=0;i<etm.size();i++){et=etm.get(i);if(et!=null&&et.isLive==true){this.drawTank(et.getX(), et.getY(),g, et.getDirect(), et.getColor());}//画出敌人的子弹for(int j=0;j<et.ensh.size();j++){Shot enshot=et.ensh.get(j);if(enshot.isLive==true){g.fill3DRect(enshot.getShotX(),enshot.getShotY(), 2, 2, false);// System.out.println("第"+i+"辆坦克的第"+j+"颗子弹的Y="+enshot.getShotY());}else{et.ensh.remove(enshot);}}}}//判断子弹是否击中坦克的函数public void hitTank(Shot s,Tank t){switch(t.getDirect()){case 0:case 2:if(s.getShotX()>t.getX()&&s.getShotX()<t.getX()+20&&s.getShotY()>t.getY()&&s.getShotY()<t.getY()+30) {s.isLive=false;t.isLive=false;Bomb b=new Bomb(t.getX(),t.getY());bombs.add(b);}break;case 1:case 3:if(s.getShotX()>t.getX()&&s.getShotX()<t.getX()+30&&s.getShotY()>t.getY()&&s.getShotY()<t.getY()+20) {s.isLive=false;t.isLive=false;Bomb b=new Bomb(t.getX(),t.getY());bombs.add(b);}}}//画出坦克的函数public void drawTank(int xx,int yy,Graphics g,int direct,int type){//判断什么颜色类型的坦克switch(type){case 0:g.setColor(Color.CY AN);break;case 1:g.setColor(Color.pink);break;case 2:g.setColor(Color.red);break;case 3:g.setColor(Color.green);break;case 4:g.setColor(Color.blue);break;case 5:g.setColor(Color.yellow);break;}//判断什么方向的坦克switch(direct){//向上case 0:g.fill3DRect(xx, yy, 5, 30, false);g.fill3DRect(xx+15, yy, 5, 30, false);g.fill3DRect(xx+5, yy+5, 10, 20, false);g.fillOval(xx+5, yy+10, 10, 10);g.drawLine(xx+10, yy+15, xx+10, yy);break;//向右case 1:g.fill3DRect(xx, yy, 30, 5, false);g.fill3DRect(xx, yy+15, 30, 5, false);g.fill3DRect(xx+5, yy+5, 20, 10, false);g.fillOval(xx+10, yy+5, 10, 10);g.drawLine(xx+15, yy+10, xx+30, yy+10);break;//向下case 2:g.fill3DRect(xx, yy, 5, 30, false);g.fill3DRect(xx+15, yy, 5, 30, false);g.fill3DRect(xx+5, yy+5, 10, 20, false);g.fillOval(xx+5, yy+10, 10, 10);g.drawLine(xx+10, yy+15, xx+10, yy+30);break;//向左case 3:g.fill3DRect(xx, yy, 30, 5, false);g.fill3DRect(xx, yy+15, 30, 5, false);g.fill3DRect(xx+5, yy+5, 20, 10, false);g.fillOval(xx+10, yy+5, 10, 10);g.drawLine(xx+15, yy+10, xx, yy+10);break;}}public MyPanel(){hero=new Hero(100,100);im=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/28951278.jpg"));//创建敌人坦克for(int i=0;i<ensize;i++){et=new EnemyTank((i+1)*50,0);Shot enshot=new Shot(et.getX()+10,et.getY()+30,et.getDirect());Thread eth=new Thread(enshot);eth.start();et.ensh.add(enshot);Thread th=new Thread(et);th.start();etm.add(et);et.setets(etm);}// try {// image1=ImageIO.read(new File("bomb_1.gif"));// image2=ImageIO.read(new File("bomb_2.gif"));// image3=ImageIO.read(new File("bomb_3.gif"));// } catch (IOException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }image1=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_1.gif"));image2=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_2.gif"));image3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_3.gif"));}//控制坦克移动public void keyPressed(KeyEvent arg0) {// TODO Auto-generated method stubif(arg0.getKeyCode()==KeyEvent.VK_DOWN){this.hero.setDirect(2);this.hero.movedown();}else if(arg0.getKeyCode()==KeyEvent.VK_UP){this.hero.setDirect(0);this.hero.moveup();}else if(arg0.getKeyCode()==KeyEvent.VK_LEFT){this.hero.setDirect(3);this.hero.moveleft();}else if(arg0.getKeyCode()==KeyEvent.VK_RIGHT){this.hero.setDirect(1);this.hero.moveright();}else if(arg0.getKeyCode()==KeyEvent.VK_P){hero.speed=0;et.speed=0;}//发射子弹(连发5枚子弹)if(hero.shotm.size()<=4){if(arg0.getKeyCode()==KeyEvent.VK_SPACE){hero.shotenemy(hero.getX(),hero.getY(),hero.getDirect());}}//控制坦克不能跑出边界if(this.hero.getX()<0)this.hero.setX(0);if(this.hero.getY()<0)this.hero.setY(0);if(this.hero.getX()>365)this.hero.setX(365);if(this.hero.getY()>270)this.hero.setY(270);//面板重绘this.repaint();}public void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}public void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}public void run() {while(true){try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//不停地调用敌人是否打中自己坦克函数for(int i=0;i<etm.size();i++){et=etm.get(i);for(int j=0;j<et.ensh.size();j++){Shot enshot=et.ensh.get(j);if(enshot.isLive==true&&hero.isLive==true){this.hitTank(enshot, hero);}}}//不停地调用是否打中敌人坦克函数for(int i=0;i<hero.shotm.size();i++){Shot s=hero.shotm.get(i);if(s!=null&&s.isLive==true){for(int j=0;j<etm.size();j++){EnemyTank et=etm.get(j);if(et!=null&&et.isLive==true){this.hitTank(s, et);}}}}//面板重绘this.repaint();}}}。

相关文档
最新文档