坦克大战java编程

合集下载

坦克大战程序代码

坦克大战程序代码

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版坦克大战--事件处理】坦克动起来了

【java版坦克⼤战--事件处理】坦克动起来了折腾了这么久,坦克总算能动了。

只贴代码编辑不给上⾸页,花了半个⼩时的时间写了n多注释。

再顺便把绘图的原理发在这⾥:绘图原理Component类提供了两个和绘图有关的重要⽅法:① paint(Graphics g)绘制组件的外观.② repaint()刷新组件的外观当组件第⼀次在屏幕显⽰的时候,程序会⾃动调⽤paint()⽅法绘制组件.类 Paneljava.awt.Panel在上⼀节种public MyPanel extends Panel{public void paint(Graphics g){super.paint(g);g.drawRect();…}}现在可以为什么MyPanel继承了Panel就会有paint⽅法,可以画图了.在以下情况下paint()⽅法将会被调⽤.1.窗⼝最⼩化,再最⼤化.2.窗⼝⼤⼩发⽣变化.3.repaint函数被调⽤.事件监听的步骤:⼀个类实现监听的步骤:1. 实现相应的接⼝(KeyListener,MouseListener,ActionListener,WindowListener)2. 实现对事件的处理⽅法3. 在事件源上注册监听MyTankGame21/**2 * 坦克游戏的2.0版3 * 1.画出坦克4 * 2.我的坦克可以上下左右移动5*/6package com.test5;78import java.awt.*;9import java.awt.event.*;10import javax.swing.*;1112public class MyTankGame2 extends JFrame {1314 MyPanel mp = null;15public static void main(String[] args) {16 MyTankGame2 myTankGame2 = new MyTankGame2();17 }18//构造函数19public MyTankGame2(){20 mp = new MyPanel();21this.add(mp);22//c)在事件源上注册监听,mp为监听器23this.addKeyListener(mp);2425this.setSize(400,300);26this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);27this.setVisible(true);28 }29 }30/*31 * 我的⾯板,不清楚为什么MyPanel继承Panel监听没有效果。

JAVA课程设计 坦克大战

JAVA课程设计 坦克大战

得分显示:在游戏 界面实时显示得分 情况,方便玩家了 解游戏进度
减少内存占用:优 化数据结构,减少 不必要的内存分配
提高渲染效率: 优化渲染算法, 减少渲染时间
优化网络通信:减 少网络延迟,提高 网络通信效率
优化AI算法:提高 AI算法的效率和准 确性,提高游戏体 验
界面布局:合 理规划界面布 局,提高用户
玩家需要控制坦克,消灭敌 人,保护自己的基地
游戏支持多人在线对战,玩 家可以与朋友一起挑战
玩家控制 坦克,在 战场上与 敌人战斗
坦克可以 发射炮弹, 摧毁敌人 或障碍物
玩家需要 躲避敌人 的攻击, 保护自己 的坦克
游戏有各 种关卡, 难度逐渐 增加
玩家可以 通过升级 坦克,提 高战斗力
游戏支持 多人在线 对战,增 加游戏乐 趣
生命值耗尽:当 玩家的生命值降 至0时,游戏结束
时间耗尽:当游 戏时间耗尽时, 游戏结束
胜利条件:当玩 家达到胜利条件 时,游戏结束
失败条件:当玩 家达到失败条件 时,游戏结束
得分规则:击毁敌 方坦克得分,被敌 方坦克击毁扣分
得分方式:根据击 毁敌方坦克的数量 和难度计算得分
得分限制:得分上 限为1000分,达到 上限后不再增加得 分
,a click to unlimited possibilities
汇报人:
01
02
03
04
05
06
游戏类型:坦克大战
游戏背景:二战时期
游戏目标:摧毁敌方坦克,保 护自己的基地
游戏玩法:玩家控制坦克,通 过射击和躲避来消灭敌方坦克
游戏包含多个关卡,每个关 卡有不同的难度和挑战
设计一款坦克大战游戏
游戏界面:包括 菜单、地图、角 色、道具等元素

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

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

游戏结束判断
生命值耗尽:当坦克的生命值降至0时,游戏结束 游戏时间结束:当游戏时间达到预设值时,游戏结束 胜利条件达成:当一方达到预设的胜利条件时,游戏结束 玩家主动退出:当玩家主动选择退出游戏时,游戏结束
游戏得分计算
得分规则:击毁敌 方坦克、保护己方 坦克、完成特定任 务等
得分方式:根据击 毁敌方坦克的数量、 保护己方坦克的数 量、完成任务的难 度等计算得分
得分显示:在游戏 界面实时显示得分 情况,方便玩家了 解游戏进度
得分记录:游戏结 束后,记录玩家的 分情况,方便玩 家查看历史成绩
游戏优化与扩展
游戏性能优化
优化算法: 使用更高 效的算法, 如动态规 划、贪心 算法等
减少内存 占用:优 化数据结 构,减少 不必要的 内存占用
优化渲染: 使用更高 效的渲染 技术,如 OpenGL、 DirectX 等
优化网络 传输:使 用更高效 的网络传 输协议, 如TCP、 UDP等
优化AI: 使用更高 效的AI算 法,如神 经网络、 遗传算法 等
优化资源 管理:合 理分配系 统资源, 避免资源 浪费
游戏扩展功能实现
增加新的坦克类型:如重型坦克、轻 型坦克等
增加新的地图:如沙漠地图、雪地地 图等
增加新的游戏模式:如团队模式、生 存模式等
音效类型:背景音乐、战斗音效、 胜利音效等
音效处理:音量调节、音效混合、 音效剪辑等
添加标题
添加标题
添加标题
添加标题
音效来源:自行创作、购买版权、 网络下载等
音效与游戏场景的结合:根据游戏 场景选择合适的音效,增强游戏体 验
游戏实体设计
坦克类设计
坦克属性:生命值、攻击 力、防御力、速度等

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程序

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课设报告坦克大战

java课设报告坦克大战

java课设报告坦克大战什么是Java课设报告坦克大战?Java课设报告坦克大战是一个基于Java编程语言开发的游戏项目。

它模拟了坦克战争的场景,玩家需要操控一辆坦克,与其他玩家或者电脑控制的敌人进行战斗,完成各种任务。

这个项目旨在提高学生的Java编程能力和团队协作能力。

第一步:需求分析和设计在开始编写代码之前,我们需要进行需求分析和设计。

首先,确定游戏的功能和玩法。

例如,游戏应该具有地图、坦克、子弹等基本元素,玩家可以使用键盘控制坦克的移动和攻击,坦克和子弹应该有相应的属性和行为,坦克应该能够与其他坦克进行交互等等。

其次,我们需要设计游戏的界面和用户交互方式,包括游戏的开始菜单、游戏画面、得分、生命值等界面元素。

最后,我们应该考虑游戏的可扩展性,使得我们能够在后续的开发过程中添加更多的功能和元素。

第二步:编写代码在设计完成后,我们开始编写Java代码。

首先,我们创建一个Java项目,并进行必要的配置,例如添加游戏所需的外部库和资源文件。

然后,我们开始编写代码。

我们可以将游戏的不同元素,例如地图、坦克、子弹等,抽象成不同的类,并为每个类定义相应的属性和方法。

我们还可以使用设计模式和面向对象的编程思想,使得代码更加清晰和可维护。

同时,我们需要为游戏添加适当的事件处理器,以响应用户的操作和更新游戏状态。

我们还可以使用Java图形库或者相关的游戏引擎,使游戏具有更好的视觉效果和用户体验。

第三步:测试和调试在代码编写完成后,我们需要进行测试和调试。

我们可以编写一些测试用例,验证游戏的各个功能和元素是否正常工作。

同时,我们需要定期检查并修复可能存在的bug和错误,确保游戏的稳定性和可玩性。

在这个过程中,我们可以与团队成员合作,互相交流和帮助,提高解决问题的效率和质量。

第四步:项目上线和发布在完成测试和调试后,我们可以将游戏部署到服务器上,并发布给玩家。

我们可以选择通过应用商店或者网站进行发布,或者将游戏打包成可执行文件,供玩家下载和安装。

坦克大战【java项目】

坦克大战【java项目】

坦克⼤战【java项⽬】坦克⼤战(JAVA项⽬)1.项⽬简介复刻童年经典⼩游戏——坦克⼤战:⽤户进⼊游戏界⾯后,通过键盘上的数字1,2键选择游戏模式,选择1并按回车键进⼊单⼈模式;选择2并按回车键进⼊双⼈模式。

玩家1可通过按键WASD控制坦克⽅向及移动,并且按空格发射⼦弹。

玩家2通过⽅向键控制坦克⽅向移动,并且按K键发射⼦弹。

⼦弹碰到围墙后消失,⼦弹碰到坦克后产⽣爆炸特效。

左上⾓记录敌⽅坦克的实时数量。

玩家击败所有敌⽅坦克,游戏胜利;若所有我⽅坦克被击败,或者我⽅基地被摧毁,则游戏失败。

2.⼩组成员及分⼯成员负责任务组长黄抒鸿博客撰写,游戏规则的制定,碰撞检测,爆炸特效的实现,随机事件的编写组员雷正伟前期调研,⾯向对象设计,窗体绘制,闪动问题的解决,键盘事件的编写3.项⽬功能架构图与主要功能流程图3.1项⽬功能架构图3.2主要功能流程图3.3⾯向对象类设计图4.功能详解4.1 窗体绘制及添加键盘事件4.1.1 创建窗⼝·创建类继承JFrame·创建启动⽅法launch()4.1.2 为窗⼝上⾊·重写paint()⽅法,设置图形颜⾊和⼤⼩4.1.3 添加选项⽂字4.1.4 为窗⼝添加键盘事件添加内部类,实现KeyAdapter类,重写keyPressed⽅法,写⼊键盘事件,1选择单⼈模式,2选择双⼈模式窗⼝添加键盘监视器添加指针图⽚在项⽬⽂件夹下创建⽂件夹images,关于项⽬的图⽚,插件都放在这个⽂件夹内创建图⽚对象在launch()⽅法中重绘图形4.2双缓冲解决闪动问题创建⼀个图⽚Image offScreemImage = null;重写paint()⽅法创建⼀个和弹出窗⼝宽⾼相同的图⽚,获取该图⽚的图形对象,把所有内容添加到该图⽚中//创建和容器⼀样⼤⼩的Image图⽚if(offScreemImage == null) {offScreemImage = this.createImage(width,height);}//获的该图⽚的图形Graphics gImage = offScreemImage.getGraphics();gImage.setColor(Color.GRAY);gImage.fillRect(0, 0, width, height);//添加游戏选项gImage.setColor(Color.BLUE);gImage.setFont(new Font("仿宋", Font.BOLD, 50));if (state == 0 ) {gImage.drawString("选择游戏模式", 220, 100);gImage.drawString("单⼈模式", 220, 200);gImage.drawString("双⼈模式", 220, 300);//绘制指针gImage.drawImage(select, 160, y, null);} else if (state ==1 || state ==2) {gImage.drawString("游戏开始", 220, 100);if (state ==1) {gImage.drawString("单⼈模式", 220, 200);} else if(state ==2) {gImage.drawString("双⼈模式", 220, 200);}}4.3⾯向对象设计游戏⽗类:坦克类:玩家⼀和玩家⼆玩家2和玩家1的⽅法都是⼀样的,只需要修改键盘事件。

坦克大战游戏编程实现

坦克大战游戏编程实现

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

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

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

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

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

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

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

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

以下是使用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课程设计坦克大战(含代码)

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的图形用户界面而开发的,可以放松心情的小游戏。

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

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

坦克大战

坦克大战

package tank_war_1;import java.awt.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.*;import javax.imageio.ImageIO;import javax.swing.*;import java.util.*;//Game center.----------------------------------------------------------------------------------------- public class TankWar extends JFrame {private static final long serialVersionUID = 1L;private Draw window;public static void main(String[] args) {TankWar map = new TankWar();}// 构造public TankWar() {window = new Draw();// Start the window 线程。

Thread t = new Thread(window);t.start();this.add(window);this.addKeyListener(window);this.setSize(1366, 768);this.setVisible(true);}}// Panel----------------------------------------------------------------------------------------------- class Draw extends JPanel implements KeyListener, Runnable {private static final long serialVersionUID = 1L;// Definition my tank.......................MyTank tank1 = null;// Definition enemy tank....................Vector<EnemyTank> enemys = new Vector<EnemyTank>();int enSize = 15;// Bang's processVector<Bang> ba = new Vector<Bang>();Color c1, c2;// Biagbang's three pictureImage bang1 = null;Image bang2 = null;Image bang3 = null;public Draw() {tank1 = new MyTank(15, 320);for (int i = 0; i < enSize; i++) {// A enemy tank.....................EnemyTank enemy = new EnemyTank((i + 1) * 50 + 200, 10);enemys.add(enemy);enemy.setColor(1);enemy.setDirection(2);// Let enemy can see each otherenemy.setets(enemys);// Start enemyThread t = new Thread(enemy);t.start();// Add bulletShot s = new Shot(enemy.x + 11, enemy.y + 36, 2);enemy.ss.add(s);Thread t2 = new Thread(s);t2.start();enemys.add(enemy);// I don't know/////////////}// Bang picturetry {bang1 = ImageIO.read(new File("bang1.gif"));// image in Tank warbang2 = ImageIO.read(new File("bang2.gif"));bang3 = ImageIO.read(new File("bang3.gif"));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//bang1=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bang1.gif"));//bang2=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bang2.gif")) ;//bang3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bang3.gif")) ;// image in src}public void paint(Graphics g) {// Add tank........................................super.paint(g);setBackground(Color.black);// Add my tank.....................................if (tank1.noBang) {this.DrawTank(tank1.getX(), tank1.getY(), g, tank1.getDirection(),0);}// Add Many Fire...................................for (int i = 0; i < tank1.ss.size(); i++) {// Add fire........................................Shot ms = tank1.ss.get(i);if (ms != null && ms.noBang == true) {g.setColor(Color.red);g.draw3DRect(ms.x, ms.y, 2, 2, false);}// Remove fire....................................if (ms.noBang == false) {tank1.ss.remove(ms);}}// Add Big Bang !for (int i = 0; i < ba.size(); i++) {Bang b = ba.get(i);if (b.time > 30) {g.drawImage(bang2, b.x, b.y, 30, 30, this);}if (b.time <= 30 && b.time > 20) {g.drawImage(bang1, b.x, b.y, 30, 30, this);}if (b.time <= 20 && b.time > 10) {g.drawImage(bang2, b.x, b.y, 30, 30, this);}if (b.time <= 10) {g.drawImage(bang3, b.x, b.y, 30, 30, this);}b.BangDown();// Delete the Bangif (b.time == 0) {ba.remove(b);}}// Add enemy tank and bullet..................................for (int i = 0; i < enemys.size(); i++) {EnemyTank et = enemys.get(i);if (et.noBang) {this.DrawTank(et.getX(), et.getY(), g, et.getDirection(), 1);// Add bulletfor (int j = 0; j < et.ss.size(); j++) {Shot es = et.ss.get(j);if (es.noBang){g.draw3DRect(es.x, es.y, 2, 2, false);} else {et.ss.remove(es);}}}}}// My bullet hit enemy..............................public void MyBulletHit() {for (int i = 0; i < tank1.ss.size(); i++) {Shot ms = tank1.ss.get(i);if (ms.noBang) {for (int j = 0; j < enemys.size(); j++) {EnemyTank et = enemys.get(j);if (et.noBang) {this.hitTank(ms, et);}}}}}// Enemy bullet hit me............................public void EnemyBulletHit() {for (int i = 0; i < enemys.size(); i++) {EnemyTank et = enemys.get(i);for (int j = 0; j < et.ss.size(); j++) {Shot es = et.ss.get(j);this.hitTank(es, tank1);}}}// Despair enemy tank.............................public void hitTank(Shot s, Tank enemy) {// Enemy's direction~.........................switch (enemy.getDirection()) {case 0:// UP and DOWNcase 2:if (s.x >= enemy.x && s.x <= enemy.x + 22 && s.y >= enemy.y - 1 && s.y <= enemy.y + 30) {// Bullet deads.noBang = false;// Enemy tank is deadenemy.noBang = false;// Big Bang !!!!!Bang b = new Bang(enemy.x, enemy.y);ba.add(b);}break;case 1:// RIGHT and LEFTcase 3:if (s.x >= enemy.x - 5 && s.x <= enemy.x + 26 && s.y >= enemy.y + 4 && s.y <= enemy.y + 26) {// Bullet deads.noBang = false;// Enemy tank is deadenemy.noBang = false;}break;}}// Draw Tank............................................public void DrawTank(int x, int y, Graphics g, int direct, int type) { c1 = new Color(120, 120, 120);c2 = new Color(160, 160, 160);// Draw tank's style1...............................switch (type) {case 0:g.setColor(Color.red);break;case 1:g.setColor(Color.yellow);break;case 2:g.setColor(Color.blue);break;case 3:g.setColor(Color.green);break;}// Draw tank's direction...........................switch (direct) {case 0:// upg.fill3DRect(x, y, 6, 30, true); // leftg.fill3DRect(x + 16, y, 6, 30, true); // rightg.setColor(c2);g.fill3DRect(x + 6, y + 5, 10, 20, true); // centerg.setColor(c1);g.fillOval(x + 6, y + 10, 10, 10); // ovalg.setColor(Color.gray);g.fill3DRect(x + 10, y, 2, 11, true); // gun1g.fill3DRect(x + 9, y - 6, 4, 6, true); // gun2break;case 1:// right.......................................g.fill3DRect(x - 4, y + 4, 30, 6, true); // leftg.fill3DRect(x - 4, y + 20, 30, 6, true); // rightg.setColor(c2);g.fill3DRect(x + 1, y + 10, 20, 10, true); // centerg.setColor(c1);g.fillOval(x + 6, y + 10, 10, 10); // ovalg.setColor(Color.gray);g.fill3DRect(x + 16, y + 14, 11, 2, true); // gun1g.fill3DRect(x + 27, y + 13, 6, 4, true); // gun2break;case 3:// Left.......................................g.fill3DRect(x - 4, y + 4, 30, 6, true); // leftg.fill3DRect(x - 4, y + 20, 30, 6, true); // rightg.setColor(c2);g.fill3DRect(x + 1, y + 10, 20, 10, true); // centerg.setColor(c1);g.fillOval(x + 6, y + 10, 10, 10); // ovalg.setColor(Color.gray);g.fill3DRect(x - 5, y + 14, 11, 2, true); // gun1g.fill3DRect(x - 11, y + 13, 6, 4, true); // gun2break;case 2:// Down........................................g.fill3DRect(x, y, 6, 30, true); // leftg.fill3DRect(x + 16, y, 6, 30, true); // rightg.setColor(c2);g.fill3DRect(x + 6, y + 5, 10, 20, true); // centerg.setColor(c1);g.fillOval(x + 6, y + 10, 10, 10); // ovalg.setColor(Color.gray);g.fill3DRect(x + 10, y + 21, 2, 11, true); // gun1g.fill3DRect(x + 9, y + 32, 4, 6, true); // gun2break;}}// Key listener wdsa// 0123............................................................public void keyPressed(KeyEvent e) {// My tank's direction..................................switch (e.getKeyCode()) {case KeyEvent.VK_W:// Up................................this.tank1.setDirection(0);this.tank1.moveUp();break;case KeyEvent.VK_D:// Right..............................this.tank1.setDirection(1);this.tank1.moveRight();break;case KeyEvent.VK_S:// Down..............................this.tank1.setDirection(2);this.tank1.moveDown();break;case KeyEvent.VK_A:// Left...............................this.tank1.setDirection(3);this.tank1.moveLeft();break;}// if(e.getKeyCode()==KeyEvent.VK_W)// {// this.tank1.setDirection(0);// this.tank1.moveUp();// }else if(e.getKeyCode()==KeyEvent.VK_D)// {// this.tank1.setDirection(1);// this.tank1.moveRight();// }else if(e.getKeyCode()==KeyEvent.VK_S)// {// this.tank1.setDirection(2);// this.tank1.moveDown();// }else if(e.getKeyCode()==KeyEvent.VK_A)// {// this.tank1.setDirection(3);// this.tank1.moveLeft();// }if (e.getKeyCode() == KeyEvent.VK_J)// Fire............................... {if (this.tank1.ss.size() < 5)// 5 Time!{this.tank1.Fire();}}// Must repaint....repaint();}public void keyTyped(KeyEvent e) {}public void keyReleased(KeyEvent e) {}@Overridepublic void run() {// TODO Repaint the fire,while (true) {try {Thread.sleep(25);} catch (Exception e) {}// My bullet hit enemythis.MyBulletHit();// Enemy's bullet hit methis.EnemyBulletHit();this.repaint();}}}package tank_war_1;import java.util.*;// Bullet----------------------------------------------------------------------------------------- class Shot implements Runnable{int x;int y;int direction;int speed=3;boolean noBang=true;public Shot(int x,int y,int direction){this.x=x;this.y=y;this.direction=direction;}public void run() {while(true){try{Thread.sleep(25);}catch(Exception e){}switch(direction)// The running fire!!....................{case 0:y-=speed;break;case 1:x+=speed;break;case 2:y+=speed;break;case 3:x-=speed;break;}// Edge..............................if(x<0||x>700||y<0||y>400){this.noBang=false;break;}}}}// Bang-----------------------------------------------------------------------------------------class Bang{int x;int y;int time=40;boolean noBang=true;public Bang(int x,int y){this.x=x;this.y=y;}public void BangDown(){if(time>0){time--;}else{this.noBang=false;}}}// Tank----------------------------------------------------------------------------------------- class Tank{// tank's positionint x;int y;//Tank's directionint direction;// Tank's speedint speed=4;// Tank's colorint color;// Tank is liveboolean noBang=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 getDirection(){return direction;}public void setDirection(int direction){ this.direction=direction;}public int getSpeed(){return speed;}public void setSpeed(int speed){this.speed=speed;}public int getColor(){return color;}public void setColor(int color){this.color=color;}}//My tank---------------------------------------------------------------------------------------------- class MyTank extends Tank{Vector<Shot>ss=new Vector<Shot>();Shot s=null;public MyTank(int x,int y){super(x, y);}public void Fire()// Fire................................{switch (this.direction){case 0:s=new Shot(x+10,y-6,0);ss.add(s);break;case 1:s=new Shot(x+30,y+14,1);ss.add(s);break;case 2:s=new Shot(x+10,y+35,2);ss.add(s);break;case 3:s=new Shot(x-11,y+14,3);ss.add(s);break;}Thread t=new Thread(s);t.start();}// Tank go up...............................public void moveUp(){this.y-=this.speed;}public void moveRight(){this.x+=this.speed;}public void moveDown(){this.y+=this.speed;}public void moveLeft(){this.x-=this.speed;}}// Enemy Tank---------------------------------------------------------------------------------------- class EnemyTank extends Tank implements Runnable{// 子弹周期int time=0;//定义向量,can access the panel's Enemy tankVector <EnemyTank> ets=new Vector<EnemyTank>();// Add bulletVector<Shot> ss=new Vector();public EnemyTank(int x, int y){super(x, y);}// Access panel's Enemy tankpublic void setets(Vector<EnemyTank> touch1){this.ets=touch1;}// 判断if touch the enemy tankpublic boolean isTouchE(){boolean isTouchE=false;// 间隔int itv=9;// 判断switch(this.direction){case 0:// up........................................for(int i=0;i<ets.size();i++){EnemyTank et=ets.get(i);if(et!=this){if(et.direction==0||et.direction==2)/////{if(this.x>et.x&&this.x<et.x+22&&this.y>et.y&&this.y<et.y+30){return true;}if(this.x+22>et.x&&this.x+22<et.x+22&&this.y>et.y&&this.y<et.y+30){return true;}}if(et.direction==1||et.direction==3)/////{if(this.x>et.x-4&&this.x<et.x+26&&this.y>et.y+4&&this.y<et.y+26){return true;}if(this.x+22>et.x-4&&this.x+22<et.x+26&&this.y>et.y+4&&this.y<et.y+26){return true;}}}}break;case 1:// right.......................................for(int i=0;i<ets.size();i++){EnemyTank et=ets.get(i);if(et!=this){if(et.direction==0||et.direction==2){if(this.x+26>et.x&&this.x+26<et.x+22&&this.y+4>et.y&&this.y+4<et.y+30){return true;}if(this.x+26>et.x&&this.x+26<et.x+22&&this.y+26>et.y&&this.y+26<et.y+30){return true;}}if(et.direction==1||et.direction==3){if(this.x+26>et.x-4&&this.x+26<et.x+26&&this.y+4>et.y+4&&this.y+4<et.y+26){return true;}if(this.x+26>et.x-4&&this.x+26<et.x+26&&this.y+26>et.y+4&&this.y+26<et.y+2 6){return true;}}}}break;case 2:// down.......................................for(int i=0;i<ets.size();i++){EnemyTank et=ets.get(i);if(et!=this){if(et.direction==0||et.direction==2){if(this.x>et.x&&this.x<et.x+22&&this.y+30>et.y&&this.y+30<et.y+30){return true;}if(this.x+22>et.x&&this.x+22<et.x+22&&this.y+30>et.y&&this.y+30<et.y+30){return true;}}if(et.direction==1||et.direction==3){if(this.x>et.x-4&&this.x<et.x+26&&this.y+30>et.y+4&&this.y+30<et.y+26){return true;}if(this.x+22>et.x-4&&this.x+22<et.x+26&&this.y+30>et.y+4&&this.y+30<et.y+2 6){return true;}}}}break;case 3:// left.......................................for(int i=0;i<ets.size();i++){EnemyTank et=ets.get(i);if(et!=this){if(et.direction==0||et.direction==2){if(this.x-4>et.x&&this.x-4<et.x+22&&this.y+4>et.y&&this.y+4<et.y+30){return true;}if(this.x-4>et.x&&this.x-4<et.x+22&&this.y+26>et.y&&this.y+26<et.y+30){return true;}}if(et.direction==1||et.direction==3){if(this.x-4>et.x-4&&this.x-4<et.x+26&&this.y+4>et.y+4&&this.y+4<et.y+26){return true;}if(this.x-4>et.x-4&&this.x-4<et.x+26&&this.y+26>et.y+4&&this.y+26<et.y+26){return true;}}}}break;}// switch(this.direction)// {// case 0:// me up// for(int i=0;i<ets.size();i++)// {// EnemyTank et=ets.get(i);// if(et!=this){// if(et.direction==0||et.direction==2)// {//if(this.x+22>et.x-itv&&this.x<et.x+22+itv&&this.y+30>et.y-itv&&this.y<et.y+30 +itv)// {// return true;// }//// }// if(et.direction==1&&et.direction==3)// {//if(this.x+22>et.x-4-itv&&this.x<et.x+26+itv&&this.y+30>et.y+4-itv&&this.y<et. y+26+itv)// {// return true;// }// }// }// }// break;// case 1: //me right// for(int i=0;i<ets.size();i++)// {// EnemyTank et=ets.get(i);// if(et!=this){// if(et.direction==0||et.direction==2)// {//if(this.x+26>et.x-itv&&this.x-4<et.x+22+itv&&this.y+26>et.y-itv&&this.y+4<et. y+30+itv)// {// return true;// }//// }// if(et.direction==1&&et.direction==3)// {//if(this.x+26>et.x-4-itv&&this.x-4<et.x+26+itv&&this.y+26>et.y+4-itv&&this.y+4 <et.y+26+itv)// {// return true;// }// }// }//// }// break;// case 2: //me down// for(int i=0;i<ets.size();i++)// {// EnemyTank et=ets.get(i);// if(et!=this){// if(et.direction==0||et.direction==2)// {//if(this.x+22>et.x-itv&&this.x<et.x+22+itv&&this.y+30>et.y-itv&&this.y<et.y+30 +itv)// {// return true;// }//// }// if(et.direction==1&&et.direction==3)// {//if(this.x+22>et.x-4-itv&&this.x<et.x+26+itv&&this.y+30>et.y+4-itv&&this.y<et. y+26+itv)// {// return true;// }// }// }// }// break;// case 3: // me left// for(int i=0;i<ets.size();i++)// {// EnemyTank et=ets.get(i);// if(et!=this){// if(et.direction==0||et.direction==2)// {//if(this.x+26>et.x-itv&&this.x-4<et.x+22+itv&&this.y+26>et.y-itv&&this.y+4<et. y+30+itv)// {// return true;// }//// }// if(et.direction==1&&et.direction==3)// {//if(this.x+26>et.x-4-itv&&this.x-4<et.x+26+itv&&this.y+26>et.y+4-itv&&this.y+4 <et.y+26+itv)// {// return true;// }// }// }//// }// break;// }return isTouchE;}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(50);}catch(Exception e){e.printStackTrace();}switch(this.direction){case 0:for(int i=0;i<15;i++){if(y>6&&!this.isTouchE())y-=speed;try {Thread.sleep(80);}catch(Exception e){e.printStackTrace();}}break;case 1:for(int i=0;i<15;i++){if(x<647&&!this.isTouchE())x+=speed;try {Thread.sleep(80);}catch(Exception e){e.printStackTrace();}}break;case 2:for(int i=0;i<15;i++){if(y<322&&!this.isTouchE())y+=speed;try {Thread.sleep(80);}catch(Exception e){e.printStackTrace();}}break;case 3:for(int i=0;i<15;i++){if(x>12&&!this.isTouchE())x-=speed;try {Thread.sleep(80);}catch(Exception e){e.printStackTrace();}}break;}// Many bullet...........................this.time++;if(time%1==0)// control the bullet's frequency {if(noBang){if(ss.size()<6){Shot s=null;switch(direction){case 0:s=new Shot(x+10,y-6,0);ss.add(s);break;case 1:s=new Shot(x+30,y+14,1);ss.add(s);break;case 2:s=new Shot(x+10,y+35,2);ss.add(s);break;case 3:s=new Shot(x-11,y+14,3);ss.add(s);break;}Thread t=new Thread(s);t.start();}}}//...................................................// Random direction!this.direction=(int)(Math.random()*4);// Deadif(this.noBang==false){break;}}}}。

坦克大战游戏

坦克大战游戏

坦克大战游戏import java.awt.*; import javax.swing.*;import java.applet.*;import java.awt.event.*;public class MytankeGame1 extends JFrame {Mypanel mp=null;public static void main(String[] args){MytankeGame1 mtg=new MytankeGame1(); }public MytankeGame1(){mp=new Mypanel();this.add(mp);//注册监听this.addKeyListener(mp);this.setSize(400,300);this.setVisible(true);}}//我的面板-0pclass Mypanel extends JPanel implements KeyListener {//定义一个我的坦克Hero hero=null;//构造函数public Mypanel(){hero=new Hero(10,10);}//重写paintpublic void paint(Graphics g){super.paint(g);g.fillRect(0,0,400,300);//画出自己的坦克this.drawTank(hero.getX(),hero.getY(),g,this.hero.direct,1);}//画出坦克函数public void drawTank(int x,int y,Graphics g,int direct,int type) {//判断是什么类型的坦克switch(type){case 0:g.setColor(Color.cyan);break;case 1:g.setColor(Color.yellow);break;}//判断方向switch(direct){//向上case 0:。

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代码Tank

坦克大战Java代码Tank

import java.awt.*;import java.awt.event.*;import java.util.*;//定义坦克类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; //坦克高度private boolean live = true; //初始化生命为trueprivate BloodBar bb = new BloodBar();//声明血块变量private int life = 100; //初始化生命值为100TankClient tc;//生命坦克客户端变量private boolean good;//设置区分敌我两方标志private int x, y; //声明两个整型私有变量x,y坐标private int oldX, oldY;//记录上一步的坐标private static Random r = new Random(); //创建一个随机数r对象//声明方向变量private boolean bL=false, bU=false, bR=false, bD = false;enum Direction {L, LU, U, RU, R, RD, D, LD, STOP};/*坦克的八个方向和一个stop 状态*/private Direction dir = Direction.STOP;private Direction ptDir = Direction.D;private int step = r.nextInt(12) + 3;//整数step在[3,14]间随机取值//构造方法public Tank(int x, int y, boolean good) {this.x = x;this.y = y;this.oldX = x;this.oldY = 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);//画出子弹if(good) bb.draw(g);switch(ptDir) {case L:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y + Tank.HEIGHT/2);break;case LU:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y);break;case U:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH/2, y);break;case RU:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y);break;case R:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y + Tank.HEIGHT/2);break;case RD:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y + Tank.HEIGHT);break;case D:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH/2, y + Tank.HEIGHT);break;case LD:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y + Tank.HEIGHT);break;}move();}//移动方法void move() {//记录上一次坐标this.oldX = x;this.oldY = y;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(this.dir != Direction.STOP) {this.ptDir = this.dir;}//控制坦克不出界if(x < 0) x = 0;if(y < 30) y = 30;if(x + Tank.WIDTH > TankClient.GAME_WIDTH) x = TankClient.GAME_WIDTH - Tank.WIDTH;if(y + Tank.HEIGHT > TankClient.GAME_HEIGHT) y = TankClient.GAME_HEIGHT - Tank.HEIGHT;if(!good) {Direction[] dirs = Direction.values();if(step == 0) {step = r.nextInt(12) + 3;int rn = r.nextInt(dirs.length);//改变方向dir = dirs[rn];}step --;if(r.nextInt(40) > 38) this.fire();}}private void stay() {x = oldX;y = oldY;}//键按下的消息处理public void keyPressed(KeyEvent e) {int key = e.getKeyCode();switch(key) {case KeyEvent.VK_Q :if(!this.live) {this.live = true;this.life = 100;}break;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();}//设定方向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 =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_A ://按下A开火superFire();break;}locateDirection();}//开火发射方法public Missile fire() {if(!live) return null;int x = this.x + Tank.WIDTH/2 - Missile.WIDTH/2;int y = this.y + Tank.HEIGHT/2 - Missile.HEIGHT/2;Missile m = new Missile(x, y, good, ptDir, this.tc);tc.missiles.add(m);return m;}public Missile fire(Direction dir) {if(!live) return null;int x = this.x + Tank.WIDTH/2 - Missile.WIDTH/2;int y = this.y + Tank.HEIGHT/2 - Missile.HEIGHT/2;Missile m = new Missile(x, y, good, dir, 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;}//判断坦克状态是否良好public boolean isGood() {return good;}//坦克与墙相撞public boolean collidesWithWall(Wall w) {if(this.live && this.getRect().intersects(w.getRect())) {this.stay();return true;}return false;}//坦克与坦克相撞public boolean collidesWithTanks(java.util.List<Tank> tanks) {for(int i=0; i<tanks.size(); i++) {Tank t = tanks.get(i);if(this != t) {if(this.live && t.isLive() && this.getRect().intersects(t.getRect())) {this.stay();t.stay();return true;}}}return false;}//发射超级子弹private void superFire() {Direction[] dirs = Direction.values();for(int i=0; i<8; i++) {fire(dirs[i]);}}//返回坦克的生命值public int getLife() {return life;}//设置坦克的生命值public void setLife(int life) {this.life = life;}//创建生命值private class BloodBar {//在坦克上方画出生命条public void draw(Graphics g) {Color c = g.getColor();g.setColor(Color.RED);g.drawRect(x, y-10, WIDTH, 10);int w = WIDTH * life/100 ;g.fillRect(x, y-10, w, 10);g.setColor(c);}}//判断坦克是否吃到东西public boolean eat(Blood b) {if(this.live && b.isLive() && this.getRect().intersects(b.getRect())) { this.life = 100;b.setLive(false);return true;}return false;}}。

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代码

import java.awt.*;//血块类public class Blood {int x, y, w, h;//定义血块坐标变量,宽度、高度变量TankClient tc; //生命坦克客户端变量int step = 0;private boolean live = true;//初始生命为true//定义5个血块数组private int[][] pos = {{350,300},{360,300},{375,275},{400,200},{360,270},{365,};290}, {340, 280}//血块构造函数public Blood() {}//画出血块public void draw(Graphics g) {}private void move() {}//看是否和子弹相碰撞public Rectangle getRect() {return new Rectangle(x, y, w , h);step ++;if(step == pos.length){}x = pos[step][0];y = pos[step][1];step = 0;if(!live) return;Color c = g.getColor();//对象c获取当前颜色g.setColor(Color.MAGENTA);//设定血块颜色为洋红色g.fillRect(x, y, w, h);//用洋红色填充矩形g.setColor(c);move();//调用move方法x = pos[0][0];y = pos[0][1];w = h = 15;//血块移动方法}}public boolean isLive() {}public void setLive(boolean live) { }this.live = live;return live;//返回生存状态//判断生存状态//设定生死状态import java.awt.*;//爆炸类public class Explode {int x, y; //定义爆炸坐标变量private boolean live = true;//初始化生命为true//引用坦克客户端对象private TankClient tc ;//定义并初始化半径数组int[] diameter = {4, 7, 12, 18, 26, 32, 49, 30, 14, 6};int step = 0;//根据碰撞位置创建爆炸public Explode(int x, int y, TankClient tc) {}//用一个圆来表示模拟爆炸public void draw(Graphics g) {if(!live) {}if(step == diameter.length) {}Color c = g.getColor();//对象c用来获取颜色live = false;step = 0;return;tc.explodes.remove(this);return;this.x = x;this.y = y;this.tc = tc;}}g.setColor(Color.ORANGE);//设定爆炸颜色为桔黄色g.fillOval(x, y, diameter[step], diameter[step]);//用桔黄色填充圆g.setColor(c);step ++;import java.awt.*;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;//子弹高度变量int x, y;//子弹坐标Tank.Direction dir;//子弹方向//子弹生死状态变量private boolean good;//设定敌我双方判断标志private boolean live = true;//判断是否存活//坦克客户对象private TankClient tc;//子弹构造函数public Missile(int x, int y, Tank.Direction dir) {}//重写构造函数public Missile(int x, int y, boolean good, Tank.Direction dir, TankClient tc) {} //在窗体上画出子弹public void draw(Graphics g) {if(!live) {tc.missiles.remove(this);return;this(x, y, dir);this.good = good;this.tc = tc;this.x = x;this.y = y;this.dir = dir;}}//如果子弹死了,则不画出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;x -= XSPEED;y -= YSPEED;break;y -= YSPEED; break;x += XSPEED; y -= YSPEED; break;x += XSPEED; break;x += XSPEED; y += YSPEED; break;y += YSPEED; break;x -= XSPEED; y += YSPEED; break; break; case LU: case U: case RU: case R: case RD:case D:case LD:case STOP:{}}//判断子弹是否出界,若出则去掉if(x < 0 || y < 0 || x > TankClient.GAME_WIDTH || y >TankClient.GAME_HEIGHT)}live = false;//判断子弹生存状态public boolean isLive() {}//获取子弹外围坐标public Rectangle getRect() {}//打坦克函数public boolean hitTank(Tank t) {}//依次判断所有敌方坦克是否被子弹击中public boolean hitTanks(List<Tank> tanks) {}//判断子弹是否击中墙public boolean hitWall(Wall w) {for(int i=0; i<tanks.size(); i++) {}return false;if(hitTank(tanks.get(i))) {}return true;if(this.live && this.getRect().intersects(t.getRect()) && t.isLive() &&}return false;if(t.isGood()) {}this.live = false;Explode e = new Explode(x, y, tc);//创建一个爆炸e对象tc.explodes.add(e);//添加到爆炸容器中return true;t.setLife(t.getLife()-20);if(t.getLife() <= 0) t.setLive(false);//坦克没血了则没生命t.setLive(false);return new Rectangle(x, y, WIDTH, HEIGHT);return live;//返回子弹生存状态this.good != t.isGood()) { //每中一次弹生命值减少20} else {}}if(this.live && this.getRect().intersects(w.getRect())) {}return false;this.live = false;return true;import java.awt.*;import java.awt.event.*;import java.util.*;//定义坦克类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; //坦克高度private boolean live = true; //初始化生命为trueprivate BloodBar bb = new BloodBar();//声明血块变量private int life = 100; //初始化生命值为100TankClient tc;//生命坦克客户端变量private boolean good;//设置区分敌我两方标志private int x, y; //声明两个整型私有变量x,y坐标private int oldX, oldY;//记录上一步的坐标private static Random r = new Random(); //创建一个随机数r对象//声明方向变量private boolean bL=false, bU=false, bR=false, bD = false;enum Direction {L, LU, U, RU, R, RD, D, LD, STOP};/*坦克的八个方向和一个stop状private Direction dir = Direction.STOP;private Direction ptDir = Direction.D;private int step = r.nextInt(12) + 3;//整数step在[3,14]间随机取值态*///构造方法public Tank(int x, int y, boolean good) {}//重写构造方法public Tank(int x, int y, boolean good, Direction dir, TankClient tc) {}//画出坦克public void draw(Graphics g) {if(!live) {}Color c = g.getColor();//获取颜色if(good) g.setColor(Color.RED);//我方坦克颜色设置为红色else g.setColor(Color.BLUE);g.fillOval(x, y, WIDTH, HEIGHT);g.setColor(c);//画出子弹if(good) bb.draw(g);switch(ptDir) {case L:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y + Tank.HEIGHT/2);break;g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y);break;g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH/2, y);break;g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y);break;if(!good) {}return;tc.tanks.remove(this);this(x, y, good);this.dir = dir;this.tc = tc;this.x = x;this.y = y;this.oldX = x;this.oldY = y;this.good = good;case LU:case U:case RU:case R:}}g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y +break;g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y +break;g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH/2, y +break;g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y + Tank.HEIGHT);break; Tank.HEIGHT/2);case RD:Tank.HEIGHT);case D:Tank.HEIGHT);case LD:move();//移动方法void move() {//记录上一次坐标this.oldX = x;this.oldY = y;switch(dir) {case L:x -= XSPEED;break;x -= XSPEED;y -= YSPEED; break;y -= YSPEED; break;x += XSPEED; y -= YSPEED; break;x += XSPEED; break;x += XSPEED; case LU: case U:case RU: case R:case RD:}}y += YSPEED; break;y += YSPEED; break;x -= XSPEED; y += YSPEED;break;break;case D:case LD:case STOP:if(this.dir != Direction.STOP) {}//控制坦克不出界if(x < 0) x = 0;if(y < 30) y = 30;if(x + Tank.WIDTH > TankClient.GAME_WIDTH) x = TankClient.GAME_WIDTH -if(y + Tank.HEIGHT > TankClient.GAME_HEIGHT) y = TankClient.GAME_HEIGHT -if(!good) {}Direction[] dirs = Direction.values();if(step == 0) {}if(r.nextInt(40) > 38) this.fire();step = r.nextInt(12) + 3;int rn = r.nextInt(dirs.length);//改变方向dir = dirs[rn];this.ptDir = this.dir;Tank.WIDTH;Tank.HEIGHT;step --;private void stay() {}//键按下的消息处理public void keyPressed(KeyEvent e) { int key = e.getKeyCode();x = oldX;y = oldY;}switch(key) {case KeyEvent.VK_Q :}locateDirection();if(!this.live) {}break; bL = true;break;bU = true;break;bR = true;break;bD = true;break;this.live = true;this.life = 100;case KeyEvent.VK_LEFT :case KeyEvent.VK_UP :case KeyEvent.VK_RIGHT :case KeyEvent.VK_DOWN ://设定方向void locateDirection() {}public void keyReleased(KeyEvent e) { int key = e.getKeyCode();switch(key) {case KeyEvent.VK_CONTROL:fire();break;bL =true;break;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;//键抬起的消息处理case KeyEvent.VK_LEFT :}case KeyEvent.VK_UP :}locateDirection();bU = true;break;bR = true;break;bD = true;break;superFire();break;case KeyEvent.VK_RIGHT :case KeyEvent.VK_DOWN :case KeyEvent.VK_A ://按下A开火//开火发射方法public Missile fire() {}public Missile fire(Direction dir) {}//看坦克是否与子弹碰撞public Rectangle getRect() {}//判断坦克是否还活着}public void setLive(boolean live) {return live;return new Rectangle(x, y, WIDTH, HEIGHT);if(!live) return null;int x = this.x + Tank.WIDTH/2 - Missile.WIDTH/2;int y = this.y + Tank.HEIGHT/2 - Missile.HEIGHT/2;Missile m = new Missile(x, y, good, dir, this.tc);tc.missiles.add(m);if(!live) return null;int x = this.x + Tank.WIDTH/2 - Missile.WIDTH/2;int y = this.y + Tank.HEIGHT/2 - Missile.HEIGHT/2;Missile m = new Missile(x, y, good, ptDir, this.tc);tc.missiles.add(m);return m;public boolean isLive() {//设定坦克的生死状态{}this.live = live;//判断坦克状态是否良好public boolean isGood() {}//坦克与墙相撞public boolean collidesWithWall(Wall w) {}//坦克与坦克相撞public boolean collidesWithTanks(java.util.List<Tank> tanks) {}//发射超级子弹private void superFire() {}public int getLife() {}public void setLife(int life) {}this.life = life;return life;Direction[] dirs = Direction.values();for(int i=0; i<8; i++) {}fire(dirs[i]);for(int i=0; i<tanks.size(); i++) {}return false;Tank t = tanks.get(i);}if(this.live&&t.isLive()&&this.getRect().intersects(t.getRect()))}this.stay(); t.stay();return true;if(this.live && this.getRect().intersects(w.getRect())) {}return false;this.stay(); return true;return good;//返回坦克的生命值//设置坦克的生命值}//创建生命值private class BloodBar {}//判断坦克是否吃到东西public boolean eat(Blood b) {}if(this.live && b.isLive() && this.getRect().intersects(b.getRect())) {}return false;this.life = 100;b.setLive(false);return true;public void draw(Graphics g) {}Color c = g.getColor();g.setColor(Color.RED);g.drawRect(x, y-10, WIDTH, 10);int w = WIDTH * life/100 ;g.fillRect(x, y-10, w, 10);g.setColor(c);//在坦克上方画出生命条import java.awt.*;import java.awt.event.*;import java.util.List;import java.util.ArrayList;//坦克游戏的窗体类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);//声明两个墙变量Wallw1=newWall(100,200,20,150,this),w2=newWall(300,100,300,20,this);List<E xplode> explodes = new ArrayList<Explode>();//创建一个存放爆炸的容器List<Missile> missiles = new ArrayList<Missile>();//创建一个存放子弹的容器List<Tank> tanks = new ArrayList<Tank>();//创建一个存放坦克的容器Image offScreenImage = null;Blood b = new Blood();//创建一个血块对象//画方法public 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);//坦克数g.drawString("tanks life:" + myTank.getLife(), 10, 110);//坦克生命//画出爆炸if(tanks.size() <= 0) {}//画出子弹for(int i=0; i<missiles.size(); i++) {}for(int i=0; i<explodes.size(); i++) {}for(int i=0; i<tanks.size(); i++) {}myTank.draw(g);//画出坦克myTank.eat(b);w1."draw(g);//画出墙Tank t = tanks.get(i);t.collidesWithWall(w1);t.collidesWithWall(w2);//坦克撞到墙t.collidesWithTanks(tanks);//坦克相撞t.draw(g);Explode e = explodes.get(i);e.draw(g);Missile m = missiles.get(i);m.hitTanks(tanks);//打敌人m.hitTank(myTank);//被敌人打m.hitWall(w1);//撞墙m.hitWall(w2);m.draw(g);//if(!m.isLive()) missiles.remove(m);//else m.draw(g);for(int i=0; i<5; i++) {}tanks.add(new Tank(50 + 40*(i+1), 50, false, Tank.Direction.D,this));}w2."draw(g);b.draw(g);//双缓存消除闪烁public void update(Graphics g) {}//启动窗口public void lauchFrame() {}public static void main(String[] args) {//画出坦克for(int i=0; i<10; i++) {}//this.setLocation(400, 300);this.setSize(GAME_WIDTH, GAME_HEIGHT);this.setTitle("TankWar");this.addWindowListener(new WindowAdapter() //处理窗口的关闭});this.setResizable(false);//设置窗口大小固定this.setBackground(Color.GREEN);//窗口背景颜色为绿色this.addKeyListener(new KeyMonitor());setVisible(true);new Thread(new PaintThread()).start();public void windowClosing(WindowEvent e) {}System.exit(0);tanks.add(new Tank(50 + 40*(i+1), 50, false, Tank.Direction.D,this));if(offScreenImage == null) {}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);offScreenImage =this.createImage(GAME_WIDTH, GAME_HEIGHT);{}}TankClient tc = new TankClient();//创建一个窗体uchFrame();//内部类新起一线程控制坦克移动private class PaintThread implements Runnable {}//增加键盘监听private class KeyMonitor extends KeyAdapter {}public void keyReleased(KeyEvent e) {}public void keyPressed(KeyEvent e) {}myTank.keyPressed(e);myTank.keyReleased(e);public void run() {}while(true) {}repaint();try {}Thread.sleep(50);//每隔50ms,坦克移动一下(重画一下)e.printStackTrace(); } catch (InterruptedException e) {//键盘抬起//键盘按下import java.awt.*;//墙类public class Wall {int x, y, w, h;//坐标,长,宽TankClient tc ;//坦克客户对象//根据墙左上角坐标,宽度,高度创建墙public Wall(int x, int y, int w, int h, TankClient tc) {this.x = x;this.y = y;}}this.w = w;this.h = h;this.tc = tc;//在窗体中画出墙public void draw(Graphics g) {}//返回墙的矩形碰撞区域public Rectangle getRect() {}return new Rectangle(x, y, w, h);g.fillRect(x, y, w, h);。

韩顺平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实现经典游戏坦克大战的示例代码

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);/*** 画出东西(包括坦克、障碍物。

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

package tank4;import java.awt.* ;import javax.swing.* ;import java.awt.event.*;import java.util.EventListener;public class HsTank2 extends JFrame {HsTank2(String title) {this.setTitle(title) ;this.setSize(610 , 640) ;this.setLocation(300 , 100) ;this.setBackground(Color.WHITE) ;MyTank mp = new MyTank() ;this.add(mp) ;this.addKeyListener(mp) ;new Thread(mp).start() ;this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public static void main(String[] args) {HsTank2 h = new HsTank2("坦克大战") ;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 = 1 ; //设置游戏难度//子弹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.WHITE) ;g.fillRect(0,0,610,640);g.setColor(Color.red) ;g.drawString("生命:"+ shengming, 10 , 10 ) ; //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.fill3DRect(x , y , 40 , 40,false) ;g.setColor(Color.blue) ;g.fill3DRect(x-5, y-5, 10, 50, false);g.fill3DRect(x+35, y-5, 10, 50, false);g.fillOval(x +5 , y+5 , 30 , 30) ;g.setColor(Color.black) ;g.fill3DRect(x + 15 , y - 20 , 10 , 40,false) ;}if(op == 2) {g.setColor(Color.red) ;g.fillRect(x , y , 40 , 40) ;g.setColor(Color.blue) ;g.fillOval(x + 5 , y+5 , 30 , 30) ;g.fill3DRect(x-5, y-5, 50, 10, false);g.fill3DRect(x-5, y+35, 50, 10, false);g.setColor(Color.black) ;g.fillRect(x + 20 , y + 15 , 40 , 10) ;}if(op == 3) {g.setColor(Color.red) ;g.fillRect(x , y , 40 , 40) ;g.setColor(Color.blue) ;g.fillOval(x + 5 , y+5 , 30 , 30) ;g.fill3DRect(x-5, y-5, 10, 50, false);g.fill3DRect(x+35, y-5, 10, 50, false);g.setColor(Color.black) ;g.fillRect(x + 15 , y + 20 , 10 , 40) ;}if(op == 4) {g.setColor(Color.red) ;g.fillRect(x , y , 40 , 40) ;g.setColor(Color.blue) ;g.fillOval(x + 5 , y+5 , 30 , 30) ;g.fill3DRect(x-5, y-5, 50, 10, false);g.fill3DRect(x-5, y+35, 50, 10, false);g.setColor(Color.black) ;g.fillRect(x - 20 , y + 15 , 40 , 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.setColor(Color.yellow) ;g.fillRect(xf[i] , yf[i] , 40 , 40) ;g.fill3DRect(xf[i]-5, yf[i]-5, 10, 50, false);g.fill3DRect(xf[i]+35, yf[i]-5, 10, 50, false);g.setColor(Color.cyan) ;g.fillOval(xf[i] + 5 , yf[i] + 5 , 30 , 30) ; g.setColor(Color.yellow) ;g.fill3DRect(xf[i] + 15 , yf[i] - 20 , 10 , 40,false) ;}if(opf[i] == 2) {g.setColor(Color.yellow) ;g.fillRect(xf[i] , yf[i] , 40 , 40) ;g.fill3DRect(xf[i]-5, yf[i]-5, 50, 10, false);g.fill3DRect(xf[i]-5, yf[i]+35, 50, 10, false);g.setColor(Color.cyan) ;g.fillOval(xf[i] + 5 , yf[i] + 5 , 30 , 30) ;g.setColor(Color.yellow) ;g.fill3DRect(xf[i] + 20 , yf[i] + 15 , 40 , 10,false) ;}if(opf[i] == 3) {g.setColor(Color.yellow) ;g.fillRect(xf[i] , yf[i] , 40 , 40) ;g.fill3DRect(xf[i]-5, yf[i]-5, 10, 50, false);g.fill3DRect(xf[i]+35, yf[i]-5, 10, 50, false);g.setColor(Color.cyan) ;g.fillOval(xf[i] + 5 , yf[i] + 5 , 30 , 30) ;g.setColor(Color.yellow) ;g.fill3DRect(xf[i] + 15 , yf[i] + 20 , 10 , 40,false) ;}if(opf[i] == 4) {g.setColor(Color.yellow) ;g.fillRect(xf[i] , yf[i] , 40 , 40) ;g.fill3DRect(xf[i]-5, yf[i]-5, 50, 10, false);g.fill3DRect(xf[i]-5, yf[i]+35, 50, 10, false);g.setColor(Color.cyan) ;g.fillOval(xf[i] + 5 , yf[i] + 5 , 30 , 30) ;g.setColor(Color.yellow) ;g.fill3DRect(xf[i] - 20 , yf[i] + 15 , 40 , 10,false) ;}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{opf[i] = 2 ;}}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{opf[i] = 4 ;}}}}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(fenshu==2000){//弹出胜利对话框JOptionPane.showMessageDialog(null,"你赢了!!!","You win! !", JOptionPane.ERROR_MESSAGE);//结束游戏System.exit(0) ;}//重画if(shengming<=0){//弹出胜利对话框JOptionPane.showMessageDialog(null,"你结束了!!!","Game Over !", JOptionPane.ERROR_MESSAGE); //结束游戏System.exit(0) ;}this.repaint() ;}}}package tank4;import java.awt.*;import java.awt.event.*;import java.util.*;import javax.swing.*;public class MyTankGame_4 extends JFrame{MyPanel mp=null;public static void main(String[] args) {MyTankGame_4 mtg=new MyTankGame_4();}public MyTankGame_4(){mp=new MyPanel();//启动mp线程Thread t=new Thread(mp);t.start();this.add(mp);this.addKeyListener(mp);this.setTitle("Hero");this.setSize(400,300);this.setLocation(700,300);this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭格式this.setVisible (true);}}//我的面板class MyPanel extends JPanel implements KeyListener,Runnable{//int a=100,b=100;Hero hero=null; //定义一个我的坦克Vector<EnemyTank> ets=new Vector<EnemyTank>();//定义敌人的坦克Vector<Bomb> bombs=new Vector<Bomb>();//定义一个炸弹集合int enSize=10;//定义三张图片,一颗炸弹!Image imagge1=null; Image imagge2=null; Image imagge3=null;//构造public MyPanel(){hero=new Hero(100, 100);//初始化敌人的坦克for (int i = 0; i < enSize; i++) {//创建敌人坦克的对象EnemyTank et=new EnemyTank((i+1)*50, 100);et.setColor(0);int a=(int)(Math.random()*4);et.setDirect(a);Thread t=new Thread(et);t.start();//给敌人坦克加入子弹Shot s=new Shot(et.getX()+10, et.getY()+10, 2);et.ss.add(s);Thread t2=new Thread(s); t2.start(); ets.add(et);}//初始化图片imagge1=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/3.GIF")); imagge2=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/2.GIF"));imagge3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/1.GIF"));}@Overridepublic void run() {//每隔一百毫秒重绘while(true){try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//判断是否击中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) {this.bitTank(myshot, et);}}}}//重绘this.repaint();}}public void paint(Graphics g){//1、调用父类完成初始化super.paint(g);g.fillRect(0, 0, 400, 300);//画出自己的坦克this.drawTank(hero.getX(), hero.getY(), g, hero.getDirect(),1);//从ss中取出每颗子弹并画出for(int i=0;i<this.hero.ss.size();i++){//取出Shot myshot=hero.ss.get(i);//画出一颗子弹if(myshot!=null&&myshot.islive==true){g.draw3DRect(myshot.x-1 , myshot.y, 1, 1, false);}if(myshot.islive==false){hero.ss.remove(myshot);}}//画出炸弹for(int i=0;i<bombs.size();i++){//取出炸弹Bomb b=bombs.get(i);if(b.life>6) {g.drawImage(imagge1, b.x, b.y, 30, 30, this);}else if(b.life>3){g.drawImage(imagge2, b.x, b.y, 30, 30, this);}else {g.drawImage(imagge3, b.x, b.y, 30, 30, this);}//让b的生命值减小b.lifeDown();//如果炸弹生命值为0,就把炸弹从bombs中去掉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{//如果敌人的子弹死亡后就将其删除et.ss.remove(enemyShot);}}}}}//判断子弹是否击中坦克public void bitTank(Shot s,EnemyTank et){//判断坦克的方向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;//创建一颗炸弹,放入VoctorBomb 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;//创建一颗炸弹,放入VectorBomb b=new Bomb(et.x, et.y);bombs.add(b);} break;}}//画出坦克的函数public void drawTank(int x,int y,Graphics g,int direct,int type){//判断是什么类型的坦克if(type==0) g.setColor(Color.cyan);else if(type==1) g.setColor(Color.yellow);else g.setColor(Color.red);//判断方向switch(direct){//向上case 0://画出坦克(到时再封装成一个函数) //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+4, y+10, 10, 10);//画出线g.setColor(Color.red);g.drawLine(x+10,y-5,x+10,y+15);break;//向右case 1://画出坦克(到时再封装成一个函数)//1.画出上边的矩形g.fill3DRect(x, y, 30, 5,false);//2.画出下边的矩形g.fill3DRect(x, y+15, 30, 5,false);//3.画出中间矩形g.fill3DRect(x+5, y+5, 20, 10,false);//4.画出圆形g.fillOval(x+10, y+5, 10, 10);//画出线g.setColor(Color.red);g.drawLine(x+15,y+10, x+35,y+10); break;//向下case 2://画出坦克(到时再封装成一个函数)//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+4, y+10, 10, 10);//画出线g.setColor(Color.red);g.drawLine(x+10,y+35,x+10,y+15);break;//向右case 3://画出坦克(到时再封装成一个函数)//1.画出上边的矩形g.fill3DRect(x, y, 30, 5,false);//2.画出下边的矩形g.fill3DRect(x, y+15, 30, 5,false);//3.画出中间矩形g.fill3DRect(x+5, y+5, 20, 10,false);//4.画出圆形g.fillOval(x+10, y+5, 10, 10);//画出线g.setColor(Color.red);g.drawLine(x+15,y+10, x-5,y+10);break;}}@Override//键按下处理a 向左s 向下w 向上d 向右public void keyPressed(KeyEvent arg0) {if(arg0.getKeyCode()==KeyEvent.VK_UP) {//设置我的坦克的方向this.hero.setDirect(0);this.hero.moveUp();}else if(arg0.getKeyCode()==KeyEvent.VK_RIGHT){ //设置我的坦克的方向this.hero.setDirect(1);this.hero.moveRigjt();}else if(arg0.getKeyCode()==KeyEvent.VK_DOWN){ //设置我的坦克的方向this.hero.setDirect(2);this.hero.moveDown();}else if(arg0.getKeyCode()==KeyEvent.VK_LEFT){ //设置我的坦克的方向this.hero.setDirect(3);this.hero.moveLife();}else if(arg0.getKeyCode()==KeyEvent.VK_B){this.hero.setSpeed(5); //加速1}else if(arg0.getKeyCode()==KeyEvent.VK_V){this.hero.setSpeed(6); //加速2}else if(arg0.getKeyCode()==KeyEvent.VK_C){this.hero.setSpeed(7); //加速3}if(arg0.getKeyCode()==KeyEvent.VK_SPACE){ //判断是否按J键//开火System.out.println(""+this.hero.ss.size());if(this.hero.ss.size()<5)this.hero.shotEnemy();}//必须重新绘制Panelthis.repaint();}@Overridepublic void keyReleased(KeyEvent arg0) {}@Overridepublic void keyTyped(KeyEvent arg0) {}}//炸弹类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{protected int x;protected int y;protected int direct;protected int speed=5;//是否还活着protected 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();}switch(direct){case 0://上y-=speed; b reak;case 1://右x+=speed; break;case 2://下y+=speed; break;case 3://左x-=speed; b reak;}//子弹何时死亡??//判断该子弹是否碰到边缘if(x<0||x>400||y<0||y>300) {this.islive=false; break;}}}}//坦克类class Tank{protected int x=0;//坦克的横坐标protected int y=0;//坦克的纵坐标//设置坦克的速度protected int speed=3;//坦克方向//0表示向上1表示右2表示下3表示左protected int direct=0;//坦克的颜色protected int color;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 int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public Tank(int x,int y){this.x=x;this.y=y;}}//敌人的坦克,并做成线程class EnemyTank extends Tank implements Runnable{boolean isLive=true;int times=0;//敌人的子弹Vector<Shot> ss=new Vector<Shot>();//敌人添加子弹,应刚刚创建坦克和敌人的坦克子弹死亡后public EnemyTank(int x,int y){super(x,y);}@Overridepublic void run() {while(true){switch(this.direct) {case 0://向上for(int i=0;i<30;i++){if(y>0)y-=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<360)x+=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<240){y+=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){x-=speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;}this.times++;if(times%2==0){if(isLive){if(ss.size()<5){Shot s=null;//没有子弹//添加switch(direct){case 0://创建一颗子弹s=new Shot(x+10, y,0);//把子弹加入向量ss.add(s); break;case 1:s=new Shot(x+30, y+10,1);ss.add(s); break;case 2:s=new Shot(x+10,y+30,2);ss.add(s); break;case 3:s=new Shot(x, y+10,3);ss.add(s); break;}Thread t=new Thread(s);t.start();}}}//让坦克产生一个新的方向this.direct=(int)(Math.random()*4);//判断坦克是否死亡if(this.isLive==false){//让坦克死亡后推出break;}}}}//我的坦克class Hero extends Tank{//子弹Vector<Shot> ss=new Vector<Shot>();Shot s=null;public Hero(int x,int y){super(x,y);}//开火public void shotEnemy(){switch(this.getDirect()){case 0://创建一颗子弹s=new Shot(x+10, y,0);//把子弹加入向量ss.add(s); break;case 1:s=new Shot(x+30, y+10,1);ss.add(s); break;case 2:s=new Shot(x+10,y+30,2);ss.add(s); break;case 3:s=new Shot(x, y+10,3);ss.add(s); break;}Thread t=new Thread(s);t.start();}//坦克向上移动public void moveUp(){if(y>0)y-=speed;}//坦克向右移动public void moveRigjt(){if(x<360)x+=speed;}//坦克向下移动public void moveDown(){if(y<240)y+=speed;}//坦克向左移动public void moveLife(){if(x>0)x-=speed;}}。

相关文档
最新文档