VB坦克大战代码
VB坦克大战代码
Private Sub Form_Load() La.Top = 4000La.Left = 3000La.Height = 800La.Width = 900Lb.Top = 4300Lb.Left = 3900Lb.Height = 200Lb.Width = 900Lc.Top = 4300Lc.Left = 4560Lc.Height = 200Lc.Width = 200End SubPrivate Sub Form_keypress(keyascii As Integer)If keyascii = 106 ThenLa.Enabled = FalseLb.Enabled = FalseIf La.Top - Lb.Top = 900 And Lb.Left - La.Left = 300 Then Lc.Top = La.Top - 900Lc.Left = La.Left + 300Lc.Visible = TrueTimer1."Enabled = TrueTimer2."Enabled = FalseTimer3."Enabled = FalseTimer4."Enabled = FalseElseIf La.Left - Lb.Left = 900 And Lb.Top - La.Top = 300 Then Lc.Top = La.Top + 300Lc.Left = La.Left - 900Lc.Visible = TrueTimer1."Enabled = FalseTimer2."Enabled = TrueTimer3."Enabled = FalseTimer4."Enabled = FalseElseIf Lb.Top - La.Top = 900 And Lb.Left - La.Left = 300 Then Lc.Top = La.Top + 1600Lc.Left = La.Left + 300Lc.Visible = TrueTimer1."Enabled = FalseTimer2."Enabled = FalseTimer3."Enabled = TrueTimer4."Enabled = FalseElseIf Lb.Left - La.Left = 900 And Lb.Top - La.Top = 300 Then Lc.Top = La.Top + 300Lc.Left = La.Left + 1600Lc.Visible = TrueTimer1."Enabled = FalseTimer2."Enabled = FalseTimerTimer4."Enabled = TrueEnd IfElseIf keyascii = 119 Then La.Enabled = TrueLb.Enabled = TrueLb.Left = La.Left + 300 Lb.Top = La.Top - 900 La.Height = 900La.Width = 800Lb.Width = 200Lb.Height = 900If Lb.Top <= 0 Then Lb.Enabled = FalseLa.Enabled = FalseElseLa.Top = La.Top - 100 Lb.Top = Lb.Top - 100 End IfElseIf keyascii = 97 ThenLb.Enabled = TrueLb.Left = La.Left - 900 Lb.Top = La.Top + 300 La.Height = 800La.Width = 900Lb.Width = 900Lb.Height = 200If Lb.Left <= 0 Then Lb.Enabled = FalseLa.Enabled = FalseElseLa.Left = La.Left - 100 Lb.Left = Lb.Left - 100 End IfElseIf keyascii = 100 Then La.Enabled = TrueLb.Enabled = TrueLb.Left = La.Left + 900 Lb.Top = La.Top + 300 La.Height = 800La.Width = 900Lb.Width = 900Lb.Height = 200If Lb.Left >= 8700 Then Lb.Enabled = FalseLa.Enabled = FalseElseLa.Left = La.Left + 100 Lb.Left = Lb.Left + 100 End IfElseIf keyascii = 115 Then La.Enabled = TrueLb.Enabled = TrueLb.Left = La.Left + 300 Lb.Top = La.Top + 900 La.Height = 900La.Width = 800Lb.Width = 200Lb.Height = 900If Lb.Top >= 7600 Then Lb.Enabled = FalseLa.Enabled = FalseElseLa.Top = La.Top + 100Lb.Top = Lb.Top + 100End IfElseIf keyascii = 8 ThenEndEnd IfEnd SubPrivate Sub Timer1_Timer()Do While Lc.Top > 0Lc.Top = Lc.Top - 2Lc.Left = Lc.LeftIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top< Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = FalseTimer1."Enabled = FalseEnd SubPrivate Sub Timer2_Timer()Do While Lc.Left > 0Lc.Left = Lc.Left - 2Lc.Top = Lc.TopIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top <Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = FalseTimer2."Enabled = FalseEnd SubPrivate Sub Timer3_Timer()Do While Lc.Top < 8880Lc.Top = Lc.Top + 2Lc.Left = Lc.LeftIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top <Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = FalseTimer3."Enabled = FalseEnd SubPrivate Sub Timer4_Timer()Do While Lc.Left < 9750Lc.Left = Lc.Left + 2Lc.Top = Lc.TopIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top< Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = FalseTimer4."Enabled = FalseEnd Sub。
坦克大战程序代码
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() ;}}}。
Pygame坦克大战游戏开发实战详解代码
Pygame坦克⼤战游戏开发实战详解代码导语哈喽!哈喽——我是⽊⽊⼦今天来升级下之前写的坦克⼤战游戏嘛,哈哈哈其实也不算是修改,就是稍微的调试⼀下!因为之前写的界⾯都是英⽂的,有的⼩伙伴⼉英⽂⼀点⼉都不会的可能看着别扭,今天来⼀款中⽂版的给⼤家嘛!俗话说的好:“⾬露均沾”。
哈哈哈.jpg⼩简介:《坦克⼤战》,1985年由⽇本开发商南梦宫(Namco)开发,是第⼀款可以双打的红⽩机游戏。
当时使⽤的还是⼩霸王。
很多⼩朋友以学习的名义买了以后偷偷打的打游戏还被家长发现了有没得!《坦克⼤战》红⽩机原版共有35关,每⼀关的地形和障碍都不同。
图为原版坦克⼤战最后⼀关,你有没有打通关过?(⼩声bb,我这个游戏⽔平可能达不到!)正⽂1)游戏规则:游戏过程是这样的,玩家操作坦克消灭电脑控制的坦克,并保护⾃⼰基地。
基地图标是⼀只傲娇的张着翅膀的⽼鹰。
⼩时候⾃⼰失⼿把飞鹰轰成烧鸡的惨案经常发⽣。
双打的时候,为了看谁刷得分⾼,都争着打坦克,⼤本营的⽼鹰被烤熟了都不管。
坦克⼤战中的宝贝有战车、星星、时钟等,⼩编当时最喜欢的是时钟,敌不能动我能动的感觉妙极了。
图中的坦克图标吃了是可以加⼀条命的,当时为了抢宝贝都抢先把队友的坦克打晕。
2)环境安装Python3、Pycharm、Pygame、以及⾃带或⾃定义的模块。
pip install +模块名或pip install -i https:///simple/ +模块名3)代码演⽰(之前不是写过的嘛,今天的话就是修改下的,这种⼩游戏代码肯定都很多的,所以这⾥直接贴主程序了。
需要完整的打包好的代码跟素材哪些的话直接滴滴我即可或者看我主页左侧哪⾥有源码基地的哈!)主程序:import pygamefrom pygame.locals import *import sysimport sceneimport bulletimport foodimport tanksimport home# 开始界⾯显⽰def show_start_interface(screen, width, height):tfont = pygame.font.Font('./font/simkai.ttf', width // 4)cfont = pygame.font.Font('./font/simkai.ttf', width // 20)title = tfont.render(u'坦克⼤战', True, (255, 0, 0))content1 = cfont.render(u'按1键进⼊单⼈游戏', True, (0, 244, 222))content2 = cfont.render(u'按2键进⼊双⼈⼈游戏', True, (0, 0, 255))#显⽰字体pygame.font.Font.render(text⽂本, antialias是否抗锯齿, color颜⾊, background=None)trect = title.get_rect()# 默认title左上⾓的坐标是 (0, 0)trect.midtop = (width / 2, height / 5)crect1 = content1.get_rect()crect1.midtop = (width / 2, height / 1.8)crect2 = content2.get_rect()crect2.midtop = (width / 2, height / 1.6)screen.blit(title, trect)screen.blit(content1, crect1)screen.blit(content2, crect2)# 在指定位置绘制指定⽂字对象pygame.display.update()# 更新界⾯while True:for event in pygame.event.get():if event.type == QUIT:sys.exit()elif event.type == pygame.KEYDOWN:if event.key == pygame.K_1:return 1if event.key == pygame.K_2:return 2# 结束界⾯显⽰def show_end_interface(screen, width, height, is_win):bg_img = pygame.image.load("./images/others/background.png") screen.blit(bg_img, (0, 0))if is_win:font = pygame.font.Font('./font/simkai.ttf', width // 10)content = font.render(u'恭喜通关!', True, (255, 0, 0))rect = content.get_rect()rect.midtop = (width / 2, height / 2)screen.blit(content, rect)else:fail_img = pygame.image.load("./images/others/gameover.png") rect = fail_img.get_rect()rect.midtop = (width / 2, height / 2)screen.blit(fail_img, rect)pygame.display.update()while True:for event in pygame.event.get():if event.type == QUIT:sys.exit()# 关卡切换def show_switch_stage(screen, width, height, stage):bg_img = pygame.image.load("./images/others/background.png") screen.blit(bg_img, (0, 0))font = pygame.font.Font('./font/simkai.ttf', width // 10)content = font.render(u'第%d关' % stage, True, (0, 255, 0))rect = content.get_rect()rect.midtop = (width / 2, height / 2)screen.blit(content, rect)pygame.display.update()delay_event = EREVENTpygame.time.set_timer(delay_event, 1000)#定时器延时while True:for event in pygame.event.get():if event.type == QUIT:sys.exit()if event.type == delay_event:returndef main():pygame.init()pygame.mixer.init()screen = pygame.display.set_mode((630, 630))pygame.display.set_caption('坦克⼤战')bg_img = pygame.image.load('./images/others/background.png') # 加载⾳效add_sound = pygame.mixer.Sound("./audios/add.wav")add_sound.set_volume(1)bang_sound = pygame.mixer.Sound("./audios/bang.wav")bang_sound.set_volume(1)blast_sound = pygame.mixer.Sound("./audios/blast.wav")blast_sound.set_volume(1)fire_sound = pygame.mixer.Sound("./audios/fire.wav")fire_sound.set_volume(1)Gunfire_sound = pygame.mixer.Sound("./audios/Gunfire.wav")Gunfire_sound.set_volume(1)hit_sound = pygame.mixer.Sound("./audios/hit.wav")hit_sound.set_volume(1)start_sound = pygame.mixer.Sound("./audios/start.wav")start_sound.set_volume(1)# 开始界⾯num_player = show_start_interface(screen, 630, 630)# 播放游戏开始的⾳乐start_sound.play()# 关卡stage = 0num_stage = 2# 游戏是否结束is_gameover = False# 时钟clock = pygame.time.Clock()# 主循环while not is_gameover:# 关卡stage += 1if stage > num_stage:breakshow_switch_stage(screen, 630, 630, stage)# 该关卡坦克总数量enemytanks_total = min(stage * 18, 80)# 场上存在的敌⽅坦克总数量enemytanks_now = 0# 场上可以存在的敌⽅坦克总数量enemytanks_now_max = min(max(stage * 2, 4), 8)# 精灵组,独⽴运⾏的动画组tanksGroup = pygame.sprite.Group()mytanksGroup = pygame.sprite.Group()enemytanksGroup = pygame.sprite.Group()bulletsGroup = pygame.sprite.Group()mybulletsGroup = pygame.sprite.Group()enemybulletsGroup = pygame.sprite.Group()myfoodsGroup = pygame.sprite.Group()# ⾃定义事件# -⽣成敌⽅坦克事件genEnemyEvent = EREVENTpygame.time.set_timer(genEnemyEvent, 100)# -敌⽅坦克静⽌恢复事件recoverEnemyEvent = EREVENTpygame.time.set_timer(recoverEnemyEvent, 8000)# -我⽅坦克⽆敌恢复事件noprotectMytankEvent = EREVENTpygame.time.set_timer(noprotectMytankEvent, 8000)# 关卡地图map_stage = scene.Map(stage)# 我⽅坦克tank_player1 = tanks.myTank(1)tanksGroup.add(tank_player1)mytanksGroup.add(tank_player1)if num_player > 1:tank_player2 = tanks.myTank(2)tanksGroup.add(tank_player2)mytanksGroup.add(tank_player2)is_switch_tank = Trueplayer1_moving = Falseplayer2_moving = False# 为了轮胎的动画效果time = 0# 敌⽅坦克for i in range(0, 3):if enemytanks_total > 0:enemytank = tanks.enemyTank(i)tanksGroup.add(enemytank)enemytanksGroup.add(enemytank)enemytanks_now += 1enemytanks_total -= 1# ⼤本营myhome = home.Home()# 出场特效appearance_img = pygame.image.load("./images/others/appear.png").convert_alpha() appearances = []appearances.append(appearance_img.subsurface((0, 0), (48, 48)))appearances.append(appearance_img.subsurface((48, 0), (48, 48)))appearances.append(appearance_img.subsurface((96, 0), (48, 48)))# 关卡主循环while True:if is_gameover is True:breakif enemytanks_total < 1 and enemytanks_now < 1:is_gameover = Falsebreakfor event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == genEnemyEvent:if enemytanks_total > 0:if enemytanks_now < enemytanks_now_max:enemytank = tanks.enemyTank()if not pygame.sprite.spritecollide(enemytank, tanksGroup, False, None):tanksGroup.add(enemytank)enemytanksGroup.add(enemytank)enemytanks_now += 1enemytanks_total -= 1if event.type == recoverEnemyEvent:for each in enemytanksGroup:each.can_move = Trueif event.type == noprotectMytankEvent:for each in mytanksGroup:mytanksGroup.protected = False# 检查⽤户键盘操作key_pressed = pygame.key.get_pressed()# 玩家⼀# WSAD -> 上下左右# 空格键射击if key_pressed[pygame.K_w]:tanksGroup.remove(tank_player1)tank_player1.move_up(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome)tanksGroup.add(tank_player1)player1_moving = Trueelif key_pressed[pygame.K_s]:tanksGroup.remove(tank_player1)tank_player1.move_down(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome) tanksGroup.add(tank_player1)player1_moving = Trueelif key_pressed[pygame.K_a]:tanksGroup.remove(tank_player1)tank_player1.move_left(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome)tanksGroup.add(tank_player1)player1_moving = Trueelif key_pressed[pygame.K_d]:tanksGroup.remove(tank_player1)tank_player1.move_right(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome)tanksGroup.add(tank_player1)player1_moving = Trueelif key_pressed[pygame.K_SPACE]:if not tank_player1.bullet.being:fire_sound.play()tank_player1.shoot()# 玩家⼆# ↑↓←→ -> 上下左右# ⼩键盘0键射击if num_player > 1:if key_pressed[pygame.K_UP]:tanksGroup.remove(tank_player2)tank_player2.move_up(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome) tanksGroup.add(tank_player2)player2_moving = Trueelif key_pressed[pygame.K_DOWN]:tanksGroup.remove(tank_player2)tank_player2.move_down(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome) tanksGroup.add(tank_player2)player2_moving = Trueelif key_pressed[pygame.K_LEFT]:tanksGroup.remove(tank_player2)tank_player2.move_left(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome) tanksGroup.add(tank_player2)player2_moving = Trueelif key_pressed[pygame.K_RIGHT]:tanksGroup.remove(tank_player2)tank_player2.move_right(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome) tanksGroup.add(tank_player2)player2_moving = Trueelif key_pressed[pygame.K_KP0]:if not tank_player2.bullet.being:fire_sound.play()tank_player2.shoot()# 背景screen.blit(bg_img, (0, 0))# ⽯头墙for each in map_stage.brickGroup:screen.blit(each.brick, each.rect)# 钢墙for each in map_stage.ironGroup:screen.blit(each.iron, each.rect)# 冰for each in map_stage.iceGroup:screen.blit(each.ice, each.rect)# 河流for each in map_stage.riverGroup:screen.blit(each.river, each.rect)# 树for each in map_stage.treeGroup:screen.blit(each.tree, each.rect)time += 1if time == 5:time = 0is_switch_tank = not is_switch_tank# 我⽅坦克if tank_player1 in mytanksGroup:if is_switch_tank and player1_moving:screen.blit(tank_player1.tank_0, (tank_player1.rect.left, tank_player1.rect.top))player1_moving = Falseelse:screen.blit(tank_player1.tank_1, (tank_player1.rect.left, tank_player1.rect.top))if tank_player1.protected:screen.blit(tank_player1.protected_mask1, (tank_player1.rect.left, tank_player1.rect.top))if num_player > 1:if tank_player2 in mytanksGroup:if is_switch_tank and player2_moving:screen.blit(tank_player2.tank_0, (tank_player2.rect.left, tank_player2.rect.top))player1_moving = Falseelse:screen.blit(tank_player2.tank_1, (tank_player2.rect.left, tank_player2.rect.top))if tank_player2.protected:screen.blit(tank_player1.protected_mask1, (tank_player2.rect.left, tank_player2.rect.top)) # 敌⽅坦克for each in enemytanksGroup:# 出⽣特效if each.born:if each.times > 0:each.times -= 1if each.times <= 10:screen.blit(appearances[2], (3 + each.x * 12 * 24, 3))elif each.times <= 20:screen.blit(appearances[1], (3 + each.x * 12 * 24, 3))elif each.times <= 30:screen.blit(appearances[0], (3 + each.x * 12 * 24, 3))elif each.times <= 40:screen.blit(appearances[2], (3 + each.x * 12 * 24, 3))elif each.times <= 50:screen.blit(appearances[1], (3 + each.x * 12 * 24, 3))elif each.times <= 60:screen.blit(appearances[0], (3 + each.x * 12 * 24, 3))elif each.times <= 70:screen.blit(appearances[2], (3 + each.x * 12 * 24, 3))elif each.times <= 80:screen.blit(appearances[1], (3 + each.x * 12 * 24, 3))elif each.times <= 90:screen.blit(appearances[0], (3 + each.x * 12 * 24, 3))else:each.born = Falseelse:if is_switch_tank:screen.blit(each.tank_0, (each.rect.left, each.rect.top))else:screen.blit(each.tank_1, (each.rect.left, each.rect.top))if each.can_move:tanksGroup.remove(each)each.move(tanksGroup, map_stage.brickGroup, map_stage.ironGroup, myhome)tanksGroup.add(each)# 我⽅⼦弹for tank_player in mytanksGroup:if tank_player.bullet.being:tank_player.bullet.move()screen.blit(tank_player.bullet.bullet, tank_player.bullet.rect)# ⼦弹碰撞敌⽅⼦弹for each in enemybulletsGroup:if each.being:if pygame.sprite.collide_rect(tank_player.bullet, each):tank_player.bullet.being = Falseeach.being = FalseenemybulletsGroup.remove(each)breakelse:enemybulletsGroup.remove(each)# ⼦弹碰撞敌⽅坦克for each in enemytanksGroup:if each.being:if pygame.sprite.collide_rect(tank_player.bullet, each):if each.is_red == True:myfood = food.Food()myfood.generate()myfoodsGroup.add(myfood)each.is_red = Falseeach.blood -= 1each.color -= 1if each.blood < 0:bang_sound.play()each.being = FalseenemytanksGroup.remove(each)enemytanks_now -= 1tanksGroup.remove(each)else:each.reload()tank_player.bullet.being = Falsebreakelse:enemytanksGroup.remove(each)tanksGroup.remove(each)# ⼦弹碰撞⽯头墙if pygame.sprite.spritecollide(tank_player.bullet, map_stage.brickGroup, True, None): tank_player.bullet.being = False# ⼦弹碰钢墙if tank_player.bullet.stronger:if pygame.sprite.spritecollide(tank_player.bullet, map_stage.ironGroup, True, None): tank_player.bullet.being = Falseelse:if pygame.sprite.spritecollide(tank_player.bullet, map_stage.ironGroup, False, None): tank_player.bullet.being = False# ⼦弹碰⼤本营if pygame.sprite.collide_rect(tank_player.bullet, myhome):tank_player.bullet.being = Falsemyhome.set_dead()is_gameover = True# 敌⽅⼦弹for each in enemytanksGroup:if each.being:if each.can_move and not each.bullet.being:enemybulletsGroup.remove(each.bullet)each.shoot()enemybulletsGroup.add(each.bullet)if not each.born:if each.bullet.being:each.bullet.move()screen.blit(each.bullet.bullet, each.bullet.rect)# ⼦弹碰撞我⽅坦克for tank_player in mytanksGroup:if pygame.sprite.collide_rect(each.bullet, tank_player):if not tank_player.protected:bang_sound.play()tank_player.life -= 1if tank_player.life < 0:mytanksGroup.remove(tank_player)tanksGroup.remove(tank_player)if len(mytanksGroup) < 1:is_gameover = Trueelse:tank_player.reset()each.bullet.being = FalseenemybulletsGroup.remove(each.bullet)break# ⼦弹碰撞⽯头墙if pygame.sprite.spritecollide(each.bullet, map_stage.brickGroup, True, None): each.bullet.being = FalseenemybulletsGroup.remove(each.bullet)# ⼦弹碰钢墙if each.bullet.stronger:if pygame.sprite.spritecollide(each.bullet, map_stage.ironGroup, True, None): each.bullet.being = Falseelse:if pygame.sprite.spritecollide(each.bullet, map_stage.ironGroup, False, None): each.bullet.being = False# ⼦弹碰⼤本营if pygame.sprite.collide_rect(each.bullet, myhome):each.bullet.being = Falsemyhome.set_dead()is_gameover = Trueelse:enemytanksGroup.remove(each)tanksGroup.remove(each)# 家screen.blit(myhome.home, myhome.rect)# ⾷物for myfood in myfoodsGroup:if myfood.being and myfood.time > 0:screen.blit(myfood.food, myfood.rect)myfood.time -= 1for tank_player in mytanksGroup:if pygame.sprite.collide_rect(tank_player, myfood):# 消灭当前所有敌⼈if myfood.kind == 0:for _ in enemytanksGroup:bang_sound.play()enemytanksGroup = pygame.sprite.Group()enemytanks_total -= enemytanks_nowenemytanks_now = 0# 敌⼈静⽌if myfood.kind == 1:for each in enemytanksGroup:each.can_move = False# ⼦弹增强if myfood.kind == 2:add_sound.play()tank_player.bullet.stronger = True# 使得⼤本营的墙变为钢板if myfood.kind == 3:map_stage.protect_home()# 坦克获得⼀段时间的保护罩if myfood.kind == 4:add_sound.play()for tank_player in mytanksGroup:tank_player.protected = True# 坦克升级if myfood.kind == 5:add_sound.play()tank_player.up_level()# 坦克⽣命+1if myfood.kind == 6:add_sound.play()tank_player.life += 1myfood.being = FalsemyfoodsGroup.remove(myfood)breakelse:myfood.being = FalsemyfoodsGroup.remove(myfood)pygame.display.flip()clock.tick(60)if not is_gameover:show_end_interface(screen, 630, 630, True)else:show_end_interface(screen, 630, 630, False)if __name__ == '__main__':main()4)效果展⽰视频展⽰效果——【Pygame实战】经典的坦克⼤战游戏,勾起童年⽆限回忆!静态截图效果——游戏界⾯:第⼀关单⼈游戏:双⼈第⼀关游戏:总结好啦!中⽂版的坦克⼤战都看的懂了哈,想咋玩⼉咋玩⼉。
C语言完整游戏项目坦克大战详细代码
C语⾔完整游戏项⽬坦克⼤战详细代码话不多说我们今天就来创造出属于我们⾃⼰的《坦克⼤战》,GOGOGO直接开始吧这次的源码⽐较详细,我分了好⼏个cpp⽂件,思路更加的清晰,请耐⼼⽤⼼的观看⾸先就是我们载⼊图⽚的函数tupian.cpp# include "tanke.h"障碍物void LaoWang(int * tilex, int * tiley){IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32 , 32 , &img, 32 * 5, 0 );}void tileHong(int * tilex, int * tiley){IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32, 32, &img, 32 * 0, 0 );return;}void tileLv(int * tilex, int * tiley){IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32, 32, &img, 32 * 2, 0 );return;}void tileBai(int * tilex, int * tiley){IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32, 32, &img, 32 * 1, 0 );return;}IMAGE img;loadimage(&img, _T("res\\tile.bmp"));putimage(*tilex, *tiley, 32, 32, &img, 32 * 3, 0 ); }//物品void FaZhang(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\fazhang.jpg"));putimage(*wupinx, *wupiny, 24, 24, &img, 0, 0 ); }void ShouQiang(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\shouqiang.jpg"));putimage(*wupinx, *wupiny, 24, 24, &img, 0, 0 ); }void ShangDian(int *wupinx, int *wupiny){IMAGE img;loadimage(&img,_T("res\\shangdian.jpg"));putimage(*wupinx, *wupiny, 32, 32, &img, 0, 0 ); }void YaoShui(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\yaoshui.jpg"));putimage(*wupinx, *wupiny, 28, 28, &img, 0, 0 ); }void DunPai(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\dunpai.jpg"));putimage(*wupinx, *wupiny, 28, 28, &img, 0, 0 ); }void XieZi(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\ iezi.jpg"));putimage(*wupinx, *wupiny, 28, 28, &img, 0, 0 ); }void Boss(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\boss.jpg"));putimage(*wupinx, *wupiny, 32, 32, &img, 0, 0 ); }void BigBoss(int *wupinx, int *wupiny){IMAGE img;loadimage(&img, _T("res\\bigboss.jpg"));putimage(*wupinx, *wupiny, 32, 32, &img, 0, 0 ); }接下来是初始化的函数waiyuan.cpp# include "tanke.h"{setcolor(GREEN);settextstyle(0, 0, ("宋体"));char c2[20] = "⾃⼰⽣命值:";outtextxy(0, 20, c2);char c3[10] ;sprintf(c3, _T("%.1f"), 100* (60 - *j) / 60.0);outtextxy(90, 20, c3);}void DShengMing(int * d,int *k){setcolor(GREEN);settextstyle(0, 0, ("宋体"));char c2[20] = "敌⼈⽣命值:";outtextxy(0, 0, c2);char c3[10] ;sprintf(c3, _T("%.1f"), 100* (60 - *d) / 60.0);outtextxy(90, 0, c3);char c4[40] = "恭喜~! 现在起⾦币到2200有惊喜!";//胜利 if ( *k >= 8000 ){setcolor(YELLOW);settextstyle(30, 0, ("宋体"));outtextxy(150, 0, c4);}}void Gold(int * gold){setcolor(GREEN);settextstyle(0, 0, ("宋体"));char c2[20] = "⾦币:";outtextxy(0, 40, c2);char c3[10] ;sprintf(c3, _T("%d"), *gold);outtextxy(40, 40, c3);}void start(void){initgraph(200, 130);TCHAR s1[10]="坦克⼤战";TCHAR s2[30]="按A 开始游戏按B 退出游戏";TCHAR s3[30]="按W S A D控制⽅向";TCHAR s4[20]="按J 发射⼦弹";TCHAR s5[20]="按C 看攻略";outtextxy(70, 0, s1);outtextxy(0, 110, s2);outtextxy(60, 90, s5);outtextxy(55, 30, s4);outtextxy(35, 60, s3);while (true){Sleep(500);if (GetAsyncKeyState('A')){BeginBatchDraw();closegraph();initgraph(640, 480);Sleep(200);Quit();return ;}if (GetAsyncKeyState('C'))GongLue();}}}void GongLue(void){initgraph(450, 300);TCHAR s1[20]="游戏攻略:";TCHAR s2[50]="再打坦克之前先吃法杖打掉⽩⾊砖块,";TCHAR s3[50]="这样敌坦克打⽩⾊就不能回⾎了,boss更应如此。
坦克大战,及源代码
采用双向循环链表作太极形式旋转的图案,图案的变化采用刷新屏幕的方法做到。
首先,建立一个二维字符数组,保存图形数据,然后通过更改该二维字符数组和清屏,再显示,做到图像的变化。
用它提示坦克大战游戏的操作方法。
再显示问题解决后,通过无回显读取函数getch();和输入流检查函数kbhit();读取输入的方向键或回车键进入下一页面。
用同样的方法,读取方向键和回车键,更改内部图案方法,使用户选择关:第一关:仅有4个坦克同时作战,总数为30个!第二关:仅有5个坦克同时作战,总数为40个!第三关:有6个坦克同时作战,总数为50个!第四关:有7个坦克同时作战,总数为60个!第五关:有8个坦克同时作战,总数为70个!选择关卡后,进入下一页面:进行相关提示。
最后进入游戏界面。
也可以通过按左方向键返回上一级重新选择!!!第一关到第三关:都是宽80,高42的。
最后两关:都是宽160,高42的。
右击标题栏选择属性,进入设置。
接着就是进入最重要的坦克大战游戏了:这时采用的就不是刷新屏幕能解决的问题了。
由于界面太大,不能刷新屏幕,仅能用光标移动函数来更改图像。
光标移动函数为gotoxy(int ,int );读者自己查看定义。
采用同样输入流读取方法。
接着是游戏规则,操作者用W.w.A.a.S.s.D.d移动坦克,空格是停下。
用方向键改变炮筒的方向,回车键是开火。
但当自己的炮弹还在运行时,不得开火!!!用链表保存每一辆坦克(包括主坦克)的数据。
电脑控制的坦克,被控制者的坦克炮弹击中,就会发生爆炸,并死亡。
当界面上的所有坦克小于特定值时,如果内部还有未出现的坦克,就会在上方的随机位置,产生新坦克。
如果操作者的坦克被击中,它的HP(我称为生命值)就会减一点。
刚开始游戏时的HP=5;但升级进入下一关时保留上一局的最后分数和HP。
不会重置。
但游戏中有补血包,可以补充生命值(HP)补血包每90秒出现一次,出现的时间长为60秒。
如果在这期间操作者的坦克运动到它的位置,补血包将给操作者的坦克补血。
坦克大战游戏编程实现
坦克大战游戏编程实现游戏编程实现坦克大战坦克大战是一款经典的电子游戏,在游戏中,玩家将控制一个坦克,通过操作坦克的移动和攻击,与其他玩家或电脑进行战斗。
本文将介绍如何使用编程语言实现坦克大战游戏。
设计思路在实现坦克大战游戏之前,首先需要明确游戏的基本要素和规则。
玩家将操作一个坦克,通过键盘或操纵杆控制坦克的移动和攻击。
游戏画面由地图、坦克、子弹等元素构成。
坦克可以向前、向后、向左、向右移动,可以发射子弹进行攻击。
玩家需要躲避敌方坦克的攻击,同时尽可能击败敌方坦克。
编程实现坦克的移动和攻击可以通过编程语言来实现。
以下是使用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的主窗口,并在窗口中添加了一个玩家坦克、敌方坦克和子弹的列表。
VB坦克大战设计报告
坦克大战设计报告学院班级学号姓名成绩一、设计思路1.要达到的目的培养学生综合利用VB语言进行程序设计的能力,主要是培养学生的时钟控制和综合编程能力。
⏹要求使用面向对象和结构化程序设计的编程思路⏹能通过键盘W(上)、S(下)、A(左)、D(右)移动坦克。
⏹可以通过上述按键随时改变坦克的方向。
⏹炮身和炮筒分别为标签控件◆当坦克移动到窗体边框时停止前进,但能改变方向。
◆按键J时可以按炮筒方向发射炮弹(炮弹为标签控件)。
二、部分程序关键源代码及注释1Private Sub Form_KeyPress(KeyAscii As Integer)If KeyAscii = 106 ThenLa.Enabled = FalseLb.Enabled = False (当发炮弹时坦克不能再移动以免跑到炮弹前)2If La.Top - Lb.Top = 800 And Lb.Left - La.Left = 300 ThenLc.Top = La.Top - 800Lc.Left = La.Left + 300Lc.V isible = TrueTimer1.Enabled = TrueTimer2.Enabled = False (只运行一个时钟)Timer3.Enabled = FalseTimer4.Enabled = False3 ElseIf KeyAscii = 119 ThenLa.Enabled = TrueLb.Enabled = TrueLb.Left = La.Left + 300Lb.Top = La.Top – 800 (方向键控制方向和移动)Lb.Width = 200Lb.Height = 800If Lb.Top = 0 ThenLb.Top = 0ElseLa.Top = La.Top - 200Lb.Top = Lb.Top - 200End IfSub4Private Sub Form_Load()Lc.V isible = False (开始炮弹不可见)End Sub5Private Sub Timer1_Timer()If Lc.Top < 0 ThenLc.V isible = FalseTimer1.Enabled = False (当到达边界时时钟控件停止运行,炮弹消失)Else 'If Lc.Top <= 7600 ThenLc.Top = Lc.Top - 200Lc.Left = Lc.LeftEnd IfEnd Sub三、设计方案的完善及目前存在的问题1.设计方案要完善的地方要完善的地方是创新,做的时候感觉要尽快完成基本要求,没太考虑创新,做完之后感觉创新与基本要求的程序代码很矛盾,余地太少,还有要参加其他考试,时间也不允许,粗劣之处可能会很多。
VB坦克大战设计报告
坦克大战设计报告一、设计思路1.要达到的目的培养学生综合利用VB语言进行程序设计的能力,主要是培养学生的时钟控制和综合编程能力。
⏹要求使用面向对象和结构化程序设计的编程思路⏹能通过键盘W(上)、S(下)、A(左)、D(右)移动坦克。
⏹可以通过上述按键随时改变坦克的方向。
⏹炮身和炮筒分别为标签控件◆当坦克移动到窗体边框时停止前进,但能改变方向。
按键J时可以按炮筒方向发射炮弹(炮弹为标签控件)。
2.关键问题的解决①坦克由两个控件构成label1作为坦克的主体部分,label2作为炮管。
②坦克的移动通过窗体的keypress事件接受键盘按键,w键控制坦克向上,s键控制坦克向下,a键控制坦克向左,d键控制坦克向右。
炮弹的发射由键盘事件控制,单击j键发射炮弹。
利用timer控件控制炮弹延直线移动(改变炮弹的top和left属性),当炮弹击中边缘后消失。
③每当利用keypress事件触发坦克的发炮,首先判断是否炮弹在运行当中,如果运行当中则不进行响应。
炮弹的运动是由timer控件控制,发炮时启动timer事件。
二、程序流程图三、部分程序关键源代码及注释1 If La.Top - Lb.Top = 900 And Lb.Left - La.Left = 300 ThenLc.Top = La.Top - 900Lc.Left = La.Left + 300Lc.Visible = TrueTimer1.Enabled = True (向某一方向发炮时只运行一个时钟)Timer2.Enabled = FalseTimer3.Enabled = FalseTimer4.Enabled = False2 ElseIf keyascii = 97 ThenLa.Enabled = TrueLb.Enabled = TrueLb.Left = La.Left - 900Lb.Top = La.Top + 300 (方向键控制转向和移动)La.Height = 800La.Width = 900 (转向时Lable重新定位)Lb.Width = 900Lb.Height = 200If Lb.Left <= 0 ThenLb.Enabled = FalseLa.Enabled = FalseElseLa.Left = La.Left – 100 (炮筒和炮身相对位置不变的移动)Lb.Left = Lb.Left - 100End If3 Private Sub Timer2_Timer()Do While Lc.Left > 0Lc.Left = Lc.Left - 2Lc.Top = Lc.TopIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top < Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = False (当炮弹到达边界时时钟停止运行,炮弹消失)Timer2.Enabled = FalseEnd Sub四、设计方案的完善及目前存在的问题1.设计方案要完善的地方①×××××②×××××③×××××。
坦克大战源码
坦克大战源码根据韩顺平老师视频所作/**坦克大战* 防重叠*/package ;import .*;import .*;import class MyTankGame5 extends JFrame implements ActionListener{quals("newgame")){quals("exit")){quals("saveExit")){quals("continue")){etImage"/"));image2=().getImage"/"));image3=().getImage"/"));etNodesAndEnemy();etSpeed();etSpeed(0);etSpeed();etSpeed(0);边的矩形(x, y, 5, 30,false);边的矩形(x, y, 5, 30,false);etSpeed();etSpeed(0);etSpeed(esp1);;import Node{int x;int y;int direct;public Node(int x,int y,int direct){=x;=y;=direct;}}//记录坦克信息的类class Recorder{//记录敌人和我的坦克数量private static int enlife=20;private static int mylife=10;private static int deadenemy=0;private static FileWriter fw=null;private static BufferedWriter bw=null;private static FileReader fr=null;private static BufferedReader br=null;private static Vector<EnemyTank> ets=new Vector<EnemyTank>();//从文件恢复记录static Vector<Node> nodes=new Vector<Node>();//完成读取public Vector<Node> getNodesAndEnemy(){try {//创建fr=new FileReader("d:\\chen\\");br=new BufferedReader(fr);String n="";//先读取第一行n=();deadenemy=(n);//用split分割从第二行开始取while((n=())!=null){//字符串str中从第一个字符起,//每遇到一个空格则切割为一个元素,//放入[]xyd数组中String []xyd=(" ");//这里的空格数与keepRecAndEnemyTank()中//写入(String record=+" "++" "+;)//!!!!!!!!!!!!!! //的空格数要对应,否则会报错!Node node1=new Node(xyd[0]),(xyd[1]),(xyd[2]));(node1);}} catch (IOException e) {// TODO Auto-generated catch block();}finally{//关闭文件//谁先开,谁后关!try {();();} catch (IOException e) {// TODO Auto-generated catch block();}}return nodes;}public static Vector<EnemyTank> getEts() {return ets;}public static void setEts(Vector<EnemyTank> ets) { = ets;}//保存击毁敌人的数目和敌人坐标,存盘退出public static void keepRecAndEnemyTank(){try {//创建fw=new FileWriter("d:\\chen\\");bw=new BufferedWriter(fw);(deadenemy+"\r\n");//保存当前敌人的数目和坐标for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//保存活的if{String record=+" "++" "+;//写入(record+"\r\n");}}} catch (IOException e) {// TODO Auto-generated catch block();}finally{//关闭文件//谁先开,谁后关!try {();();} catch (IOException e) {// TODO Auto-generated catch block();}}}//保存击毁的敌人数目public static void keepRecording(){try {//创建fw=new FileWriter("d:\\chen\\");bw=new BufferedWriter(fw);(deadenemy+"\r\n");} catch (IOException e) {// TODO Auto-generated catch block();}finally{//关闭文件//谁先开,谁后关!try {();();} catch (IOException e) {// TODO Auto-generated catch block();}}}//读取出上一局击毁的敌人数目public static void getRecording(){try {//创建fr=new FileReader("d:\\chen\\");br=new BufferedReader(fr);String n=();deadenemy=(n);} catch (IOException e) {// TODO Auto-generated catch block();}finally{//关闭文件//谁先开,谁后关!try {();();} catch (IOException e) {// TODO Auto-generated catch block();}}}public static int getEnlife() {return enlife;}public static void setEnlife(int enlife) {= enlife;}public static int getMylife() {return mylife;}public static void setMylife(int mylife) {= mylife;}//减少数量public static void reduceMylife() {;}public static void reduceEnlife() {;}public static void deadenemy() {++;public static int getDeadenemy() {return deadenemy;}}class Tank{//坦克的横坐标int x=0;//纵坐标int y=0;//暂停速度int tempspeed;public int getTempspeed() {return tempspeed;}public void setTempspeed(int tempspeed) { = tempspeed;}//颜色int color;boolean isLive=true;public boolean isLive() {return isLive;}public void setLive(boolean isLive) {= isLive;}public int getColor() {return color;}public void setColor(int color) {= color;public int getX() {return x;}public void setX(int x) {= x;}public int getY() {return y;}public void setY(int y) {= y;}public Tank (int x,int y){=x;=y;}//坦克方向//0上,1右,2下,3左int direct=0;public int getDirect() {return direct;}public void setDirect(int direct) {= direct;}//坦克的速度int speed=3;public int getSpeed() {return speed;}public void setSpeed(int speed) {= speed;}}//敌方坦克class EnemyTank extends Tank implements Runnable{//设敌人可以复活10次static int newlife=10;//计数器static int counter=0;//让坦克随机产生步数//每次走多少步int steps=(int)()*50+10);int sleeptime=200; //睡眠时间//定义一个向量存放敌人子弹Vector<Shot> ss1=new Vector<Shot>();//在敌人创建和子弹死亡后在创建子弹public EnemyTank(int x,int y){super(x,y);}//定义一个向量,访问MyPanel的所有敌人坦克Vector<EnemyTank> ets=new Vector<EnemyTank>();//得到MyPanel的所有敌人坦克public void setEts(Vector<EnemyTank> vv){=vv;}//判断是否撞到了别的敌人坦克public boolean isTouchotherEnemy(){boolean b=false;//判断switch{case 0://向上//取出敌人所有坦克for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if==0||==2){if>=&&<=+20&&>=&&<=+30){return true;}if+20>=&&+20<=+20&&>=&&<=+30){return true;}}//如果敌人方向是向左或者向右if==1||==3){if>=&&<=+30&&>=&&<=+20){return true;}if+20>=&&+20<=+30&&>=&&<=+20){return true;}}}}break;case 1://向右//取出敌人所有坦克for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if==0||==2){if+30>=&&+30<=+20&&>=&&<=+30){return true;}if+30>=&&+30<=+20&&+20>=&&+20<=+30){return true;}}//如果敌人方向是向左或者向右if==1||==3){if>=&&<=+30&&>=&&<=+20){return true;}if+30>=&&+30<=+30&&+20>=&&+20<=+20){return true;}}}}break;case 2://向下//取出敌人所有坦克for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if==0||==2){if>=&&<=+20&&+30>=&&+30<=+30){return true;}if+20>=&&+20<=+20&&+30>=&&+30<=+30){return true;}}//如果敌人方向是向左或者向右if==1||==3){if>=&&<=+30&&+30>=&&+30<=+20){return true;}if+20>=&&+20<=+30&&+30>=&&+30<=+20){return true;}}}}break;case 3://向左//取出敌人所有坦克for(int i=0;i<();i++){//取出第一个坦克EnemyTank et=(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if==0||==2){if>=&&<=+20&&>=&&<=+30){return true;}if>=&&<=+20&&+20>=&&+20<=+30){return true;}}//如果敌人方向是向左或者向右if==1||==3){if>=&&<=+30&&>=&&<=+20){return true;}if>=&&<=+30&&+20>=&&+20<=+20){return true;}}}}break;}return b;}public void run() {// TODO Auto-generated method stubwhile(true){switch{case 0://继续让他再走几步for(int i=0;i<steps;i++){if(y>0&&!isTouchotherEnemy()){y-=speed;}// //撞到墙或者队友就转弯||isTouchotherEnemy()// else if(y<=0)// {// //让坦克变向// =(direct+1)%4;// }try {(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch block();}}break;case 1://继续让他再走几步for(int i=0;i<steps;i++){if(x<&&!isTouchotherEnemy()){x+=speed;}// //撞到墙或者队友就转弯// else if(x>=// {// //让坦克变向// =(direct+1)%4;// }try {(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch block();}}break;case 2://继续让他再走几步for(int i=0;i<steps;i++){if(y<&&!isTouchotherEnemy()){y+=speed;}//撞到墙或者队友就转弯// else if(y>=// {// //让坦克变向// =(direct+1)%4;// }try {(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch block();}}break;case 3://继续让他再走几步for(int i=0;i<steps;i++){if(x>0&&!isTouchotherEnemy()){x-=speed;}// //撞到墙或者队友就转弯// else if(x<=0)// {// //让坦克变向// =(direct+1)%4;// }try {(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch block();}}break;}//判断是否死亡,是否暂停if==false||=={//退出线程break;}//让坦克随机产生方向=(int)()*4);}}}//我的坦克class Hero extends Tank{//设我可以复活3次static int newlife=10;//计数器static int counter=0;Vector<Shot> ss=new Vector<Shot>();//子弹Shot s=null;public Hero(int x,int y){super(x,y);}//开火public void shotEnemy(){switch{case 0:s=new Shot(x+9,y-10,0);(s);break;case 1:s=new Shot(x+35,y+9,1);(s);break;case 2:s=new Shot(x+10,y+35,2);(s);break;case 3:s=new Shot(x-9,y+9,3);(s);break;}//创建线程对象Thread t1=new Thread(s);//启动();}//坦克向上移动public void moveUp(){if(y>0&&{y-=speed;}}//坦克向右移动public void moveRight(){if(x<&&{x+=speed;}}//坦克向下移动public void moveDown(){if(y<&&{y+=speed;}}//坦克向左移动public void moveLeft(){if(x>0&&{x-=speed;}}}//炸弹类class Bomb{//定义炸弹坐标int x,y;//炸弹生命int life=3;boolean isLive=true;public Bomb(int x,int y){=x;=y;}//减少生命值public void lifeDown(){if(life>0){life--;}else{=false;}}}//子弹类class Shot implements Runnable{//坐标int x;int y;int direct;int speed=5;public int getDirect() {return direct;}public void setDirect(int direct) {= direct;}public int getSpeed() {return speed;}public void setSpeed(int speed) {= speed;}//是否还活着boolean isLive=true;public Shot(int x,int y,int direct){=x;=y;=direct;}public void run(){while(true){try {(50);} catch (InterruptedException e) {// TODO Auto-generated catch block();}switch(direct){case 0://上方向y-=speed;break;case 1://向右x+=speed;break;case 2://向下y+=speed;break;case 3://向左x-=speed;break;}//"子弹坐标:"+"("+x+","+y+")");//子弹何时死亡?//判断该子弹是否碰到窗口边缘if(x<0||x>||y<0||y>{=false;break;}}}}//播放声音的类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 = (soundFile);} catch (Exception e1) {();return;}AudioFormat format = ();SourceDataLine auline = null;info = new , format);try {auline = (SourceDataLine) (info);(format);} catch (Exception e) {();return;}();int nBytesRead = 0;//这是缓冲byte[] abData = new byte[512];try {while (nBytesRead != -1){nBytesRead = (abData, 0, ;if (nBytesRead >= 0)(abData, 0, nBytesRead);}} catch (IOException e) {();return;} finally {();();}}}。
坦克大战的游戏代码
using System;using System.Collections.Generic;using System.Text;using System.Drawing; //addusing System.Collections;//addnamespace 坦克{class Tank{private int width; //坦克的宽度private int height; //坦克的高度private int top; //坦克位置的纵坐标private int left; //坦克位置的横坐标private int type; //坦克的类型(2---5敌方,6己方)private int direct; //0--上,1--下,2--左,3--右public ArrayList bList=new ArrayList();//子弹序列public Tank(int tank_type)//构造函数{Random r = new Random();this.direct = r.Next(0, 4);//产生0—3的数this.width = 32;this.height = 32;this.left = r.Next(0, 1);//产生0—9的数this.top = r.Next(0, 1);//产生0—9的数this.type = tank_type;}public int Top//Top属性{get{return top;}set{if (top >= 0 && top <= 9){top = value;//if (top == 0 || top == 9) newDirect();}}}public int Type//坦克的类型属性{get{return type;}set{if (top >= 1 && top <= 5){type = value;}}}public int Left//Left属性{get{return left;}set{if (left >= 0 && left <= 9){left = value;//if (left == 0 || left == 9) newDirect();}}}public int Direct//Direct属性(坦克方向){get{return direct;}set{direct = value;}}public void newDirect()//改变方向{Random r = new Random();int new_Direct=r.Next(0, 4);//产生0—3的数while(this.direct == new_Direct)new_Direct = r.Next(0, 4);//产生0—3的数this.direct = new_Direct;}public void Draw(Graphics g,int type)//根据坦克类型选择不同图片{Image tankImage = Image.FromFile("BMP/ETANK1.BMP");if (type == 2) tankImage = Image.FromFile("BMP/ETANK2.BMP");if (type == 3) tankImage = Image.FromFile("BMP/ETANK3.BMP");if (type == 4) tankImage = Image.FromFile("BMP/ETANK4.BMP");if (type == 5) tankImage = Image.FromFile("BMP/ETANK1.BMP");if (type == 6) tankImage = Image.FromFile("BMP/MYTANK.BMP");//得到绘制这个坦克图形的在游戏面板中的矩形区域Rectangle destRect = new Rectangle(this.left * width, this.top * height, width,height);Rectangle srcRect = new Rectangle(direct * width, 0, width, height);g.DrawImage(tankImage,destRect,srcRect,GraphicsUnit.Pixel );}public void Explore(Graphics g)//坦克爆炸动画{//得到绘制这个坦克图形的在游戏面板中的矩形区域Rectangle destRect = new Rectangle(this.left * width, this.top * height, width, height);Rectangle srcRect = new Rectangle(0, 0, width, height);Image tankImage = Image.FromFile("BMP/explode1.bmp");g.DrawImage(tankImage, destRect, srcRect, GraphicsUnit.Pixel);tankImage = Image.FromFile("BMP/explode1.bmp");g.DrawImage(tankImage, destRect, srcRect, GraphicsUnit.Pixel);tankImage = Image.FromFile("BMP/explode2.bmp");g.DrawImage(tankImage, destRect, srcRect, GraphicsUnit.Pixel);PlaySound.Play("Sound/Explode.wav");}public void fire(){bullet b = new bullet(this.type);//根据坦克产生不同子弹b.Direct = this.Direct;//坦克的朝向b.Top = this.Top;b.Left = this.Left;//b.move();bList.Add(b);if(this.type==6) PlaySound.Play("Sound/Shoot.wav");//己方发射出声}public void MoveBullet(ref int [,]Map){for (int i = bList.Count-1; i>=0; i--)//遍历子弹序列//for (int i = 0; i < bList.Count;i++ ){bullet t = ((bullet)bList[i]);//移动以前if (t.Left < 0 || t.Left > 9 || t.Top < 0 || t.Top > 9)//超出边界{bList.RemoveAt(i); continue;//删除此颗子弹}if (Map[t.Left, t.Top] != 0 && Map[t.Left, t.Top]!= this.type )//已遇到坦克和墙等障碍物{bList.RemoveAt(i);//删除此颗子弹if (t.hitE(Map[t.Left, t.Top]))//击中对方坦克Map[t.Left, t.Top] = -1;//此处坦克被打中continue;}t.move();//移动以后if (t.Left < 0 || t.Left > 9 || t.Top < 0 ||t.Top > 9)//超出边界{bList.RemoveAt(i);continue;//删除此颗子弹}if (Map[t.Left, t.Top] != 0)//已遇到物体{bList.RemoveAt(i);//删除此颗子弹if (t.hitE(Map[t.Left, t.Top]))//击中对方坦克Map[t.Left, t.Top] = -1;//此处坦克被打中continue;}}}public void DrawBullet(Graphics g,int [,]Map)//画子弹{MoveBullet(ref Map);foreach (bullet t in bList)//遍历子弹序列t.Draw(g);}//public void NewPosition()//产生新坐标//{// Random r = new Random();// this.left = r.Next(0, 10);//产生0—9的数// this.top = r.Next(0, 10);//产生0—9的数//}//public bool ComparePosition(Tank s)//比较坦克位置//{// if (this.left == s.left && this.top == s.top)// return true;// else// return false;//}}}。
坦克大战源代码
/**坦克大战*/package com.tankgame1;import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.util.*;public class TankGame1_0 extends JFrame implements KeyListener,ActionListener{ GamePanel gp;StartPanel sp;JMenuBar jmb=null;JMenu jm=null,jm1=null;JMenuItem jmi1,jmi2,jmi3,jmi4;TankGame1_0(){jmb=new JMenuBar();jm=new JMenu("文件");jm1=new JMenu("游戏设置");jmi1=new JMenuItem("新游戏");jmi1.setActionCommand("NEW");jmi1.addActionListener(this);jmi2=new JMenuItem("暂停");jmi2.setActionCommand("PAUSE");jmi2.addActionListener(this);jmi3=new JMenuItem("继续");jmi3.setActionCommand("CONTINUE");jmi3.addActionListener(this);jmi4=new JMenuItem("退出");jmi4.setActionCommand("QUIT");jmi4.addActionListener(this);jm.add(jmi1);jm.add(jmi2);jm.add(jmi3);jm.add(jmi4);jmb.add(jm);jmb.add(jm1);// gp=new GamePanel();// Thread t=new Thread(gp);// t.start();// //注册一下接收键盘的动作// this.addKeyListener(this);// //设置界面// this.add(gp);sp=new StartPanel();Thread t=new Thread(sp);t.start();this.add(sp);this.setJMenuBar(jmb);this.setBounds(180, 20, 305, 530);this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }public static void main(String[] args) {TankGame1_0 tg=new TankGame1_0();}@Overridepublic void keyPressed(KeyEvent arg0) {if(!Record.pause){switch(arg0.getKeyCode()){case KeyEvent.VK_UP:if(!gp.mtk.isTouchTank()&&!gp.mtk.isTouchRiver())gp.mtk.moveUp();gp.mtk.setDirect(0);break;case KeyEvent.VK_DOWN:if(!gp.mtk.isTouchTank()&&!gp.mtk.isTouchRiver())gp.mtk.moveDown();gp.mtk.setDirect(2);break;case KeyEvent.VK_LEFT:if(!gp.mtk.isTouchTank()&&!gp.mtk.isTouchRiver())gp.mtk.moveLeft();gp.mtk.setDirect(3);break;case KeyEvent.VK_RIGHT:if(!gp.mtk.isTouchTank()&&!gp.mtk.isTouchRiver())gp.mtk.moveRight();gp.mtk.setDirect(1);break;}if(arg0.getKeyCode()=='A'||arg0.getKeyCode()=='a'){ gp.mtk.kitEnemy();}gp.repaint();}}@Overridepublic void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void actionPerformed(ActionEvent arg0) {if(arg0.getActionCommand().equals("NEW")){this.remove(sp);gp=new GamePanel();Thread t=new Thread(gp);t.start();//注册一下接收键盘的动作this.addKeyListener(this);//设置界面this.add(gp);this.setVisible(true);}if(arg0.getActionCommand().equals("PAUSE")){Record.pause=true;}if(arg0.getActionCommand().equals("CONTINUE")){ Record.pause=false;}if(arg0.getActionCommand().equals("QUIT")){System.exit(0);}}}class GamePanel extends JPanel implements Runnable{//定义的我的坦克MyTank mtk;River river=new River(50,300,200,30);Vector<SoilWall> sw=new V ector<SoilWall>();SoilWall s=null;Vector<SteelWall> stw=new Vector<SteelWall>();SteelWall st=null;Image im1=null;Image im2=null;Image im3=null;Image im4=null;Image im5=null;Vector<Bomb> bb=new Vector<Bomb>();//定义敌人的坦克int drtssize=4;Vector<EnemyTank> drts;EnemyTank dt=null;GamePanel(){//初始化爆炸的图片im1=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_1.gif"));im2=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_2.gif"));im3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/bomb_3.gif"));im4=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/img2.jpg"));im5=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/img1.jpg"));//土墙的初始化for(int i=5;i<24;i++,i++){s=new SoilWall(i*10,120);sw.add(s);}//钢墙的初始化for(int i=5;i<24;i++,i++){st=new SteelWall(i*10,200);stw.add(st);}//我的坦克初始化mtk=new MyTank(135,350,0,0);mtk.setStw(stw);mtk.setSw(sw);//敌人的坦克初始化drts=new Vector<EnemyTank>();for(int i=0;i<this.drtssize;i++){EnemyTank dt=new EnemyTank((i+1)*50,10,2,1);EnemyTank dt1=new EnemyTank((i+1)*50,60,2,1);Thread t=new Thread(dt);Thread t1=new Thread(dt1);t.start();t1.start();dt.setEts(drts);dt1.setEts(drts);dt.setR(river);dt1.setR(river);dt.setSw(sw);dt.setStw(stw);mtk.setEts(drts);mtk.setR(river);drts.add(dt);drts.add(dt1);}}public void paint(Graphics g){super.paint(g);//游戏的操作背景色g.setColor(Color.BLACK);//g.fillRect(0, 0, 300, 400);g.drawImage(im4, 0, 0, 300, 400,this);//让tank接收到panel上的对象mtk.setEts(drts);if(river!=null)mtk.setR(river);//画出河流if(river!=null)g.drawImage(im5, river.x, river.y, river.x1, river.y1, this); //画出墙来g.setColor(Color.yellow);for(int i=0;i<sw.size();i++){s=sw.get(i);if(s.isLive)g.fill3DRect(s.x, s.y, 15, 20, true);elsesw.remove(s);}g.setColor(Color.WHITE);for(int i=0;i<stw.size();i++){st=stw.get(i);if(st.isLive)g.fill3DRect(st.x, st.y, 15, 20, true);elsestw.remove(st);}//画出炸弹for(int i=0;i<bb.size();i++){Bomb bomb=bb.get(i);if(bomb.isLive==true){bomb.times--;if(bomb.times>14)g.drawImage(im1, bomb.x, bomb.y, 30, 30,this);else if(bomb.times>7)g.drawImage(im2, bomb.x, bomb.y, 30, 30,this);else if(bomb.times>0)g.drawImage(im3, bomb.x, bomb.y, 30, 30,this);}if(bomb.times==0){bomb.isLive=false;bb.remove(bomb);}}//画我的坦克if(Record.MyLife>0)drawTank(mtk.getX(),mtk.getY(),mtk.getDirect(),0,g);if(mtk.isLive==false){Record.MyLife--;mtk=new MyTank(135,350,0,0);mtk.setSw(sw);mtk.setStw(stw);}//画我的坦克的子弹g.setColor(Color.white);for(int i=0;i<mtk.bs.size();i++){Bullet b=mtk.bs.get(i);if(b!=null&&b.isLive==true)g.drawOval(b.getX(), b.getY(), 2, 2);if(b.isLive==false)mtk.bs.remove(b);}//画出敌人的坦克for(int i=0;i<drts.size();i++){EnemyTank dt=drts.get(i);if(dt.isLive==true && dt!=null)drawTank(dt.getX(),dt.getY(),dt.getDirect(),dt.getType(),g);if(dt.isLive==false){drts.remove(dt);Record.EnemyLife--;if(Record.EnemyLife>7){dt=new EnemyTank(120,10,2,1);dt.setSw(sw);dt.setStw(stw);Thread t=new Thread(dt);t.start();drts.add(dt);}}}//画出敌人的坦克的子弹g.setColor(Color.white);for(int i=0;i<drts.size();i++){EnemyTank dt=drts.get(i);if(dt.isLive==true)for(int j=0;j<dt.bs.size();j++){Bullet b=dt.bs.get(j);if(b.isLive)g.drawOval(b.getX(), b.getY(), 2, 2);if(b.isLive==false)dt.bs.remove(b);}}//显示游戏结束画面if(Record.EnemyLife<=0||Record.MyLife<=0){g.setColor(Color.YELLOW);g.setFont(new Font("宋体",Font.BOLD,20));g.drawString("GAME OVER!", 100, 100);Record.pause=true;}//显示游戏中的各种提示信息showInfo(g);}//显示信息的方法public void showInfo(Graphics g){Color c=null;c=g.getColor();this.drawTank(50, 420, 0, 0, g);this.drawTank(150, 420, 0, 1, g);g.setColor(Color.BLACK);g.setFont(new Font("黑体",Font.BOLD,20));g.drawString(Record.MyLife+"", 80, 435);g.drawString(Record.EnemyLife+"", 185, 435);g.setColor(c);}//用于绘制坦克public void drawTank(int x,int y,int direct,int type,Graphics g){ switch(type){case 0:g.setColor(Color.YELLOW);break;case 1:g.setColor(Color.green);break;}switch(direct){case 0:g.fill3DRect(x, y, 5, 30, false);g.draw3DRect(x+5, y+5, 10, 20, true);g.fill3DRect(x+15, y, 5, 30, false);g.fillOval(x+7, y+8, 6, 13);g.drawRect(x+10, y-4, 1, 17);break;case 2:g.fill3DRect(x, y, 5, 30, false);g.draw3DRect(x+5, y+5, 10, 20, true);g.fill3DRect(x+15, y, 5, 30, false);g.fillOval(x+7, y+8, 6, 13);g.drawRect(x+10, y+13, 1, 17);break;case 1:g.fill3DRect(x, y, 30, 5, false);g.draw3DRect(x+5, y+5, 20, 10, true);g.fill3DRect(x, y+15, 30, 5, false);g.fillOval(x+9, y+7, 13, 6);g.drawRect(x+15, y+9, 17, 1);break;case 3:g.fill3DRect(x, y, 30, 5, false);g.draw3DRect(x+5, y+5, 20, 10, true);g.fill3DRect(x, y+15, 30, 5, false);g.fillOval(x+9, y+7, 13, 6);g.drawRect(x-2, y+9, 17, 1);break;}}public void kill(Tank t,Bullet b){switch(t.direct){case 0:case 2:if(b.x>t.x&&b.y>t.y&&b.x<t.x+20&&b.y<t.y+30) {t.isLive=false;b.isLive=false;this.bb.add(new Bomb(t.getX(),t.getY()));}break;case 1:case 3:if(b.x>t.x&&b.y>t.y&&b.x<t.x+30&&b.y<t.y+20) {t.isLive=false;b.isLive=false;this.bb.add(new Bomb(t.getX(),t.getY()));}break;}}public void killWall(Wall w,Bullet b){if(b.x>=w.x&&b.y>=w.y&&b.x<=w.x+15&&b.y<=w.y+20) {w.life--;b.isLive=false;if(w.life<=0)w.isLive=false;}}@Overridepublic void run() {while(true){this.repaint();try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if(mtk!=null)for(int i=0;i<mtk.bs.size();i++){Bullet b=mtk.bs.get(i);if(b.isLive){for(int j=0;j<drts.size();j++){Tank t=drts.get(j);if(t.isLive){this.kill(t, b);}}}}for(int i=0;i<drts.size();i++){Tank et=drts.get(i);if(et.isLive){for(int j=0;j<et.bs.size();j++){Bullet b=et.bs.get(j);if(b.isLive&&b!=null){this.kill(mtk, b);}}}}for(int i=0;i<drts.size();i++){Tank et=drts.get(i);if(et.isLive){for(int j=0;j<et.bs.size();j++){Bullet b=et.bs.get(j);for(int k=0;k<sw.size();k++){SoilWall t=sw.get(k);if(t.isLive){this.killWall(t, b);}}for(int k=0;k<stw.size();k++){SteelWall t=stw.get(k);if(t.isLive){this.killWall(t, b);}}}}}for(int i=0;i<mtk.bs.size();i++){Bullet b=mtk.bs.get(i);if(b.isLive){for(int j=0;j<sw.size();j++){SoilWall t=sw.get(j);if(t.isLive){this.killWall(t, b);}}for(int j=0;j<stw.size();j++){SteelWall t=stw.get(j);if(t.isLive){this.killWall(t, b);}}}}}}}//游戏开始界面class StartPanel extends JPanel implements Runnable{ boolean f=true;public void paint(Graphics g){super.paint(g);g.setColor(Color.RED);g.setFont(new Font("宋体",Font.BOLD,30));if(f){g.drawString("请选择菜单", 60, 150);f=false;}elsef=true;}@Overridepublic void run() {while(true){try {Thread.sleep(200);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.repaint();}}}//坦克类class Tank{int x;int y;int direct;int type;int speed;boolean isLive=true;Vector<SoilWall> sw=new V ector<SoilWall>();public Vector<SoilWall> getSw() {return sw;}public void setSw(Vector<SoilWall> sw) {this.sw = sw;}public SoilWall getS() {return s;}public void setS(SoilWall s) {this.s = s;}public Vector<SteelWall> getStw() {return stw;}public void setStw(Vector<SteelWall> stw) {this.stw = stw;}public SteelWall getSt() {return st;}public void setSt(SteelWall st) {this.st = st;}SoilWall s=null;Vector<SteelWall> stw=new Vector<SteelWall>(); SteelWall st=null;Vector<EnemyTank> ets=new Vector<EnemyTank>(); River r=null;public boolean isLive() {return isLive;}public void setLive(boolean isLive) {this.isLive = isLive;}public River getR() {return r;}public void setR(River r) {this.r = r;}public Vector<Bullet> getBs() {return bs;}public void setBs(Vector<Bullet> bs) {this.bs = bs;}public Bullet getB() {return b;}public void setB(Bullet b) {this.b = b;}public Vector<EnemyTank> getEts() {return ets;}public void setEts(Vector<EnemyTank> ets) { this.ets = ets;}Vector<Bullet> bs=new V ector<Bullet>(); Bullet b;public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public int getType() {return type;}public void setType(int type) {this.type = type;}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;}Tank(int x,int y,int direct,int type){this.direct=direct;this.x=x;this.y=y;this.type=type;}public void moveUp(){if(!Record.pause){if(y>=0&&!this.isTouchRiver()&&!this.isTouchWall()) y=y-speed;if(isTouchRiver())y=y+speed;}}public void moveDown(){if(!Record.pause){if(y<=370&&!this.isTouchRiver()&&!this.isTouchWall()) y=y+speed;if(isTouchRiver())y=y-speed;}}public void moveLeft(){if(!Record.pause){if(x>=0&&!this.isTouchRiver()&&!this.isTouchWall()) x=x-speed;if(isTouchRiver())x=x+speed;}}public void moveRight(){if(!Record.pause){if(x<=270&&!this.isTouchRiver()&&!this.isTouchWall()) x=x+speed;if(isTouchRiver())x=x-speed;}}public void kitEnemy(){switch(this.direct){case 0:b=new Bullet(this.x+9,this.y-6,0);break;case 1:b=new Bullet(this.x+31,this.y+8,1);break;case 2:b=new Bullet(this.x+9,this.y+31,2);break;case 3:b=new Bullet(this.x-4,this.y+8,3);break;}if(bs.size()<5){bs.add(b);Thread t=new Thread(b);t.start();}}public boolean isTouchWall(){boolean f=false;switch(this.direct){case 0:case 2:for(int i=0;i<sw.size();i++){s=sw.get(i);if(this.x>=s.x&&this.y>=s.y&&this.x<=s.x+15&&this.y<=s.y+20)f=true;if(this.x+20>=s.x&&this.y>=s.y&&this.x+20<=s.x+15&&this.y<=s.y+20) f=true;if(this.x>=s.x&&this.y+30>=s.y&&this.x<=s.x+15&&this.y+30<=s.y+20) f=true;if(this.x+20>=s.x&&this.y+30>=s.y&&this.x+20<=s.x+15&&this.y+30<=s.y+20)f=true;if(this.x+5>=s.x&&this.y>=s.y&&this.x+5<=s.x+15&&this.y<=s.y+20) f=true;if(this.x+5>=s.x&&this.y+20>=s.y&&this.x+5<=s.x+15&&this.y+20<=s.y+20)f=true;}if(this.direct==0&&f)this.y=this.y+this.speed;if(this.direct==2&&f)this.y=this.y-this.speed;for(int i=0;i<stw.size();i++){st=stw.get(i);if(this.x>=st.x&&this.y>=st.y&&this.x<=st.x+15&&this.y<=st.y+20)f=true;if(this.x+20>=st.x&&this.y>=st.y&&this.x+20<=st.x+15&&this.y<=st.y+20) f=true;if(this.x>=st.x&&this.y+30>=st.y&&this.x<=st.x+15&&this.y+30<=st.y+20) f=true;if(this.x+20>=st.x&&this.y+30>=st.y&&this.x+20<=st.x+15&&this.y+30<=st.y+20)f=true;if(this.x+5>=st.x&&this.y>=st.y&&this.x+5<=st.x+15&&this.y<=st.y+20) f=true;if(this.x+5>=st.x&&this.y+20>=st.y&&this.x+5<=st.x+15&&this.y+20<=st.y+20)f=true;}if(this.direct==0&&f)this.y=this.y+this.speed;if(this.direct==2&&f)this.y=this.y-this.speed;break;case 1:case 3:for(int i=0;i<sw.size();i++){s=sw.get(i);if(this.x>=s.x&&this.y>=s.y&&this.x<=s.x+15&&this.y<=s.y+20)f=true;if(this.x+30>=s.x&&this.y>=s.y&&this.x+30<=s.x+15&&this.y<=s.y+20) f=true;if(this.x>=s.x&&this.y+20>=s.y&&this.x<=s.x+15&&this.y+20<=s.y+20) f=true;if(this.x+30>=s.x&&this.y+20>=s.y&&this.x+30<=s.x+15&&this.y+20<=s.y+20)f=true;if(this.x>=s.x&&this.y+10>=s.y&&this.x<=s.x+15&&this.y+10<=s.y+20) f=true;if(this.x+30>=s.x&&this.y+10>=s.y&&this.x+30<=s.x+15&&this.y+10<=s.y+20)f=true;}if(this.direct==1&&f)this.x=this.x-this.speed;if(this.direct==3&&f)this.x=this.x+this.speed;for(int i=0;i<stw.size();i++){st=stw.get(i);if(this.x>=st.x&&this.y>=st.y&&this.x<=st.x+15&&this.y<=st.y+20)f=true;if(this.x+30>=st.x&&this.y>=st.y&&this.x+30<=st.x+15&&this.y<=st.y+20) f=true;if(this.x>=st.x&&this.y+20>=st.y&&this.x<=st.x+15&&this.y+20<=st.y+20) f=true;if(this.x+30>=st.x&&this.y+20>=st.y&&this.x+30<=st.x+15&&this.y+20<=st.y+20)f=true;if(this.x>=st.x&&this.y+10>=st.y&&this.x<=st.x+15&&this.y+10<=st.y+20) f=true;if(this.x+30>=st.x&&this.y+10>=st.y&&this.x+30<=st.x+15&&this.y+10<=st.y+20)f=true;}if(this.direct==1&&f)this.x=this.x-this.speed;if(this.direct==3&&f)this.x=this.x+this.speed;break;}return f;}public boolean isTouchTank(){boolean f=false;for(int i=0;i<ets.size();i++){EnemyTank et=ets.get(i);if(et!=this){switch(this.direct){case 0:if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.y>=et.y&&this.x<=et.x+20&&this.y<=et.y+30)f=true;if(this.x+20>=et.x&&this.y>=et.y&&this.x+20<=et.x+20&&this.y<=et.y+30)f=true;}if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.y>=et.y&&this.x<=et.x+30&&this.y<=et.y+20)f=true;if(this.x+20>=et.x&&this.y>=et.y&&this.x+20<=et.x+30&&this.y<=et.y+20)f=true;}break;case 1:if(et.direct==0||et.direct==2){if(this.x+30>=et.x&&this.y>=et.y&&this.x+30<=et.x+20&&this.y<=et.y+30)f=true;if(this.x+30>=et.x&&this.y+20>=et.y&&this.x+30<=et.x+20&&this.y+20<=et.y+30)f=true;}if(et.direct==1||et.direct==3){if(this.x+30>=et.x&&this.y>=et.y&&this.x+30<=et.x+30&&this.y<=et.y+20)f=true;if(this.x+30>=et.x&&this.y+20>=et.y&&this.x+30<=et.x+30&&this.y+20<=et.y+20)f=true;}break;case 2:if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.y+30>=et.y&&this.x<=et.x+20&&this.y<=et.y+30){f=true;}if(this.x+20>=et.x&&this.y+30>=et.y&&this.x+20<=et.x+20&&this.y+30<=et.y+30){f=true;}}if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.y+30>=et.y&&this.x<=et.x+30&&this.y<=et.y+20){f=true;}if(this.x+20>=et.x&&this.y+30>=et.y&&this.x+20<=et.x+30&&this.y+30<=et.y+20){f=true;}}break;case 3:if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.y>=et.y&&this.x<=et.x+20&&this.y<=et.y+30)f=true;if(this.x>=et.x&&this.y+20>=et.y&&this.x<=et.x+20&&this.y+20<=et.y+30)f=true;}if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.y>=et.y&&this.x<=et.x+30&&this.y<=et.y+20)f=true;if(this.x>=et.x&&this.y+20>=et.y&&this.x<=et.x+30&&this.y+20<=et.y+20)f=true;}break;}}}return f;}public boolean isTouchRiver(){boolean f=false;if(this.r!=null)switch(this.direct){case 0:case 2:if(this.x>=r.x&&this.y>=r.y&&this.x<=r.x+r.x1&&this.y<=r.y+r.y1)f=true;if(this.x+20>=r.x&&this.y>=r.y&&this.x+20<=r.x+r.x1&&this.y<=r.y+r.y1) f=true;if(this.x>=r.x&&this.y+30>=r.y&&this.x<=r.x+r.x1&&this.y+30<=r.y+r.y1) f=true;if(this.x+20>=r.x&&this.y+30>=r.y&&this.x+20<=r.x+r.x1&&this.y+30<=r.y+r.y1)f=true;if(this.direct==0&&f)this.y=this.y+this.speed;if(this.direct==2&&f)this.y=this.y-this.speed;break;case 1:case 3:if(this.x>=r.x&&this.y>=r.y&&this.x<=r.x+r.x1&&this.y<=r.y+r.y1)f=true;if(this.x+30>=r.x&&this.y>=r.y&&this.x+30<=r.x+r.x1&&this.y<=r.y+r.y1) f=true;if(this.x>=r.x&&this.y+20>=r.y&&this.x<=r.x+r.x1&&this.y+20<=r.y+r.y1) f=true;if(this.x+30>=r.x&&this.y+20>=r.y&&this.x+30<=r.x+r.x1&&this.y+20<=r.y+r.y1) f=true;if(this.direct==1&&f)this.x=this.x-this.speed;if(this.direct==3&&f)this.x=this.x+this.speed;break;}return f;}}//我的坦克类class MyTank extends Tank{MyTank(int x,int y,int direct,int type){super(x,y,direct,type);this.setDirect(0);this.setType(0);this.setSpeed(5);}}//敌人的坦克类class EnemyTank extends Tank implements Runnable{EnemyTank(int x,int y,int direct,int type){super(x,y,direct,type);this.setDirect(2);this.setType(1);this.setSpeed(5);}@Overridepublic void run() {while(true){while(Record.pause){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}this.direct=(int)(Math.random()*4);this.kitEnemy();switch(this.direct){case 0:if(!this.isTouchTank()&&!this.isTouchRiver()&&!this.isTouchWall())for(int i=0;i<=15;i++){this.moveUp();try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 1:if(!this.isTouchTank()&&!this.isTouchRiver()&&!this.isTouchWall())for(int i=0;i<=15;i++){if(!this.isTouchTank()&&!this.isTouchRiver()&&!this.isTouchWall())this.moveRight();try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 2:if(!this.isTouchTank()&&!this.isTouchRiver()&&!this.isTouchWall())for(int i=0;i<=15;i++){if(!this.isTouchTank()&&!this.isTouchRiver()&&!this.isTouchWall())this.moveDown();try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 3:if(!this.isTouchTank()&&!this.isTouchRiver()&&!this.isTouchWall())for(int i=0;i<=15;i++){if(!this.isTouchTank()&&!this.isTouchRiver()&&!this.isTouchWall())this.moveLeft();try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;}}}}class Bullet implements Runnable{int x;boolean isLive=true;public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getDirect() {return direct;}public void setDirect(int direct) {this.direct = direct;}int y;int direct;int speed=10;public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}public Bullet(int x,int y,int direct){this.x=x;this.y=y;this.direct=direct;}@Overridepublic void run() {while(true){while(Record.pause){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}switch(this.direct){case 0:y=y-speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}break;case 1:x=x+speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}break;case 2:y=y+speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}break;case 3:x=x-speed;try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}break;}if(x<-5||y<-5||x>300||y>400){this.isLive=false;break;}}}}//爆炸类class Bomb{int x;int y;int times=24;boolean isLive=true;Bomb(int x,int y){this.x=x;this.y=y;}}class Record{static int MyLife=3;static int EnemyLife=20;static boolean pause=false;}class River{int x,x1;int y,y1;River(int x,int y,int x1,int y1){this.x=x;this.y=y;this.x1=x1;this.y1=y1;}}class Wall{int x;int y;boolean isLive=true;int life=1;Wall(int x,int y){this.x=x;this.y=y;}}class SoilWall extends Wall{SoilWall(int x,int y){super(x, y);life=1;}}class SteelWall extends Wall{SteelWall(int x,int y){super(x,y);life=3;}}。
VB坦克大战代码
Private Sub Form_Load() La.Top = 4000La.Left = 3000La.Height = 800La.Width = 900Lb.Top = 4300Lb.Left = 3900Lb.Height = 200Lb.Width = 900Lc.Top = 4300Lc.Left = 4560Lc.Height = 200Lc.Width = 200End SubPrivate Sub Form_keypress(keyascii As Integer)If keyascii = 106 ThenLa.Enabled = FalseLb.Enabled = FalseIf La.Top - Lb.Top = 900 And Lb.Left - La.Left = 300 Then Lc.Top = La.Top - 900Lc.Left = La.Left + 300Lc.Visible = TrueTimer1."Enabled = TrueTimer2."Enabled = FalseTimer3."Enabled = FalseTimer4."Enabled = FalseElseIf La.Left - Lb.Left = 900 And Lb.Top - La.Top = 300 Then Lc.Top = La.Top + 300Lc.Left = La.Left - 900Lc.Visible = TrueTimer1."Enabled = FalseTimer2."Enabled = TrueTimer3."Enabled = FalseTimer4."Enabled = FalseElseIf Lb.Top - La.Top = 900 And Lb.Left - La.Left = 300 Then Lc.Top = La.Top + 1600Lc.Left = La.Left + 300Lc.Visible = TrueTimer1."Enabled = FalseTimer2."Enabled = FalseTimer3."Enabled = TrueTimer4."Enabled = FalseElseIf Lb.Left - La.Left = 900 And Lb.Top - La.Top = 300 Then Lc.Top = La.Top + 300Lc.Left = La.Left + 1600Lc.Visible = TrueTimer1."Enabled = FalseTimer2."Enabled = FalseTimerTimer4."Enabled = TrueEnd IfElseIf keyascii = 119 Then La.Enabled = TrueLb.Enabled = TrueLb.Left = La.Left + 300 Lb.Top = La.Top - 900 La.Height = 900La.Width = 800Lb.Width = 200Lb.Height = 900If Lb.Top <= 0 Then Lb.Enabled = FalseLa.Enabled = FalseElseLa.Top = La.Top - 100 Lb.Top = Lb.Top - 100 End IfElseIf keyascii = 97 ThenLb.Enabled = TrueLb.Left = La.Left - 900 Lb.Top = La.Top + 300 La.Height = 800La.Width = 900Lb.Width = 900Lb.Height = 200If Lb.Left <= 0 Then Lb.Enabled = FalseLa.Enabled = FalseElseLa.Left = La.Left - 100 Lb.Left = Lb.Left - 100 End IfElseIf keyascii = 100 Then La.Enabled = TrueLb.Enabled = TrueLb.Left = La.Left + 900 Lb.Top = La.Top + 300 La.Height = 800La.Width = 900Lb.Width = 900Lb.Height = 200If Lb.Left >= 8700 Then Lb.Enabled = FalseLa.Enabled = FalseElseLa.Left = La.Left + 100 Lb.Left = Lb.Left + 100 End IfElseIf keyascii = 115 Then La.Enabled = TrueLb.Enabled = TrueLb.Left = La.Left + 300 Lb.Top = La.Top + 900 La.Height = 900La.Width = 800Lb.Width = 200Lb.Height = 900If Lb.Top >= 7600 Then Lb.Enabled = FalseLa.Enabled = FalseElseLa.Top = La.Top + 100Lb.Top = Lb.Top + 100End IfElseIf keyascii = 8 ThenEndEnd IfEnd SubPrivate Sub Timer1_Timer()Do While Lc.Top > 0Lc.Top = Lc.Top - 2Lc.Left = Lc.LeftIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top< Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = FalseTimer1."Enabled = FalseEnd SubPrivate Sub Timer2_Timer()Do While Lc.Left > 0Lc.Left = Lc.Left - 2Lc.Top = Lc.TopIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top <Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = FalseTimer2."Enabled = FalseEnd SubPrivate Sub Timer3_Timer()Do While Lc.Top < 8880Lc.Top = Lc.Top + 2Lc.Left = Lc.LeftIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top <Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = FalseTimer3."Enabled = FalseEnd SubPrivate Sub Timer4_Timer()Do While Lc.Left < 9750Lc.Left = Lc.Left + 2Lc.Top = Lc.TopIf Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top< Ld.Top + Ld.Height ThenLd.Visible = FalseLc.Visible = FalseEnd IfLoopLc.Visible = FalseTimer4."Enabled = FalseEnd Sub。
坦克大战代码
坦克大战代码// 1、TTank.cpp: implementation of the TTank class.坦克类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TankWar.h"#include "TTank.h"#include "TWorld.h"#include "TExplode.h"#include "TBonus.h"#include "TBullet.h"//////////////////////////////////////////////////////////////////////// Construction/Destruction/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEnemyTank///////////////////////////////////////////////////////////////////EPG TEnemyTank::m_epg[3];//////////////////////////////////////////////////敌军坦克移动void TEnemyTank::Move(){if(!IsMyTime())return ;//防护小于0,还不死吗if(m_nShield < 0){Dead();//玩家增加经验值g_world.Player(0)->m_nExper += 10 + m_nType * 10;//加点爆炸效果g_world.ExplodeLink().Add(NEWTExplode(m_nX,m_nY,EXPLODE_TANK));}///////////////////////////////////////////////////////疯子要行动了,怎么动呢?用随机数来决定吧//玩家没进入范围,什么也不做if(ABS(m_nX-g_world.Player(0)->GetX())>500 ||ABS(m_nY-g_world.Player(0)->GetY())>500)return ;//产生0到100之间的随机数状态int status=Rand(0,100);//保存现在的位置坐标int x=m_nX,y=m_nY;//根据产生的状态行动if(status<2){//状态小于2,改变一下方向(概率是... 计算一下好像是: 2/100即0.02)m_dir =(DIRECTION) Rand(0,4);}else if(status <3){//状态小于3,开火(概率是... 计算一下好像是: (3-2)/100即0.01)switch(m_nType){case FIRE_TANK://火弹:射程100,威力20g_world.BulletLink().Add(NEWTBullet(m_nX,m_nY,m_dir,FIRE,20,100));break;case DOUBLE_MISSILE_TANK://火弹:射程250,威力15g_world.BulletLink().Add(NEWTBullet(m_nX,m_nY,m_dir,DMISSILE,15,250));break;case SINGLE_MISSILE_TANK://火弹:射程250,威力10g_world.BulletLink().Add(NEWTBullet(m_nX,m_nY,m_dir,SMISSILE,10,250));break;}}else{//其它的状态值就表示运行吧(概率是... 计算一下好像是: 100-3/100即0.97)//生命在于运动嘛:)m_nX+=g_nDirXY[m_dir][0];m_nY+=g_nDirXY[m_dir][1];}///////////////////////////////////////////////////////计算一下上面的移动是否有效//先假设移动有效BOOL canMove=TRUE;//取得自己的边框RECT rc;GetRect(rc);//////////////////////////////////////////////////////根据方向来计算是否与障碍地图上的障碍物碰撞if(m_dir==DIR_UP){//方向向上,只检查左上角及右上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))canMove = FALSE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIGHT ))canMove = FALSE;}else if(m_dir==DIR_DOWN){//方向向下,只检查左下角及右下角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_H EIGHT))canMove = FALSE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))canMove = FALSE;}else if(m_dir==DIR_RIGHT){//方向向右,只检查右下角及右上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEI GHT))canMove = FALSE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))canMove = FALSE;}else if(m_dir==DIR_LEFT){//方向向左,只检查左上角及左上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))canMove = FALSE;elseif(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEIG HT))canMove = FALSE;}//总不能移到世界范围以外吧if(m_nY>g_world.GetHeight()-OBSTACLE_HEIGHT ||m_nX>g_world.GetWidth()-OBSTACLE_WIDTH ||m_nX<0 || m_nY<0)canMove = FALSE;//有没有碰到其它的NC坦克?不过要记住排除与自己相撞的情况//疯子也不会疯到这种程度吧if(g_world.EnemyTankLink().HitTestAll(this))//停下来,打个招呼canMove = FALSE;//撞到了其它障碍物(木箱、邪恶之源)了吗?if(g_world.ObstacleLink().HitTestAll(this))canMove = FALSE;//碰到玩家坦克了吗?if(g_world.Player(0)->HitTest(this))//当然不能动了canMove = FALSE;//移动无效,恢复原值if(canMove==FALSE)m_nX = x,m_nY=y;////////////////////////////计算当前动画帧m_nCurrentFrame=m_dir;}////////////////////////////////////////////////////画坦克void TEnemyTank::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);WGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );}///////////////////////////////////////////取边框void TEnemyTank::GetRect(RECT& rc){rc.left = m_nX - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}/////////////////////////////////////////////////TEnemyTank::TEnemyTank(int x, int y, int nType):TSprite(x,y,100,0,CLASS_TENEMYTANK),m_nType(nType){switch(nType){case FIRE_TANK://防护力100,速度1/(50/1000)m_nShield = 100;SetDelayTimer(50);break;case DOUBLE_MISSILE_TANK://防护力150,速度1/(70/1000)m_nShield = 150;SetDelayTimer(70);break;case SINGLE_MISSILE_TANK://防护力100,速度1/(30/1000)m_nShield = 200;SetDelayTimer(30);break;}}///////////////////////////////////////////////////////////碰撞是否有效BOOL TEnemyTank::HitBy(TObject * pObj){//////////////////////////////////////////////与参数对象碰撞if(HitTest(pObj)){////////////////////////////////////////////参数对象是一个子弹if(pObj->ClassType()==CLASS_TBULLET){//转变为子弹对象TBullet * pBullet = (TBullet*)pObj;if(pBullet->m_nType == LIGHT){//是光弹,防护减去光弹的力量m_nShield -= pBullet->m_nShield ;return TRUE;}}}return FALSE;}///////////////////////////////////////////////////////////////////////// TPlayerTank玩家///////////////////////////////////////////////////////////////////EPG TPlayerTank::m_epg[3];TPlayerTank::TPlayerTank(int x, int y, int nType):TSprite(x,y,100,0,CLASS_TPLAYERTANK),m_nType(nType),m_nExper(0),m_nMoney(0),m_nMaxShield(100){SetDelayTimer(1); //参考值40,这里是1}///////////////////////////////////////////////////碰撞是否有效BOOL TPlayerTank::HitBy(TObject * pObj){/////////////////////////////////////////////是否与参数对象碰撞if(HitTest(pObj)){if(pObj->ClassType()==CLASS_TBULLET){//参数对象炮弹TBullet * pBullet = (TBullet*)pObj;if(pBullet->m_nType == FIRE||pBullet->m_nType == DMISSILE||pBullet->m_nType == SMISSILE){//被火弹,双导弹,单导弹(都是敌方的炮弹)击中,减防护力// m_nShield -= pBullet->m_nShield ;m_nShield += pBullet->m_nShield ;return TRUE;}}else if(pObj->ClassType()==CLASS_TBONUS){//参数对象是奖励TBonus * pBonus = (TBonus*)pObj;switch(pBonus->m_nBonusType){case BONUS_RECOVER: //恢复物品m_nShield += 20; //恢复20点m_nShield = MIN(m_nShield+20,m_nMaxShield);break;case BONUS_EXPER: //经验物品//m_nExper += 10; //经验值加10m_nType = MIN((m_nExper/1000),2); //第1000点升一级m_nMaxShield = 100 + m_nExper/100; //调整最大防护m_dwDelayTimer -= m_dwDelayTimer*10/100; //速度提高10%break;case BONUS_MONEY:m_nMoney += 100; //得到100元}return TRUE;}}return FALSE;}///////////////////////////////////////////////////////玩家坦克移动void TPlayerTank::Move(){if(!IsMyTime())return ;/*if(m_nShield<0){Dead();g_world.ExplodeLink().Add(NEWTExplode(m_nX,m_nY,EXPLODE_PLAYER));return;}*//////////////////////////////////////////////////////响应键盘事件,移动坦克//保存原坐标int x=m_nX,y=m_nY;//处理按键if(WGE_Input.Key()[DIK_UP]){if(m_nY>0) m_nY -- ;m_dir = DIR_UP;}elseif(WGE_Input.Key()[DIK_DOWN]){if(m_nY<g_world.GetHeight()-OBSTACLE_HEIGHT)m_nY += 1;m_dir = DIR_DOWN;}elseif(WGE_Input.Key()[DIK_LEFT]){if(m_nX>0) m_nX -= 1;m_dir = DIR_LEFT;}elseif(WGE_Input.Key()[DIK_RIGHT]){if(m_nX<g_world.GetWidth()-OBSTACLE_WIDTH)m_nX += 1;m_dir = DIR_RIGHT;}///////////////////////////////////////////////////////////计算上面的移动是否有效BOOL canMove=TRUE; //假设有效先RECT rc;GetRect(rc);//是否碰撞地形障碍?方法和敌人坦克一样if(m_dir==DIR_UP){if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))canMove = TRUE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIGHT ))canMove = TRUE;}elseif(m_dir==DIR_DOWN){if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_H EIGHT))canMove =TRUE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))canMove = TRUE;}elseif(m_dir==DIR_RIGHT){if(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIGHT))canMove = TRUE;elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))canMove = TRUE;}elseif(m_dir==DIR_LEFT){if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))canMove = TRUE;elseif(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEIG HT))canMove = TRUE;}//碰到了敌人的坦克没有?if(g_world.EnemyTankLink().HitTestAll(this))canMove = FALSE;//是否碰到了障碍物(木箱或邪恶源)if(g_world.ObstacleLink().HitTestAll(this))canMove = FALSE;//移动无效,恢复原坐标if(canMove==FALSE)m_nX = x,m_nY=y;//计算当前动画帧m_nCurrentFrame=m_dir;//按左CTRL键开火,不过每100ms才能开一次,加弹总要花点时间吧:)static DWORD dwFireTick=GetTickCount();if(GetTickCount()-dwFireTick>10) //参考值100ms,这里是10ms{if(WGE_Input.Key()[DIK_LCONTROL]||WGE_Input.Key()[DIK_RCONTROL ]){g_world.BulletLink().Add(NEWTBullet(m_nX,m_nY,m_dir,LIGHT,10+m_nMoney/300,100+m_nType*25));}dwFireTick=GetTickCount();}//让玩家坦克处于可视区的中央g_world.GetViewportRect(rc);int height= rc.bottom - rc.top - OBSTACLE_HEIGHT;int width= rc.right - rc.left - OBSTACLE_WIDTH;g_world.SetViewport(m_nX-width/2,m_nY-height/2);}////////////////////////////////////////////////////////画玩家坦克void TPlayerTank::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);WGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );}/////////////////////////////////////////////////返回坦克的边框void TPlayerTank::GetRect(RECT& rc){rc.left = m_nX - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}//2、TBonus.cpp: implementation of the TBonus class.奖励类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TBonus.h"#include "TWorld.h"EPG TBonus::m_epg_bonus[3];ESound TBonus::m_sound[1];//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TBonus::~TBonus(){}TBonus::TBonus(int x, int y, BONUS nBonusType):TObject(x,y,CLASS_TBONUS){m_nBonusType = nBonusType ;m_nCurrentFrame = 0;m_dwDelayTimer= 100;}void TBonus::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);WGE_Surface.Blt(m_epg_bonus[m_nBonusType],m_nCurrentFrame,p.x,p.y );}void TBonus::GetRect(RECT &rc){rc.left = m_nX - m_epg_bonus[m_nBonusType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg_bonus[m_nBonusType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg_bonus[m_nBonusType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg_bonus[m_nBonusType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}void TBonus::Move(){if(!IsMyTime())return ;if(g_world.Player(0)->HitBy(this)){Dead();m_sound[0].Play();}++m_nCurrentFrame%=m_epg_bonus[m_nBonusType].GetFrameCount();}//3、TBullet.cpp: implementation of the TBullet class.子弹类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TBullet.h"#include "TExplode.h"#include "Tworld.h"ESound TBullet::m_sound[4];EPG TBullet::m_epg[4];//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TBullet::TBullet(int x,int y,DIRECTION dir,BULLET_TYPE nType,int nShield,int nFireRange):TSprite(x,y,nShield,0,CLASS_TBULLET),m_nType(nType){SetDelayTimer(50);m_dir = dir;m_nFireRange = nFireRange;////////////////////////////////////////////计算音效的音量及均衡int valume,pan; //音量和均衡int w,h;//声源与玩家的距离w = x - g_world.Player(0)->GetX();h = y - g_world.Player(0)->GetY();//计算音效的音量及均衡valume = MAX(ABS(w),ABS(h)) * (-10000/800);pan = w * (10000/400);///////////////////////////////////////////////////跟据类型设置速度switch(nType){case LIGHT://玩家的子弹,总会听到声音的m_nSpeed = 15;//if(valume>-10000) //小于最小音量,没必要播放m_sound[2].Play(-1000,pan);break;case FIRE:m_nSpeed = 10;if(valume>-10000)m_sound[1].Play(valume,pan);break;case DMISSILE:m_nSpeed = 0; //导弹开始速度为0,然后利用加速度加速if(valume>-10000)m_sound[0].Play(valume,pan);break;case SMISSILE:m_nSpeed = 0;if(valume>-10000)m_sound[0].Play(valume,pan);break;}}TBullet::~TBullet(){}void TBullet::Move(){if(!IsMyTime())return ;TLinkNode * pNode;switch(m_nType){case FIRE: //火弹,由火坦克发射的炮弹//计算出当前动画帧m_nCurrentFrame = m_dir*3+(m_nCurrentFrame+1)%3;//超出射程范围,发出死亡信息if(m_nFireRange<0){Dead();}//击中玩家了吗?(即使死了也不让你好过)if(g_world.Player(0)->HitBy(this)){//击中目标,任务完成Dead();}//已经死亡,来个爆炸效果if(IsDead())g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY,EXPLODE_FIRE));break;case DMISSILE: //双导弹,敌军的导弹m_nSpeed +=1; //以加速为1的速度运动m_nCurrentFrame = m_dir; //计算当前动画的帧//超出射程范围,发出死亡信息if(m_nFireRange<0)Dead();//击中玩家?if(g_world.Player(0)->HitBy(this))Dead();//死了if(IsDead()){///////////////////////////////////////////////////////双导弹当然是两个爆炸效果if(m_dir==DIR_RIGHT||m_dir==DIR_LEFT){g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY+6,EXPLODE_MISSILE));g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY-6,EXPLODE_MISSILE));}else{g_world.ExplodeLink().Add(NEW TExplode(m_nX+6,m_nY,EXPLODE_MISSILE));g_world.ExplodeLink().Add(NEW TExplode(m_nX-6,m_nY,EXPLODE_MISSILE));}}break;case SMISSILE: //单导弹,不用注释了吧m_nSpeed ++;m_nCurrentFrame = m_dir;if(m_nFireRange<0)Dead();if(g_world.Player(0)->HitBy(this))Dead();if(IsDead())g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY,EXPLODE_MISSILE));break;case LIGHT: //我们的武器:)m_nCurrentFrame = 0;//////////////////////////////////////////////////////计算是否打中在链表中的敌军坦克//取得链表中的第一辆坦克pNode=g_world.EnemyTankLink().m_pHeader;while(pNode) //还不到链尾{//打中了吗?if(pNode->m_pObject->HitBy(this))//Ok,Mission completedDead();//取得下一辆坦克pNode = pNode->m_pNext;}//////////////////////////////////////////////////////计算是否打中障碍物pNode = g_world.ObstacleLink().m_pHeader ;while(pNode){if(pNode->m_pObject->HitBy(this))Dead();pNode = pNode->m_pNext;}if(m_nFireRange<0){//太远了,没办法Dead();}//???,为什么没有爆炸效果?break;default:TRACE(0,"Invalid bullet id");break;}//填加的代码//取得自己的边框RECT rc;GetRect(rc);if(m_nType==LIGHT||m_nType==FIRE||m_nType==SMISSILE||m_nType==D MISSILE){if(m_dir==DIR_UP){//方向向上,只检查左上角及右上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))Dead(); //子弹消失elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIGHT ))Dead();}else if(m_dir==DIR_DOWN){//方向向下,只检查左下角及右下角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_H EIGHT))Dead();elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))Dead();}else if(m_dir==DIR_RIGHT){//方向向右,只检查右下角及右上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEI GHT))Dead();elseif(g_world.ObstacleMap(rc.right/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEI GHT))Dead();}else if(m_dir==DIR_LEFT){//方向向左,只检查左上角及左上角坐标是否碰到障碍if(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.top/OBSTACLE_HEIG HT))Dead();elseif(g_world.ObstacleMap(rc.left/OBSTACLE_WIDTH,rc.bottom/OBSTACLE_HEIG HT))Dead();}}//是不是死了?if(!IsDead()){//没死,那么继续移动//速度太快了!if(m_nSpeed>24)m_nSpeed = 24;//向前,向前,向前...m_nX+=g_nDirXY[m_dir][0]*m_nSpeed;m_nY+=g_nDirXY[m_dir][1]*m_nSpeed;//改变射程m_nFireRange -= m_nSpeed;}}////////////////////////////////////////////////画子弹void TBullet::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p); //把世界逻辑坐标转换到设备坐标WGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );/////////////////////////////////////////////////取得碰撞矩形void TBullet::GetRect(RECT& rc){rc.left = m_nX - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}// TExplode.cpp: implementation of the TExplode class.////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TExplode.h"#include "TWorld.h"EPG TExplode::m_epg[4];ESound TExplode::m_sound[3];//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TExplode::TExplode(int x,int y,EXPLODE nType):TObject(x,y,CLASS_TEXPLODE),m_nType(nType),m_nCurrentFrame(0){SetDelayTimer(100);switch(nType){case EXPLODE_TANK:case EXPLODE_BOX:m_sound[0].Play();break;case EXPLODE_PLAYER://玩家爆炸动画慢一点,与声音配合SetDelayTimer(200);m_sound[0].Play();break;}}TExplode::~TExplode(){}/////////////////////////////////////////////////移动void TExplode::Move(){if(!IsMyTime())return ;/////////////////////////////////////////////计算if(m_nType==EXPLODE_PLAYER){//玩家爆炸应该壮烈一点if(m_nCurrentFrame>=m_epg[3].GetFrameCount()-1){//先来一个小爆炸m_sound[1].Play();//然后变成大爆炸m_nType = EXPLODE_TANK;m_nCurrentFrame = 0;return ;}}else{//一般爆炸就可以了if(m_nCurrentFrame>=m_epg[m_nType].GetFrameCount()-1){//爆炸消失Dead();return ;}}m_nCurrentFrame ++;}/////////////////////////////////////////////////画出爆炸void TExplode::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);if(m_nType==EXPLODE_PLAYER){WGE_Surface.Blt(m_epg[3],m_nCurrentFrame,p.x,p.y);}elseWGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );}//////////////////////////////////////////////取得动画边框void TExplode::GetRect(RECT& rc){int i;if(m_nType==EXPLODE_PLAYER)i = 3;elsei = m_nType;rc.left = m_nX - m_epg[i].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[i].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[i].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[i].GetFrame(m_nCurrentFrame)->m_dwWidth ;}// 4、TLink.cpp: implementation of the TLink class.连接类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TLink.h"//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TLink::TLink(){m_pHeader = NULL;}TLink::~TLink(){DeleteAll();}void TLink::AddHeader(TObject * pObject){ASSERT(pObject);TLinkNode * pAddNode = NEW TLinkNode(pObject);pAddNode->m_pNext = m_pHeader;m_pHeader = pAddNode;}void TLink::AddTail(TObject * pObject){ASSERT(pObject);TLinkNode * pAddNode = NEW TLinkNode(pObject);if(m_pHeader==NULL){m_pHeader = pAddNode ;m_pHeader->m_pNext = NULL;}else{TLinkNode * pNode = m_pHeader ;while(pNode->m_pNext){ASSERT(pObject!=pNode->m_pObject);pNode = pNode->m_pNext ;}pNode->m_pNext = pAddNode ;pAddNode->m_pNext = NULL;}}void TLink::Add(TObject * pObject){AddHeader(pObject);}void TLink::DeleteAll(){TLinkNode * pNode = m_pHeader;while(pNode){m_pHeader = pNode->m_pNext ;delete pNode ;pNode = m_pHeader;}}void TLink::Delete(TObject * pObject){TLinkNode * pPreNode = m_pHeader ;if(m_pHeader->m_pObject == pObject){m_pHeader = m_pHeader->m_pNext ;delete pPreNode ;return ;}TLinkNode * pNode = pPreNode->m_pNext ;while(pNode){if(pNode->m_pObject == pObject){pPreNode->m_pNext = pNode->m_pNext ;delete pNode;return ;}pPreNode = pNode ;pNode = pNode->m_pNext ;}}/////////////////////////////////画出链表中所有的对象void TLink::DrawAll(){TLinkNode * pNode = m_pHeader;while(pNode){pNode->m_pObject->Draw();pNode = pNode->m_pNext ;}}//////////////////////////////////////////////移动链表中所有的对象void TLink::MoveAll(){//取得第一个结点TLinkNode * pNode = m_pHeader;//循环整个链表while(pNode){if(pNode->m_pObject->IsDead()){//该对象已经被击毁,从链表中删除TObject * pDeleteObj = pNode->m_pObject;pNode = pNode->m_pNext ;Delete(pDeleteObj);}else{//调用该对象的Move()函数pNode->m_pObject->Move();pNode = pNode->m_pNext ;}}}BOOL TLink::HitTestAll(TObject * pObj){TLinkNode * pNode = m_pHeader;BOOL bHit = FALSE;while(pNode && bHit==FALSE){if(pNode->m_pObject != pObj)bHit=pNode->m_pObject->HitTest(pObj);pNode = pNode->m_pNext ;}return bHit;}//5、TObject.cpp: implementation of the TObject class.物体类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TObject.h"//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TObject::TObject(int x,int y,CLASS_TYPE nClassType):m_nX(x),m_nY(y),m_dwLastTickCount(0),m_dwDelayTimer(0),m_nClassType(nClassType),m_bIsDead(FALSE){TObject::~TObject(){}///////////////////////////////////////////////该对象是否与另它对象碰撞BOOL TObject::HitTest(TObject* object){RECT rc1,rc2,temp;GetRect(rc1);object->GetRect(rc2);return IntersectRect(&temp,&rc1,&rc2);}////////////////////////////////////////////////是否该我动了?BOOL TObject::IsMyTime(){if(GetTickCount()-m_dwLastTickCount>=m_dwDelayTimer){m_dwLastTickCount = GetTickCount();return TRUE;}return FALSE;}//6、TObstacle.cpp: implementation of the TObstacle class.障碍物类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TObstacle.h"#include "TBonus.h"#include "TBullet.h"#include "TExplode.h"#include "TWorld.h"EPG TObstacle::m_epg[2];//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TObstacle::TObstacle(int x,int y,OBSTACLE nType):TObject(x,y,CLASS_TOBSTACLE),m_nType(nType),m_nCurrentFrame(0) {SetDelayTimer(100);switch(m_nType){case OBSTACLE_BOX: //木箱//硬度100m_nHardiness = 100;break;case OBSTACLE_END: //邪恶源//硬度1000! ,非常硬m_nHardiness = 1000;break;}}TObstacle::~TObstacle(){}void TObstacle::Destroy(){m_epg[0].Destroy();m_epg[1].Destroy();}///////////////////////////////////////////////击中测试BOOL TObstacle::HitBy(TObject * pObj){if(HitTest(pObj)){////////////////////////////////////////只能被光弹击中if(pObj->ClassType()==CLASS_TBULLET){TBullet * pBullet = (TBullet*)pObj;if(pBullet->m_nType == LIGHT){m_nHardiness -= pBullet->m_nShield ;return TRUE;}}}return FALSE;}////////////////////////////////////////////移动void TObstacle::Move(){if(!IsMyTime())return ;//计算当前帧++m_nCurrentFrame%=m_epg[m_nType].GetFrameCount();if(m_nHardiness<0){//消失Dead();if(m_nType == OBSTACLE_END){//邪恶源被击毁,过关//强烈爆炸g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY, EXPLODE_PLAYER));//经验值+1000g_world.Player(0)->m_nExper += 1000;//进入下一关g_game_status = GAME_STAGECLEAR;}else if(m_nType == OBSTACLE_BOX){//产生一个随机物品g_world.BonusLink().Add(NEW TBonus(m_nX,m_nY,(BONUS)Rand(0,3)));//然后爆炸g_world.ExplodeLink().Add(NEW TExplode(m_nX,m_nY, EXPLODE_BOX));}}}/////////////////////////////////////////////画出来void TObstacle::Draw(){POINT p;p.x = m_nX;p.y = m_nY;g_world.LPToDP(p);WGE_Surface.Blt(m_epg[m_nType],m_nCurrentFrame,p.x,p.y );}///////////////////////////////////////////////////////碰撞边框void TObstacle::GetRect(RECT& rc){rc.left = m_nX - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyX;rc.top = m_nY - m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_nKeyY;rc.bottom = rc.top + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwHeight ;rc.right = rc.left + m_epg[m_nType].GetFrame(m_nCurrentFrame)->m_dwWidth ;}// TSprite.cpp: implementation of the TSprite class. 精灵类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TSprite.h"int g_nDirXY[4][2] ={{1,0} , {0,1},{-1,0},{0,-1}};//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////TSprite::TSprite(int x,int y,int nShield,int nStatus,CLASS_TYPE nClassType):TObject(x,y,nClassType),m_nShield(nShield),m_nStatus(nStatus),m_dir(DIR_LEFT) ,m_nCurrentFrame(0){}TSprite::~TSprite(){}// TWorld.cpp: implementation of the TWorld class. 世界类////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include "TankWar.h"#include "TWorld.h"#include "TBonus.h"#include "TObstacle.h"TWorld g_world; //全局唯一的世界对象//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////EGroupPic TWorld::m_grp_terrain;EPG TWorld::m_epg_icon[3];TWorld::TWorld():m_pTerrainMap(NULL),m_pObstacleMap(NULL){}TWorld::~TWorld(){DestroyWorld();}//////////////////////////////////////////////////加载地形图像BOOL TWorld::LoadTerrainPicture(LPCSTR szGrpFile,EDataFile* pDat){if(m_grp_terrain.Load(szGrpFile,pDat)==FALSE){MessageBox(NULL,szGrpFile,"加载错误",MB_OK);return FALSE;}return TRUE;。
坦克大战程序代码
坦克大战程序代码This model paper was revised by the Standardization Office on December 10, 2020class f extends JFrame {f(String title) {(title) ;(608 , 630) ;(300 , 100) ;;MyTank mp = new MyTank() ;(mp) ;(mp) ;new Thread(mp).start() ;}public static void main(String[] args) { f h = new f("坦克大战(版本") ;(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) () * 560) ;yf[i] = (int) () * 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) { (g) ;;;("生命:" , 10 , 20 ) ;(50 , 10 , shengming * 5 , 10) ;(50 , 10 , 500 , 10) ;("得分: "+ fenshu , 10 , 40) ;if(op == 1) {;(x , y , 40 , 40) ;switch (color % 6) {case 0: ; break;case 1: ; break;case 2: ; break;case 3: ; break;case 4: ; break;case 5: ; break;}(x - 5 , y - 5 , 10 , 10) ; (x - 5 , y + 5 , 10 , 10) ; (x - 5 , y + 15 , 10 , 10) ; (x - 5 , y + 25 , 10 , 10) ; (x - 5 , y + 35 , 10 , 10) ; (x + 35 , y - 5 , 10 , 10) ; (x + 35 , y + 5 , 10 , 10) ; (x + 35 , y + 15 , 10 , 10) ; (x + 35 , y + 25 , 10 , 10) ; (x + 35 , y + 35 , 10 , 10) ; ;(x + 15 , y - 20 , 10 , 40) ; switch (color % 20) {case 0: ; break; case 1: ; break; case 2: ; break; case 3: ; break; case 4: ; break; case 5: ; break; case 6: ; break; case 7: ; break; case 8: ; break; case 9: ; break; case 10: ; break; case 11: ; break; case 12: ; break; case 13: ; break; case 14: ; break; case 15: ; break;case 16: ; break;case 17: ; break;case 18: ; break;case 19: ; break; }(x + 5 , y + 30 , 10 , 10) ; (x + 25 , y + 30 , 10 , 10) ; }if(op == 2) {;(x , y , 40 , 40) ;switch (color % 6) {case 0: ; break;case 1: ; break;case 2: ; break;case 3: ; break;case 4: ; break;case 5: ; break;}(x - 5 , y - 5 , 10 , 10) ; (x + 5 , y - 5 , 10 , 10) ; (x + 15 , y - 5 , 10 , 10) ; (x + 25 , y - 5 , 10 , 10) ; (x + 35 , y - 5 , 10 , 10) ; (x - 5 , y+35 , 10 , 10) ; (x + 5 , y+35 , 10 , 10) ; (x + 15 , y+35 , 10 , 10) ; (x + 25 , y+35 , 10 , 10) ; (x + 35 , y+35 , 10 , 10) ; ;(x + 20 , y + 15 , 40 , 10) ; switch (color % 20) {case 1: ; break; case 2: ; break; case 3: ; break; case 4: ; break; case 5: ; break; case 6: ; break; case 7: ; break; case 8: ; break; case 9: ; break; case 10: ; break; case 11: ; break; case 12: ; break; case 13: ; break; case 14: ; break; case 15: ; break;case 17: ; break;case 18: ; break;case 19: ; break; }(x , y + 5 , 10 , 10) ;(x , y + 25 , 10 , 10) ;}if(op == 3) {;(x , y , 40 , 40) ;switch (color % 6) {case 0: ; break;case 1: ; break;case 2: ; break;case 3: ; break;case 5: ; break;}(x - 5 , y - 5 , 10 , 10) ; (x - 5 , y + 5 , 10 , 10) ; (x - 5 , y + 15 , 10 , 10) ; (x - 5 , y + 25 , 10 , 10) ; (x - 5 , y + 35 , 10 , 10) ; (x + 35 , y - 5 , 10 , 10) ; (x + 35 , y + 5 , 10 , 10) ; (x + 35 , y + 15 , 10 , 10) ; (x + 35 , y + 25 , 10 , 10) ; (x + 35 , y + 35 , 10 , 10) ; ;(x + 15 , y + 20 , 10 , 40) ; switch (color % 20) {case 1: ; break; case 2: ; break; case 3: ; break; case 4: ; break; case 5: ; break; case 6: ; break; case 7: ; break; case 8: ; break; case 9: ; break; case 10: ; break; case 11: ; break; case 12: ; break; case 13: ; break; case 14: ; break; case 15: ; break;case 17: ; break;case 18: ; break;case 19: ; break; }(x + 5 , y , 10 , 10) ;(x + 25 , y , 10 , 10) ;}if(op == 4) {;(x , y , 40 , 40) ;switch (color % 6) {case 0: ; break;case 1: ; break;case 2: ; break;case 3: ; break;case 5: ; break;}(x - 5 , y - 5 , 10 , 10) ; (x + 5 , y - 5 , 10 , 10) ; (x + 15 , y - 5 , 10 , 10) ; (x + 25 , y - 5 , 10 , 10) ; (x + 35 , y - 5 , 10 , 10) ; (x - 5 , y+35 , 10 , 10) ; (x + 5 , y+35 , 10 , 10) ; (x + 15 , y+35 , 10 , 10) ; (x + 25 , y+35 , 10 , 10) ; (x + 35 , y+35 , 10 , 10) ; ;(x - 20 , y + 15 , 40 , 10) ; switch (color % 20) {case 1: ; break; case 2: ; break; case 3: ; break; case 4: ; break; case 5: ; break; case 6: ; break; case 7: ; break; case 8: ; break; case 9: ; break; case 10: ; break; case 11: ; break; case 12: ; break; case 13: ; break; case 14: ; break; case 15: ; break;case 17: ; break;case 18: ; break;case 19: ; break; }(x + 30 , y + 5 , 10 , 10) ; (x + 30 , y + 25 , 10 , 10) ; };(dx , dy , 10 , 10) ;(dx1 , dy1 , 10 , 10) ;(dx2 , dy2 , 10 , 10) ;(dx3 , dy3 , 10 , 10) ;(dx4 , dy4 , 10 , 10) ;for (int i = 0; i<num; i++) { if(opf[i] == 1) {(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 15 , 10 , 10) ; (xf[i] - 5 , yf[i] + 25 , 10 , 10) ; (xf[i] - 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 35 , yf[i] - 5 , 10 , 10) ; (xf[i] + 35 , yf[i] + 5 , 10 , 10) ; (xf[i] + 35 , yf[i] + 15 , 10 , 10) ; (xf[i] + 35 , yf[i] + 25 , 10 , 10) ; (xf[i] + 35 , yf[i] + 35 , 10 , 10) ; (xf[i] + 15 , yf[i] - 20 , 10 , 40) ; (xf[i] + 5 , yf[i] + 30 , 10 , 10) ; (xf[i] + 25 , yf[i] + 30 , 10 , 10) ; }if(opf[i] == 2) {(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; (xf[i] + 5 , yf[i] - 5 , 10 , 10) ; (xf[i] + 15 , yf[i] - 5 , 10 , 10) ; (xf[i] + 25 , yf[i] - 5 , 10 , 10) ; (xf[i] + 35 , yf[i] - 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 15 , yf[i] + 35 , 10 , 10) ; (xf[i] + 25 , yf[i] + 35 , 10 , 10) ; (xf[i] + 35 , yf[i] + 35 , 10 , 10) ; (xf[i] + 20 , yf[i] + 15 , 40 , 10) ; (xf[i] , yf[i] + 5 , 10 , 10) ;(xf[i] , yf[i] + 25 , 10 , 10) ;}if(opf[i] == 3) {(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 15 , 10 , 10) ; (xf[i] - 5 , yf[i] + 25 , 10 , 10) ; (xf[i] - 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 35 , yf[i] - 5 , 10 , 10) ; (xf[i] + 35 , yf[i] + 5 , 10 , 10) ; (xf[i] + 35 , yf[i] + 15 , 10 , 10) ; (xf[i] + 35 , yf[i] + 25 , 10 , 10) ; (xf[i] + 35 , yf[i] + 35 , 10 , 10) ; (xf[i] + 15 , yf[i] + 20 , 10 , 40) ; (xf[i] + 5 , yf[i] , 10 , 10) ;(xf[i] + 25 , yf[i] , 10 , 10) ;}if(opf[i] == 4) {(xf[i] - 5 , yf[i] - 5 , 10 , 10) ; (xf[i] + 5 , yf[i] - 5 , 10 , 10) ; (xf[i] + 15 , yf[i] - 5 , 10 , 10) ; (xf[i] + 25 , yf[i] - 5 , 10 , 10) ; (xf[i] + 35 , yf[i] - 5 , 10 , 10) ; (xf[i] - 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 5 , yf[i] + 35 , 10 , 10) ; (xf[i] + 15 , yf[i] + 35 , 10 , 10) ; (xf[i] + 25 , yf[i] + 35 , 10 , 10) ; (xf[i] + 35 , yf[i] + 35 , 10 , 10) ; (xf[i] - 20 , yf[i] + 15 , 40 , 10) ; (xf[i] + 30 , yf[i] + 5 , 10 , 10) ; (xf[i] + 30 , yf[i] + 25 , 10 , 10) ; }(dxf1[i] , dyf1[i] , 10 , 10 ) ;(dxf2[i] , dyf2[i] , 10 , 10 ) ; (dxf3[i] , dyf3[i] , 10 , 10 ) ; (dxf4[i] , dyf4[i] , 10 , 10 ) ;}}public void keyTyped(KeyEvent e) {}//键盘控制坦克的移动,发弹public void keyPressed(KeyEvent e) { color ++ ;if() == {op = 1 ;y = y - tankspeed ;dy = dy - tankspeed ;if(y <= 0) {y = y + tankspeed ;dy = dy + tankspeed ; }}if() == {op = 2 ;x = x + tankspeed ; dx = dx + tankspeed ; if(x >= 560) {x = x - tankspeed ; dx = dx - tankspeed ; }}if() == {op = 3 ;y = y + tankspeed ; dy = dy + tankspeed ;if(y >= 560) {y = y - tankspeed ; dy = dy - tankspeed ; }}if() == {op = 4 ;x = x - tankspeed ; dx = dx - tankspeed ; if(x <= 0) {x = x + tankspeed ; dx = dx + tankspeed ; }}if() == {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 ;}}() ;}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) { ("被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 ) { ("被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) {("被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 ) { ("被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) {("1击中") ;fenshu = fenshu + 100 ;xf[i] = (int)() * 560 );yf[i] = (int)() * 560 );}if(dx2>xf[i]+2 &&dx2<xf[i]+32 &&dy2 - yf[i] >-10 && dy2 - yf[i] <40 ) { ("2击中") ;fenshu = fenshu + 100 ;xf[i] = (int)() * 560 );yf[i] = (int)() * 560 );}if(dy3>yf[i]+2 && dy3< yf[i]+32 && dx3-xf[i] >-10&& dx3-xf[i]<40) {("3击中") ;fenshu = fenshu + 100 ;xf[i] = (int)() * 560 );yf[i] = (int)() * 560 );}if(dx4>xf[i]+8 &&dx4<xf[i]+38 &&dy4 - yf[i] >-10 && dy4 - yf[i] <40 ) { ("4击中") ;fenshu = fenshu + 100 ;xf[i] = (int)() * 560 );yf[i] = (int)() * 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{(20) ;}catch(Exception e) {() ;}//坦克的开火if(a % 50 == 5) {if()>{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()> {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()>{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()>{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()> {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( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{opf[i] = 4 ;}}}}if(a % 50 == 11 ) {//坦克的随机移动for (int i = 2; i<4; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{}}}}if(a % 50 == 21 ) {//坦克的随机移动for (int i = 4; i<6; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {}else{opf[i] = 4 ;}}}}if(a % 50 == 31 ) {//坦克的随机移动for (int i = 6; i<8; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{opf[i] = 4 ;}}}}if(a % 50 == 41 ) {//坦克的随机移动for (int i = 8; i<10; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{opf[i] = 4 ;}}}}//重画if(shengming<=0){//弹出player1胜利对话框(null,"你结束了!!!","Game Over !", ; //结束游戏(0) ;}() ;}}}。
vb坦克大战游戏设计
Else
Line1.X1 = w2(0).X + 20
Line1.Y1 = w2(0).Y - 30
End If
Line1.X2 = X
Line1.Y2 = Y
If Turn = True Then
Shape1.Left = Line1.X2 - Shape1.Width / 2
为了适应信息化时代的需求,各高校对大多数专业都开设了一定的计算机语言课程,有的讲授VisualBasic语言。VisualBasic以其语法简单,可视化设计,功能强大,为许多学校计算机语言课程的首选语言。
目前国内各出版了大量的VisualBasic语言教程,它们都具有同样的特点:介绍语言的语法等基本知识,再辅助一些简单的示例。学生通过学习,可能能够考一个不错的成绩,但所掌握的仍然是一些支离破碎的知识,不能将所有的知识融会贯通,遇到具体的程序设计,还是无从下手。
Shape2.Top = Line1.Y2 - Shape1.Height / 2
End If
If Turn = True Then
lblStrength.Move Shape1.Left, Shape1.Top - lblStrength.Height
Else
lblStrength.Move Shape2.Left, Shape2.Top - lblStrength.Height
Timer1.Enabled = True
End Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Python3+pygame实现的90坦克大战代码完整有演示效果
Python3+pygame实现的90坦克⼤战代码完整有演⽰效果我是⼀个典型的80后,年轻时玩过了特别多的游戏,所以这⼏天⽤Python3+pygame实现了⼀个另外⼩游戏”坦克⼤战“(其他的游戏,请翻阅我的博客)本实例代码量有些多,完整的版本在1000⾏左右(当然了如果再次优化的话会减少⼀部分)分享出来,希望能帮助到⼤家,毕竟⾃⼰做教育⾏业做了这么多年,还是教育情怀的,哈哈哈哈哈⼀、显⽰效果⼆、代码下⾯代码⽤到了⼀些素材(游戏背景⾳乐、图⽚等等),可以到我的⽹站下载,谢谢⼤家的⽀持完整代码如下(注意:为了⽅便下载以及编写更简单,没有采⽤多模块的⽅式,全部代码全部放到main.py⽂件中) """作者:it项⽬实例⽹⽹站:"""import randomimport sysimport pygame# 屏幕的宽、⾼WIDTH = 630HEIGHT = 630# 边界值BORDER_LEN = 3# 字体FONTPATH = 'resources/font/font.ttf'class Iron(pygame.sprite.Sprite):"""铁墙类"""# 定义精灵组,将所有的砖墙实例对象添加到⾥⾯group = pygame.sprite.Group()def__init__(self, position):# 调⽤⽗类的初始化⽅法,这样才能够实现必要的初始化操作super().__init__()self.image = pygame.image.load("resources/images/scene/iron.png")# 当使⽤碰撞判断⽅法时,pygame就需要知道当前要检测的物体的位置,所以这个rect属性⼀定要设置self.rect = self.image.get_rect()self.rect.topleft = position# 添加到精灵组self.group.add(self)@classmethoddef show(cls, screen):for temp in cls.group:screen.blit(temp.image, temp.rect)class Ice(pygame.sprite.Sprite):"""冰类"""# 定义精灵组,将所有的实例对象添加到⾥⾯group = pygame.sprite.Group()def__init__(self, position):# 调⽤⽗类的初始化⽅法,这样才能够实现必要的初始化操作super().__init__()# 因为是12x12的⼩图⽚,所以需要制作⼀个24x24的imageimage = pygame.Surface((24, 24))for i in range(2):for j in range(2):image.blit(pygame.image.load("resources/images/scene/ice.png"), (12 * i, 12 * j))self.image = image# 当使⽤碰撞判断⽅法时,pygame就需要知道当前要检测的物体的位置,所以这个rect属性⼀定要设置 self.rect = self.image.get_rect()self.rect.topleft = position# 添加到精灵组self.group.add(self)@classmethoddef show(cls, screen):for temp in cls.group:screen.blit(temp.image, temp.rect)class River(pygame.sprite.Sprite):"""河流类"""# 定义精灵组,将所有的实例对象添加到⾥⾯group = pygame.sprite.Group()def__init__(self, position):# 调⽤⽗类的初始化⽅法,这样才能够实现必要的初始化操作super().__init__()# 因为是12x12的⼩图⽚,所以需要制作⼀个24x24的imageimage = pygame.Surface((24, 24))for i in range(2):for j in range(2):image.blit(pygame.image.load("resources/images/scene/river1.png"), (12 * i, 12 * j))self.image = image# 当使⽤碰撞判断⽅法时,pygame就需要知道当前要检测的物体的位置,所以这个rect属性⼀定要设置 self.rect = self.image.get_rect()self.rect.topleft = position# 添加到精灵组self.group.add(self)@classmethoddef show(cls, screen):for temp in cls.group:screen.blit(temp.image, temp.rect)class Tree(pygame.sprite.Sprite):"""树类"""# 定义精灵组,将所有的实例对象添加到⾥⾯group = pygame.sprite.Group()def__init__(self, position):# 调⽤⽗类的初始化⽅法,这样才能够实现必要的初始化操作super().__init__()# 因为是12x12的⼩图⽚,所以需要制作⼀个24x24的imageimage = pygame.Surface((24, 24))for i in range(2):for j in range(2):image.blit(pygame.image.load("resources/images/scene/tree.png"), (12 * i, 12 * j))self.image = image# 当使⽤碰撞判断⽅法时,pygame就需要知道当前要检测的物体的位置,所以这个rect属性⼀定要设置 self.rect = self.image.get_rect()self.rect.topleft = position# 添加到精灵组self.group.add(self)@classmethoddef show(cls, screen):for temp in cls.group:screen.blit(temp.image, temp.rect)class Brick(pygame.sprite.Sprite):"""砖墙类"""# 定义精灵组,将所有的砖墙实例对象添加到⾥⾯group = pygame.sprite.Group()def__init__(self, position):# 调⽤⽗类的初始化⽅法,这样才能够实现必要的初始化操作super().__init__()self.image = pygame.image.load("resources/images/scene/brick.png")# 当使⽤碰撞判断⽅法时,pygame就需要知道当前要检测的物体的位置,所以这个rect属性⼀定要设置self.rect = self.image.get_rect()self.rect.topleft = position# 添加到精灵组self.group.add(self)@classmethoddef show(cls, screen):for temp in cls.group:screen.blit(temp.image, temp.rect)class Bullet(pygame.sprite.Sprite):"""⼦弹类"""# 定义精灵组,将所有的砖墙实例对象添加到⾥⾯group = pygame.sprite.Group()group_enemy = pygame.sprite.Group()def__init__(self, _type, direction, position):super().__init__()# ⼦弹图⽚if direction == "up":image_path = "resources/images/bullet/bullet_up.png"elif direction == "down":image_path = "resources/images/bullet/bullet_down.png"elif direction == "left":image_path = "resources/images/bullet/bullet_left.png"elif direction == "right":image_path = "resources/images/bullet/bullet_right.png"self.image = pygame.image.load(image_path)# ⼦弹位置self.rect = self.image.get_rect()self.rect.center = position # 设置⼦弹的初始位置的中⼼点# ⼦弹⽅向self.direction = direction# ⼦弹移动速度self.speed = 8# 将⼦弹添加到精灵组if _type == "player":self.group.add(self)else:self.group_enemy.add(self)@classmethoddef auto_move(cls):for temp in cls.group:if temp.rect.x < BORDER_LEN or temp.rect.x > WIDTH - BORDER_LEN or temp.rect.y < BORDER_LEN or temp.rect.y > HEIGHT - BORDER_LEN: cls.group.remove(temp)print("⼦弹超出边界,移除⼦弹")continueif temp.direction == "up":temp.rect = temp.rect.move((0, -temp.speed))elif temp.direction == "down":temp.rect = temp.rect.move((0, temp.speed))elif temp.direction == "left":temp.rect = temp.rect.move((-temp.speed, 0))elif temp.direction == "right":temp.rect = temp.rect.move((temp.speed, 0))for temp in cls.group_enemy:if temp.rect.x < BORDER_LEN or temp.rect.x > WIDTH - BORDER_LEN or temp.rect.y < BORDER_LEN or temp.rect.y > HEIGHT - BORDER_LEN: cls.group_enemy.remove(temp)print("⼦弹超出边界,移除⼦弹")continueif temp.direction == "up":temp.rect = temp.rect.move((0, -temp.speed))elif temp.direction == "down":temp.rect = temp.rect.move((0, temp.speed))elif temp.direction == "left":temp.rect = temp.rect.move((-temp.speed, 0))elif temp.direction == "right":temp.rect = temp.rect.move((temp.speed, 0))# ⼦弹碰砖墙(如果相碰,那么就移除当前⼦弹以及砖墙)pygame.sprite.groupcollide(cls.group, Brick.group, True, True)pygame.sprite.groupcollide(cls.group_enemy, Brick.group, True, True)# ⼦弹碰铁墙(如果相碰,那么只移除⼦弹)for bullet in cls.group:if pygame.sprite.spritecollide(bullet, Iron.group, False, None):cls.group.remove(bullet)for bullet in cls.group_enemy:if pygame.sprite.spritecollide(bullet, Iron.group, False, None):cls.group_enemy.remove(bullet)@classmethoddef show(cls, screen):"""显⽰⼦弹"""for temp in cls.group:screen.blit(temp.image, temp.rect)for temp in cls.group_enemy:screen.blit(temp.image, temp.rect)@classmethoddef move_and_show(cls, screen):"""移动、显⽰⼦弹"""cls.auto_move()cls.show(screen)class PlayerTank(pygame.sprite.Sprite):"""我⽅坦克类"""# 定义类属性,存储我⽅坦克(如果是单⼈模式就只有1个,如果是双⼈模式就有2个)player_group = list()# 定义精灵组,⽤来碰撞等判断group = pygame.sprite.Group()def__init__(self, player, top_left):"""实现初始化功能"""# 调⽤⽗类的初始化⽅法,这样才能够实现必要的初始化操作super().__init__()# 坦克的图⽚image_path = "resources/images/playerTank/tank_T1_0.png"if player == "player1"else"resources/images/playerTank/tank_T2_0.png" self.tank_all_image = pygame.image.load(image_path).convert_alpha()self.image = self.tank_all_image.subsurface((0, 0), (48, 48))# 当使⽤碰撞判断⽅法时,pygame就需要知道当前要检测的物体的位置,所以这个rect属性⼀定要设置self.rect = self.image.get_rect()self.rect.topleft = top_left# 记录初始位置,以便在被击中后能够重新在默认位置出现self.origin_position = top_left# 定义移动的步长self.step_length = 8# 坦克的默认⽅向self.direction = "up"# 默认朝上# 移动缓冲, ⽤于避免坦克连续移动过快导致不⽅便调整位置self.move_cache_time = 4self.move_cache_count = 0# 坦克轮⼦转动效果self.switch_count = 0self.switch_time = 2self.switch_image_index = Falseself.image_postion_index = 0# 发射⼦弹的间隔self.is_bullet_cooling = False # 如果是第⼀次发射⼦弹,则不在冷却时间内,可以正常发射self.bullet_cooling_count = 0self.bullet_cooling_time = 30# 我⽅坦克⽣命次数self.life_num = 3# 标记此坦克是否显⽰self.is_show_flag = True# 将当前对象添加到类属性中,这样就可以通过类对象访问到我⽅坦克self.__class__.player_group.append(self) # 或者self.player_group.append(self)也是可以的# 添加到精灵组self.group.add(self)def update_direction(self):"""更新坦克的朝向"""if self.direction == 'up':self.image = self.tank_all_image.subsurface((0, 0), (48, 48))self.image_postion_index = 0elif self.direction == 'down':self.image = self.tank_all_image.subsurface((0, 48), (48, 48))self.image_postion_index = 48elif self.direction == 'left':self.image = self.tank_all_image.subsurface((0, 96), (48, 48))self.image_postion_index = 96elif self.direction == 'right':self.image = self.tank_all_image.subsurface((0, 144), (48, 48))self.image_postion_index = 144def move(self, direction, group_list):"""根据键盘调整坦克⽅向,然后移动"""# 如果要移动的⽅向与当前坦克的朝向不同,则先调整朝向if self.direction != direction:self.direction = directionself.update_direction()return# 移动缓冲self.move_cache_count += 1if self.move_cache_count < self.move_cache_time:returnelse:self.move_cache_count = 0# 移动坦克# 复制⼀份当前玩家坦克的坐标,如果碰到障碍物之后,可以进⾏恢复rect_ori = self.rectif direction == "up":self.rect = self.rect.move((0, -self.step_length))elif direction == "down":self.rect = self.rect.move((0, self.step_length))elif direction == "left":self.rect = self.rect.move((-self.step_length, 0))elif direction == "right":self.rect = self.rect.move((self.step_length, 0))# 检测碰撞"砖墙"、"铁墙"、"冰"、"河流"。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
If Lb.Top >= 7600 Then
Lb.Enabled = False
La.Enabled = False
Else
La.Top = La.Top + 100
Lb.Top = Lb.Top + 100
End If
ElseIf keyascii = 8 Then
End
End If
Loop
Lc.Visible = False
Timer4.Enabled = False
End Sub
Lc.Top = La.Top + 300
Lc.Left = La.Left - 900
Lc.Visible = True
Timer1.Enabled = False
Timer2.Enabled = True
Timer3.Enabled = False
Timer4.Enabled = False
ElseIf Lb.Top - La.Top = 900 And Lb.Left - La.Left = 300 Then
Private Sub Form_Load()
La.Top = 4000
La.Left = 3000
La.Height = 800
La.Width = 900
Lb.Top = 4300
Lb.Left = 3900
Lb.Height = 200
Lb.Width = 900
Lc.Top = 4300
Lc.Left = 4560
Ld.Visible = False
Lc.Visible = False
End If
Loop
Lc.Visible = False
Timer1.Enabled = False
End Sub
Private Sub Timer2_Timer()
Do While Lc.Left > 0
Lc.Left = Lc.Left - 2
End If
End Sub
Private Sub Timer1_Timer()
Do While Lc.Top > 0
Lc.Top = Lc.Top - 2
Lc.Left = Lc.Left
If Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top < Ld.Top + Ld.Height Then
Lc.Top = Lc.Top
If Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top < Ld.Top + Ld.Height Then
Ld.Visible = False
Lc.Visible = False
La.Height = 800
La.Width = 900
Lb.Width = 900
Lb.Height = 200
If Lb.Left >= 8700 Then
Lb.Enabled = False
La.Enabled = False
Else
La.Left = La.Left + 100
Lb.Left = Lb.Left + 100
Ld.Visible = False
Lc.Visible = False
End If
Loop
Lc.Visible = False
Timer3.Enabled = False
End Sub
Private Sub Timer4_Timer()
Do While Lc.Left < 9750
Lc.Left = Lc.Left + 2
End If
Loop
Lc.Visible = False
Timer2.Enabled = False
End Sub
Private Sub Timer3_Timer()
Do While Lc.Top < 8880
Lc.Top = Lc.Top + 2
Lc.Left = Lc.Left
If Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top < Ld.Top + Ld.Height Then
If Lb.Top <= 0 Then
Lb.Enabled = False
La.Enabled = False
Else
La.Top = La.Top - 100
Lb.Top = Lb.Top - 100
End If
ElseIf keyascii = 97 Then
La.Enabled = True
Lb.Enabled = True
Lc.Height = 200
Lc.Width = 200
End Sub
Private Sub Form_keypress(keyascii As Integer)
If keyascii = 106 Then
La.Enabled = False
Lb.Enabled = False
If La.Top - Lb.Top = 900 And Lb.Left - La.Left = 300 Then
Lb.Left = La.Left - 900
Lb.Top = La.Top + 300
La.Height = 800
La.Width = 900
Lb.Width = 900
Lb.Height = 200
If Lb.Left <= 0 Then
Lb.Enabled = False
La.Enabled = False
Lc.Top = Lc.Top
If Lc.Left > Ld.Left And Lc.Left < Ld.Left + Ld.Width And Lc.Top > Ld.Top And Lc.Top < Ld.Top + Ld.Height Then
Ld.Visible = False
Lc.Visible = False
End If
ElseIf keyascii = 115 Then
La.Enabled = True
Lb.Enabled = True
Lb.Left = La.Left + 300
Lb.Top = La.Top + 900
La.Height = 900
La.Width = 800
Lb.Width = 200
Lc.Top = La.Top + 1600
Lc.Left = La.Left + 300
Lc.Visible = True
Timer1.Enabled = False
Timer2.Enabled = False
Timer3.Enabled = True
Timer4.Enabled = False
ElseIf Lb.Left - La.Left = 900 And Lb.Top - La.Top = 300 Then
Lc.Top = La.Top - 900
Lc.Left = La.Left + 300
Lc.Visible = True
Timer1.Enabled = True
Timer2.Enabled = False
Timer3.Enabled = False
Timer4.Enabled = False
ElseIf La.Left - Lb.Left = 900 And Lb.Top - La.Top = 300 Then
ElseIf keyascii = 119 Then
La.Enabled = True
Lb.Enabled = True
Lb.Left = La.Left + 300
Lb.Top = La.Top - 900
La.Height = 900
La.Width = 800
Lb.Width = 200
Lb.Height = 900
Lc.Top = La.Top + 300
Lc.Left = La.Left + 1600
Lc.Visible = True
Timer1.Enabled = False
Timer2.Enabled = False
Timer3.Biblioteka nabled = FalseTimer4.Enabled = True
End If
Else
La.Left = La.Left - 100
Lb.Left = Lb.Left - 100
End If
ElseIf keyascii = 100 Then
La.Enabled = True
Lb.Enabled = True
Lb.Left = La.Left + 900
Lb.Top = La.Top + 300