1、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.addK
2、eyListener(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 tankbu
3、llet = 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 = ne
4、w intnum ; int yf = new intnum ; int opf = new intnum ; int dxf = new intnum ; int dyf = new intnum ;int dxf1 = new intnum ; int dyf1 = new intnum ; int dxf2 = new intnum ; int dyf2 = new intnum ; int dxf3 = new intnum ; int dyf3 = new intnum ; int dxf4 = new intnum ; int dyf4 = new intnum ;/构造函数,初始
5、化敌军坦克的位置和状态 MyTank() for (int i = 0; i= 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
6、= dx - tankspeed ; if(x y +8 dxfi - ; break; case 3: yfi+ ; dyfi+ ; for (int s = 0; s= 560) yfi - ; dyfi - ; break; case 4: xfi- ; dxfi- ; for (int s = 0; s0.5) for (int i = 0; i0.5) for (int i = 2; i0.5) for (int i = 4; i0.5) for (int i = 6; i0.5) for (int i = 8; i 0.5 ) if(Math.random() 0.5) opfi
7、= 1 ; else opfi = 2 ; else if(Math.random() 0.5) opfi = 3 ; else opfi = 4 ; if(a % 50 = 11 ) /坦克的随机移动 for (int i = 2; i 0.5 ) if(Math.random() 0.5) opfi = 1 ; else opfi = 2 ; else if(Math.random() 0.5) opfi = 3 ; else opfi = 4 ; if(a % 50 = 21 ) /坦克的随机移动 for (int i = 4; i 0.5 ) if(Math.random() 0.5)
8、 opfi = 1 ; else opfi = 2 ; else if(Math.random() 0.5) opfi = 3 ; else opfi = 4 ; if(a % 50 = 31 ) /坦克的随机移动 for (int i = 6; i 0.5 ) if(Math.random() 0.5) opfi = 1 ; else opfi = 2 ; else if(Math.random() 0.5) opfi = 3 ; else opfi = 4 ; if(a % 50 = 41 ) /坦克的随机移动 for (int i = 8; i 0.5 ) if(Math.random() 0.5) opfi = 1 ; else opfi = 2 ; else if(Math.random() 0.5) opfi = 3 ; else opfi = 4 ; /重画 if(shengming=0) /弹出 player1 胜利对话框 JOptionPane.showMessageDialog(null, “你结束了!“, “Game Over !“, JOptionPane.ERROR_MESSAGE); /结束游戏 System.exit(0) ; this.repaint() ;