坦克大战程序源代码
python+pygame实现坦克大战小游戏的示例代码(可以自定义子弹速度)
python+pygame实现坦克⼤战⼩游戏的⽰例代码(可以⾃定义⼦弹速度)python+pygame实现坦克⼤战⼩游戏—可以⾃定义⼦弹速度:运⾏环境–python3.7、pycharm;源码需要请:点赞留⾔邮箱;正常版⼦弹速度:普通速度版加速版⼦弹速度:⼦弹加速版另外还有多种道具,⽀持两⼈⼀起玩。
main()⽅法如下:def main():pygame.init()pygame.mixer.init()resolution = 630, 630screen = pygame.display.set_mode(resolution)pygame.display.set_caption("Tank Game ")# 加载图⽚,⾳乐,⾳效.background_image = pygame.image.load(r"..\image\background.png")home_image = pygame.image.load(r"..\image\home.png")home_destroyed_image = pygame.image.load(r"..\image\home_destroyed.png")bang_sound = pygame.mixer.Sound(r"..\music\bang.wav")bang_sound.set_volume(1)fire_sound = pygame.mixer.Sound(r"..\music\Gunfire.wav")start_sound = pygame.mixer.Sound(r"..\music\start.wav")start_sound.play()# 定义精灵组:坦克,我⽅坦克,敌⽅坦克,敌⽅⼦弹allTankGroup = pygame.sprite.Group()mytankGroup = pygame.sprite.Group()allEnemyGroup = pygame.sprite.Group()redEnemyGroup = pygame.sprite.Group()greenEnemyGroup = pygame.sprite.Group()otherEnemyGroup = pygame.sprite.Group()enemyBulletGroup = pygame.sprite.Group()# 创建地图bgMap = wall.Map()# 创建⾷物/道具但不显⽰prop = food.Food()# 创建我⽅坦克myTank_T1 = myTank.MyTank(1)allTankGroup.add(myTank_T1)mytankGroup.add(myTank_T1)myTank_T2 = myTank.MyTank(2)allTankGroup.add(myTank_T2)mytankGroup.add(myTank_T2)# 创建敌⽅坦克for i in range(1, 4):enemy = enemyTank.EnemyTank(i)allTankGroup.add(enemy)allEnemyGroup.add(enemy)if enemy.isred == True:redEnemyGroup.add(enemy)continueif enemy.kind == 3:greenEnemyGroup.add(enemy)continueotherEnemyGroup.add(enemy)# 敌军坦克出现动画appearance_image = pygame.image.load(r"..\image\appear.png").convert_alpha()appearance = []appearance.append(appearance_image.subsurface(( 0, 0), (48, 48)))appearance.append(appearance_image.subsurface((48, 0), (48, 48)))appearance.append(appearance_image.subsurface((96, 0), (48, 48)))# ⾃定义事件# 创建敌⽅坦克延迟200DELAYEVENT = EREVENTpygame.time.set_timer(DELAYEVENT, 200)# 创建敌⽅⼦弹延迟1000ENEMYBULLETNOTCOOLINGEVENT = EREVENT + 1 pygame.time.set_timer(ENEMYBULLETNOTCOOLINGEVENT, 1000)# 创建我⽅⼦弹延迟200MYBULLETNOTCOOLINGEVENT = EREVENT + 2pygame.time.set_timer(MYBULLETNOTCOOLINGEVENT, 200)# 敌⽅坦克静⽌8000NOTMOVEEVENT = EREVENT + 3pygame.time.set_timer(NOTMOVEEVENT, 8000)delay = 100moving = 0movdir = 0moving2 = 0movdir2 = 0enemyNumber = 3enemyCouldMove = Trueswitch_R1_R2_image = TruehomeSurvive = Truerunning_T1 = Truerunning_T2 = Trueclock = pygame.time.Clock()while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()# 我⽅⼦弹冷却事件if event.type == MYBULLETNOTCOOLINGEVENT:myTank_T1.bulletNotCooling = True# 敌⽅⼦弹冷却事件if event.type == ENEMYBULLETNOTCOOLINGEVENT:for each in allEnemyGroup:each.bulletNotCooling = True# 敌⽅坦克静⽌事件if event.type == NOTMOVEEVENT:enemyCouldMove = True# 创建敌⽅坦克延迟if event.type == DELAYEVENT:if enemyNumber < 4:enemy = enemyTank.EnemyTank()if pygame.sprite.spritecollide(enemy, allTankGroup, False, None):breakallEnemyGroup.add(enemy)allTankGroup.add(enemy)enemyNumber += 1if enemy.isred == True:redEnemyGroup.add(enemy)elif enemy.kind == 3:greenEnemyGroup.add(enemy)else:otherEnemyGroup.add(enemy)if event.type == pygame.KEYDOWN:if event.key == pygame.K_c and pygame.KMOD_CTRL:pygame.quit()sys.exit()if event.key == pygame.K_e:myTank_T1.levelUp()if event.key == pygame.K_q:myTank_T1.levelDown()if event.key == pygame.K_3:myTank_T1.levelUp()myTank_T1.levelUp()myTank_T1.level = 3if event.key == pygame.K_2:if myTank_T1.speed == 3:myTank_T1.speed = 24else:myTank_T1.speed = 3if event.key == pygame.K_1:for x, y in [(11,23),(12,23),(13,23),(14,23),(11,24),(14,24),(11,25),(14,25)]: bgMap.brick = wall.Brick()bgMap.brick.rect.left, bgMap.brick.rect.top = 3 + x * 24, 3 + y * 24bgMap.brickGroup.add(bgMap.brick)if event.key == pygame.K_4:for x, y in [(11,23),(12,23),(13,23),(14,23),(11,24),(14,24),(11,25),(14,25)]:bgMap.iron = wall.Iron()bgMap.iron.rect.left, bgMap.iron.rect.top = 3 + x * 24, 3 + y * 24bgMap.ironGroup.add(bgMap.iron)# 检查⽤户的键盘操作key_pressed = pygame.key.get_pressed()# 玩家⼀的移动操作if moving:moving -= 1if movdir == 0:allTankGroup.remove(myTank_T1)if myTank_T1.moveUp(allTankGroup, bgMap.brickGroup, bgMap.ironGroup): moving += 1allTankGroup.add(myTank_T1)running_T1 = Trueif movdir == 1:allTankGroup.remove(myTank_T1)if myTank_T1.moveDown(allTankGroup, bgMap.brickGroup, bgMap.ironGroup): moving += 1allTankGroup.add(myTank_T1)running_T1 = Trueif movdir == 2:allTankGroup.remove(myTank_T1)if myTank_T1.moveLeft(allTankGroup, bgMap.brickGroup, bgMap.ironGroup): moving += 1allTankGroup.add(myTank_T1)running_T1 = Trueif movdir == 3:allTankGroup.remove(myTank_T1)if myTank_T1.moveRight(allTankGroup, bgMap.brickGroup, bgMap.ironGroup): moving += 1allTankGroup.add(myTank_T1)running_T1 = Trueif not moving:if key_pressed[pygame.K_w]:moving = 7movdir = 0running_T1 = TrueallTankGroup.remove(myTank_T1)if myTank_T1.moveUp(allTankGroup, bgMap.brickGroup, bgMap.ironGroup): moving = 0allTankGroup.add(myTank_T1)elif key_pressed[pygame.K_s]:moving = 7movdir = 1running_T1 = TrueallTankGroup.remove(myTank_T1)if myTank_T1.moveDown(allTankGroup, bgMap.brickGroup, bgMap.ironGroup): moving = 0allTankGroup.add(myTank_T1)elif key_pressed[pygame.K_a]:moving = 7movdir = 2running_T1 = TrueallTankGroup.remove(myTank_T1)if myTank_T1.moveLeft(allTankGroup, bgMap.brickGroup, bgMap.ironGroup): moving = 0allTankGroup.add(myTank_T1)elif key_pressed[pygame.K_d]:moving = 7movdir = 3running_T1 = TrueallTankGroup.remove(myTank_T1)if myTank_T1.moveRight(allTankGroup, bgMap.brickGroup, bgMap.ironGroup): moving = 0allTankGroup.add(myTank_T1)if key_pressed[pygame.K_j]:if not myTank_T1.bullet.life and myTank_T1.bulletNotCooling:fire_sound.play()myTank_T1.shoot()myTank_T1.bulletNotCooling = False# 玩家⼆的移动操作if moving2:moving2 -= 1if movdir2 == 0:allTankGroup.remove(myTank_T2)myTank_T2.moveUp(allTankGroup, bgMap.brickGroup, bgMap.ironGroup) allTankGroup.add(myTank_T2)running_T2 = Trueif movdir2 == 1:allTankGroup.remove(myTank_T2)myTank_T2.moveDown(allTankGroup, bgMap.brickGroup, bgMap.ironGroup) allTankGroup.add(myTank_T2)running_T2 = Trueif movdir2 == 2:allTankGroup.remove(myTank_T2)myTank_T2.moveLeft(allTankGroup, bgMap.brickGroup, bgMap.ironGroup) allTankGroup.add(myTank_T2)running_T2 = Trueif movdir2 == 3:allTankGroup.remove(myTank_T2)myTank_T2.moveRight(allTankGroup, bgMap.brickGroup, bgMap.ironGroup) allTankGroup.add(myTank_T2)running_T2 = Trueif not moving2:if key_pressed[pygame.K_UP]:allTankGroup.remove(myTank_T2)myTank_T2.moveUp(allTankGroup, bgMap.brickGroup, bgMap.ironGroup) allTankGroup.add(myTank_T2)moving2 = 7movdir2 = 0running_T2 = Trueelif key_pressed[pygame.K_DOWN]:allTankGroup.remove(myTank_T2)myTank_T2.moveDown(allTankGroup, bgMap.brickGroup, bgMap.ironGroup) allTankGroup.add(myTank_T2)moving2 = 7movdir2 = 1running_T2 = Trueelif key_pressed[pygame.K_LEFT]:allTankGroup.remove(myTank_T2)myTank_T2.moveLeft(allTankGroup, bgMap.brickGroup, bgMap.ironGroup) allTankGroup.add(myTank_T2)moving2 = 7movdir2 = 2running_T2 = Trueelif key_pressed[pygame.K_RIGHT]:allTankGroup.remove(myTank_T2)myTank_T2.moveRight(allTankGroup, bgMap.brickGroup, bgMap.ironGroup) allTankGroup.add(myTank_T2)moving2 = 7movdir2 = 3running_T2 = Trueif key_pressed[pygame.K_KP0]:if not myTank_T2.bullet.life:# fire_sound.play()myTank_T2.shoot()# 画背景screen.blit(background_image, (0, 0))# 画砖块for each in bgMap.brickGroup:screen.blit(each.image, each.rect)# 花⽯头for each in bgMap.ironGroup:screen.blit(each.image, each.rect)# 画homeif homeSurvive:screen.blit(home_image, (3 + 12 * 24, 3 + 24 * 24))else:screen.blit(home_destroyed_image, (3 + 12 * 24, 3 + 24 * 24))# 画我⽅坦克1if not (delay % 5):switch_R1_R2_image = not switch_R1_R2_imageif switch_R1_R2_image and running_T1:screen.blit(myTank_T1.tank_R0, (myTank_T1.rect.left, myTank_T1.rect.top)) running_T1 = Falseelse:screen.blit(myTank_T1.tank_R1, (myTank_T1.rect.left, myTank_T1.rect.top)) # 画我⽅坦克2if switch_R1_R2_image and running_T2:screen.blit(myTank_T2.tank_R0, (myTank_T2.rect.left, myTank_T2.rect.top))running_T2 = Falseelse:screen.blit(myTank_T2.tank_R1, (myTank_T2.rect.left, myTank_T2.rect.top))# 画敌⽅坦克for each in allEnemyGroup:# 判断5⽑钱特效是否播放if each.flash:# 判断画左动作还是右动作if switch_R1_R2_image:screen.blit(each.tank_R0, (each.rect.left, each.rect.top))if enemyCouldMove:allTankGroup.remove(each)each.move(allTankGroup, bgMap.brickGroup, bgMap.ironGroup)allTankGroup.add(each)else:screen.blit(each.tank_R1, (each.rect.left, each.rect.top))if enemyCouldMove:allTankGroup.remove(each)each.move(allTankGroup, bgMap.brickGroup, bgMap.ironGroup)allTankGroup.add(each)else:# 播放5⽑钱特效if each.times > 0:each.times -= 1if each.times <= 10:screen.blit(appearance[2], (3 + each.x * 12 * 24, 3))elif each.times <= 20:screen.blit(appearance[1], (3 + each.x * 12 * 24, 3))elif each.times <= 30:screen.blit(appearance[0], (3 + each.x * 12 * 24, 3))elif each.times <= 40:screen.blit(appearance[2], (3 + each.x * 12 * 24, 3))elif each.times <= 50:screen.blit(appearance[1], (3 + each.x * 12 * 24, 3))elif each.times <= 60:screen.blit(appearance[0], (3 + each.x * 12 * 24, 3))elif each.times <= 70:screen.blit(appearance[2], (3 + each.x * 12 * 24, 3))elif each.times <= 80:screen.blit(appearance[1], (3 + each.x * 12 * 24, 3))elif each.times <= 90:screen.blit(appearance[0], (3 + each.x * 12 * 24, 3))if each.times == 0:each.flash = True# 绘制我⽅⼦弹1if myTank_T1.bullet.life:myTank_T1.bullet.move()screen.blit(myTank_T1.bullet.bullet, myTank_T1.bullet.rect)# ⼦弹碰撞⼦弹for each in enemyBulletGroup:if each.life:if pygame.sprite.collide_rect(myTank_T1.bullet, each):myTank_T1.bullet.life = Falseeach.life = Falsepygame.sprite.spritecollide(myTank_T1.bullet, enemyBulletGroup, True, None) # ⼦弹碰撞敌⽅坦克if pygame.sprite.spritecollide(myTank_T1.bullet, redEnemyGroup, True, None):prop.change()bang_sound.play()enemyNumber -= 1myTank_T1.bullet.life = Falseelif pygame.sprite.spritecollide(myTank_T1.bullet,greenEnemyGroup, False, None): for each in greenEnemyGroup:if pygame.sprite.collide_rect(myTank_T1.bullet, each):if each.life == 1:pygame.sprite.spritecollide(myTank_T1.bullet,greenEnemyGroup, True, None) bang_sound.play()enemyNumber -= 1elif each.life == 2:each.life -= 1each.tank = each.enemy_3_0elif each.life == 3:each.life -= 1each.tank = each.enemy_3_2myTank_T1.bullet.life = Falseelif pygame.sprite.spritecollide(myTank_T1.bullet, otherEnemyGroup, True, None): bang_sound.play()enemyNumber -= 1myTank_T1.bullet.life = False#if pygame.sprite.spritecollide(myTank_T1.bullet, allEnemyGroup, True, None):# bang_sound.play()# enemyNumber -= 1# myTank_T1.bullet.life = False# ⼦弹碰撞 brickGroupif pygame.sprite.spritecollide(myTank_T1.bullet, bgMap.brickGroup, True, None):myTank_T1.bullet.life = FalsemyTank_T1.bullet.rect.left, myTank_T1.bullet.rect.right = 3 + 12 * 24, 3 + 24 * 24 # ⼦弹碰撞 brickGroupif myTank_T1.bullet.strong:if pygame.sprite.spritecollide(myTank_T1.bullet, bgMap.ironGroup, True, None):myTank_T1.bullet.life = FalsemyTank_T1.bullet.rect.left, myTank_T1.bullet.rect.right = 3 + 12 * 24, 3 + 24 * 24 else:if pygame.sprite.spritecollide(myTank_T1.bullet, bgMap.ironGroup, False, None): myTank_T1.bullet.life = FalsemyTank_T1.bullet.rect.left, myTank_T1.bullet.rect.right = 3 + 12 * 24, 3 + 24 * 24 # 绘制我⽅⼦弹2if myTank_T2.bullet.life:myTank_T2.bullet.move()screen.blit(myTank_T2.bullet.bullet, myTank_T2.bullet.rect)# ⼦弹碰撞敌⽅坦克if pygame.sprite.spritecollide(myTank_T2.bullet, allEnemyGroup, True, None):bang_sound.play()enemyNumber -= 1myTank_T2.bullet.life = False# ⼦弹碰撞 brickGroupif pygame.sprite.spritecollide(myTank_T2.bullet, bgMap.brickGroup, True, None):myTank_T2.bullet.life = FalsemyTank_T2.bullet.rect.left, myTank_T2.bullet.rect.right = 3 + 12 * 24, 3 + 24 * 24 # ⼦弹碰撞 brickGroupif myTank_T2.bullet.strong:if pygame.sprite.spritecollide(myTank_T2.bullet, bgMap.ironGroup, True, None):myTank_T2.bullet.life = FalsemyTank_T2.bullet.rect.left, myTank_T2.bullet.rect.right = 3 + 12 * 24, 3 + 24 * 24 else:if pygame.sprite.spritecollide(myTank_T2.bullet, bgMap.ironGroup, False, None): myTank_T2.bullet.life = FalsemyTank_T2.bullet.rect.left, myTank_T2.bullet.rect.right = 3 + 12 * 24, 3 + 24 * 24 # 绘制敌⼈⼦弹for each in allEnemyGroup:# 如果⼦弹没有⽣命,则赋予⼦弹⽣命if not each.bullet.life and each.bulletNotCooling and enemyCouldMove:enemyBulletGroup.remove(each.bullet)each.shoot()enemyBulletGroup.add(each.bullet)each.bulletNotCooling = False# 如果5⽑钱特效播放完毕并且⼦弹存活则绘制敌⽅⼦弹if each.flash:if each.bullet.life:# 如果敌⼈可以移动if enemyCouldMove:each.bullet.move()screen.blit(each.bullet.bullet, each.bullet.rect)# ⼦弹碰撞我⽅坦克if pygame.sprite.collide_rect(each.bullet, myTank_T1):bang_sound.play()myTank_T1.rect.left, myTank_T1.rect.top = 3 + 8 * 24, 3 + 24 * 24each.bullet.life = Falsemoving = 0 # 重置移动控制参数for i in range(myTank_T1.level+1):myTank_T1.levelDown()if pygame.sprite.collide_rect(each.bullet, myTank_T2):bang_sound.play()myTank_T2.rect.left, myTank_T2.rect.top = 3 + 16 * 24, 3 + 24 * 24each.bullet.life = False# ⼦弹碰撞 brickGroupif pygame.sprite.spritecollide(each.bullet, bgMap.brickGroup, True, None):each.bullet.life = False# ⼦弹碰撞 ironGroupif each.bullet.strong:if pygame.sprite.spritecollide(each.bullet, bgMap.ironGroup, True, None):each.bullet.life = Falseelse:if pygame.sprite.spritecollide(each.bullet, bgMap.ironGroup, False, None):each.bullet.life = False# 最后画⾷物/道具if prop.life:screen.blit(prop.image, prop.rect)# 我⽅坦克碰撞⾷物/道具if pygame.sprite.collide_rect(myTank_T1, prop):if prop.kind == 1: # 敌⼈全毁for each in allEnemyGroup:if pygame.sprite.spritecollide(each, allEnemyGroup, True, None):bang_sound.play()enemyNumber -= 1prop.life = Falseif prop.kind == 2: # 敌⼈静⽌enemyCouldMove = Falseprop.life = Falseif prop.kind == 3: # ⼦弹增强myTank_T1.bullet.strong = Trueprop.life = Falseif prop.kind == 4: # 家得到保护for x, y in [(11,23),(12,23),(13,23),(14,23),(11,24),(14,24),(11,25),(14,25)]:bgMap.iron = wall.Iron()bgMap.iron.rect.left, bgMap.iron.rect.top = 3 + x * 24, 3 + y * 24bgMap.ironGroup.add(bgMap.iron)prop.life = Falseif prop.kind == 5: # 坦克⽆敌prop.life = Falsepassif prop.kind == 6: # 坦克升级myTank_T1.levelUp()prop.life = Falseif prop.kind == 7: # 坦克⽣命+1myTank_T1.life += 1prop.life = False# 延迟delay -= 1if not delay:delay = 100pygame.display.flip()clock.tick(60)总结到此这篇关于python+pygame实现坦克⼤战⼩游戏---可以⾃定义⼦弹速度的⽂章就介绍到这了,更多相关python+pygame实现坦克⼤战⼩游戏内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
坦克大战源码
坦克大战源码根据韩顺平老师视频所作/**坦克大战4.0* 防重叠*/package com.TankGame5;import java.awt.*;import javax.imageio.ImageIO;import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.File;import java.io.IOException;import java.util.Vector;public class MyTankGame5 extends JFrame implements ActionListener{//提示面板MyStartPanel msp=null;//游戏面板MyPanel mp=null;//游戏菜单//开始游戏JMenuBar jmb=null;JMenu jm1=null;//开始游戏JMenuItem jmi1=null;//退出游戏JMenuItem jmi2=null;//存盘退出JMenuItem jmi3=null;//继续上一局JMenuItem jmi4=null;public static void main(String[] args) {// TODO Auto-generated method stubMyTankGame5 bn=new MyTankGame5(); }//构造函数public MyTankGame5(){//创建菜单栏选项jmb=new JMenuBar();jm1=new JMenu("游戏(G)");//创建快捷方式jm1.setMnemonic('G');jmi1=new JMenuItem("开始新游戏(N)");jmi1.setMnemonic('N');//注册监听jmi1jmi1.addActionListener(this);jmi1.setActionCommand("newgame");jmi2=new JMenuItem("退出该局游戏(Q)");jmi2.setMnemonic('Q');//注册监听jmi2jmi2.addActionListener(this);jmi2.setActionCommand("exit");jmi3=new JMenuItem("存盘退出游戏(C)");jmi3.setMnemonic('C');//注册监听jmi3jmi3.addActionListener(this);jmi3.setActionCommand("saveExit");jmi4=new JMenuItem("继续上一局(R)");jmi4.setMnemonic('R');//注册监听jmi4jmi4.addActionListener(this);jmi4.setActionCommand("continue");jm1.add(jmi1);jm1.add(jmi4);//添加的顺序就是菜单的顺序jm1.add(jmi3);jm1.add(jmi2);jmb.add(jm1);this.setJMenuBar(jmb);//先启动提示框msp=new MyStartPanel();this.add(msp);Thread t1=new Thread(msp);t1.start();// mp=new MyPanel();// this.add(mp);// //注册监听// this.addKeyListener(mp);//// //启动mp线程// Thread t2=new Thread(mp);// t2.start();//窗口大小this.setSize(MyPanel.bx1+230,MyPanel.by1+150);this.setTitle("坦克横行");ImageIcon icon = new ImageIcon("Images/yan.png");this.setIconImage(icon.getImage());this.setLocation(250,150);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}@Overridepublic void actionPerformed(ActionEvent arg0) {// TODO Auto-generated method stubif(arg0.getActionCommand().equals("newgame")){//System.out.println("英雄的到来");//创建战场mp=new MyPanel("newgame");this.add(mp);//注册监听this.addKeyListener(mp);//启动mp线程Thread t2=new Thread(mp);t2.start();this.remove(msp);this.setVisible(true);}//简单退出else if(arg0.getActionCommand().equals("exit")) {//用户点击退出//保存击毁的敌人Recorder.keepRecording();System.exit(0);}//存盘退出处理else if(arg0.getActionCommand().equals("saveExit")) {//System.out.print("111");//获取当前值Recorder.setEts(mp.ets);//保存击毁的敌人和敌人的坐标Recorder.keepRecAndEnemyTank();//退出System.exit(0);}//继续上一局else if(arg0.getActionCommand().equals("continue")) {//创建战场mp=new MyPanel("continue");this.add(mp);//注册监听this.addKeyListener(mp);//启动mp线程Thread t2=new Thread(mp);t2.start();this.remove(msp);this.setVisible(true);}}}//开始提示面板class MyStartPanel extends JPanel implements Runnable{int times=0;public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, MyPanel.bx1, MyPanel.by1);if(times%2==0&×<=30){//提示信息Font myFont=new Font("华文新魏",Font.BOLD,30);g.setFont(myFont);g.setColor(Color.YELLOW);g.drawString("READY? GO!", 100, 120);}}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(500);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}times++;//重画闪烁效果this.repaint();}}}//我的面板class MyPanel extends JPanel implements KeyListener,Runnable {static int h=300;//坦克初始位置static int z=200;//暂停开始开关static int power=2;//背景区域大小static int bx1=400;static int by1=300;//声音控制static int audio=0;//定义一个我的坦克Hero hero=null;//定义地方的坦克组Vector<EnemyTank> ets=new Vector<EnemyTank>();static int ensize=10;//敌人个数//定义炸弹集合Vector<Bomb> bombs=new Vector<Bomb>();//信息集合Vector<Node> nodes=new V ector<Node>();//定义2个图片,一起组成爆炸效果Image image1=null;Image image2=null;Image image3=null;//构造函数public MyPanel(String flag){//恢复记录Recorder.getRecording();//播放声音AePlayWave ap=new AePlayWave("D:\\CHEN\\ks.wav");ap.start();//构造我的坦克hero=new Hero(h,z);//构造初始敌人this.startEnemyTank(flag);//初始化图片//下面的方法第一个爆炸效果不明显image1=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/beng.png"));image2=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/beng2.png"));image3=Toolkit.getDefaultToolkit().getImage(Panel.class.getResource("/beng3.png"));// try {// image1=ImageIO.read(new File("shanshui.jpg"));// image2=ImageIO.read(new File("beng2.png"));// image3=ImageIO.read(new File("beng3.png"));// } catch (Exception e) {// // TODO Auto-generated catch block// e.printStackTrace();// }}public void startEnemyTank(String flag){if(flag.equals("newgame")){//构造敌方坦克for(int i=0;i<ensize;i++){//创建敌方坦克敌人的初始位置EnemyTank et=new EnemyTank((i+1)*35,0);et.setColor(0); //???et.setDirect(2);//将MyPanel创建的坦克交给该敌人et.setEts(ets);//加入向量组ets.add(et);//给敌人添加子弹Shot s=new Shot(et.x+10,et.y+30,2);et.ss1.add(s);Thread t2=new Thread(s);t2.start();//启动敌人坦克Thread t=new Thread(et);t.start();}}else{nodes=new Recorder().getNodesAndEnemy();//构造敌方坦克for(int i=0;i<nodes.size();i++){//取出NodeNode node=nodes.get(i);//创建敌方坦克敌人的初始位置EnemyTank et=new EnemyTank(node.x,node.y);et.setColor(0); //???et.setDirect(node.direct);//将MyPanel创建的坦克交给该敌人et.setEts(ets);//加入向量组ets.add(et);//给敌人添加子弹Shot s=new Shot(et.x+10,et.y+30,2);et.ss1.add(s);Thread t2=new Thread(s);t2.start();//启动敌人坦克Thread t=new Thread(et);t.start();}}}//函数的重载,用于重复产生敌人(int)(Math.random()*270),(int)(Math.random()*360) public void startEnemyTank(){//构造敌方坦克//创建敌方坦克敌人的初始位置位置随机EnemyTank et=new EnemyTank((int)(Math.random()*370),(int)(Math.random()*270));et.setColor(0); //???et.setDirect(2);//将MyPanel创建的坦克交给该敌人et.setEts(ets);//加入向量组ets.add(et);//给敌人添加子弹Shot s=new Shot(et.x+10,et.y+30,2);et.ss1.add(s);Thread t2=new Thread(s);t2.start();//启动敌人坦克Thread t=new Thread(et);t.start();}//画提示信息的坦克public void showInfo(Graphics g){//提示信息this.drawTank(80, 330, g,0, 1);g.setColor(Color.black);g.drawString(Recorder.getEnlife()+"", 115, 350);this.drawTank(180, 330, g,0, 0);g.setColor(Color.black);g.drawString(Recorder.getMylife()+"", 220, 350);Font f=new Font("宋体",Font.BOLD,25);g.setFont(f);g.drawString("您的总成绩", 415, 40);this.drawTank(440, 90, g,0, 1);g.drawString("*", 470, 112);g.drawString(Recorder.getDeadenemy()+"", 500, 110);//判断结束提示消息//Hero输了if(Hero.counter==Hero.newlife){Font f1=new Font("宋体",Font.BOLD,40);g.setFont(f1);g.setColor(Color.RED);g.drawString("GAME OVER", 110, 150);for(int i=0;i<this.ets.size();i++){//取出各个坦克速度int esp0=ets.get(i).getSpeed();//设其速度为0ets.get(i).setSpeed(0);//取出各个坦克EnemyTank et=ets.get(i);//再取出每一颗子弹for(int j=0;j<et.ss1.size();j++){//取出各个子弹速度int ess0=et.ss1.get(j).getSpeed();//设其速度为0et.ss1.get(j).setSpeed(0);}}}//HERO 胜利!//没有敌人了就赢了else if(Recorder.getEnlife()==MyPanel.ensize-EnemyTank.newlife) {Font f1=new Font("宋体",Font.BOLD,40);g.setFont(f1);g.setColor(Color.RED);g.drawString("WINNER", 120, 150);for(int i=0;i<this.ets.size();i++){//取出各个坦克速度int esp0=ets.get(i).getSpeed();//设其速度为0ets.get(i).setSpeed(0);//取出各个坦克EnemyTank et=ets.get(i);//再取出每一颗子弹for(int j=0;j<et.ss1.size();j++){//取出各个子弹速度int ess0=et.ss1.get(j).getSpeed();//设其速度为0et.ss1.get(j).setSpeed(0);}}}}//重写paintpublic void paint(Graphics g){super.paint(g);g.fillRect(0, 0, bx1, by1); //填充背景颜色this.showInfo(g);if(hero.isLive&&Hero.counter!=Hero.newlife){//画我的坦克this.drawTank(hero.getX(), hero.getY(), g, this.hero.direct, 0);}else if(!hero.isLive&&Hero.counter<Hero.newlife){hero.isLive=true;Hero.counter++;//画我的坦克this.drawTank(hero.getX(), hero.getY(), g, this.hero.direct, 0);}//遍历Vector画出子弹&&Hero.counter!=Hero.newlifefor(int i=0;i<hero.ss.size();i++){Shot myshot=hero.ss.get(i);//画一颗子弹if(myshot!=null&&myshot.isLive){g.setColor(Color.yellow);g.fill3DRect(myshot.x, myshot.y, 3, 3, false);//g.fillOval(myshot.x-1, myshot.y, 5, 5);}if(myshot.isLive==false){//删除死亡的子弹hero.ss.remove(myshot);}}//画出炸弹for(int i=0;i<bombs.size();i++){//取出炸弹Bomb b=bombs.get(i);if(b.life>2){g.drawImage(image3, b.x, b.y, 30, 30, this);}else if(b.life>1){g.drawImage(image1, b.x, b.y, 30, 30, this);}else{g.drawImage(image2, b.x, b.y, 30, 30, this);}//播放爆炸声音AePlayWave ap1=new AePlayWave("D:\\CHEN\\bz.wav");ap1.start();//Hero输了if (Hero.counter == Hero.newlife ){//提示声音AePlayWave ap = new AePlayWave("D:\\CHEN\\gameover.wav");ap.start();audio++;}//HERO 胜利!//没有敌人了就赢了else if (Recorder.getEnlife() == MyPanel.ensize - EnemyTank.newlife && audio == 0){ //提示声音AePlayWave ap = new AePlayWave("D:\\CHEN\\winner.wav");ap.start();audio++;}//让b的生命值减小b.lifeDown();//减小到0就去掉if(b.life==0){bombs.remove(b);}}//画敌方坦克for(int i=0;i<ets.size();i++){EnemyTank et=ets.get(i);if(et.isLive){this.drawTank(et.getX(), et.getY(), g, et.getDirect(), 1);//画出敌人子弹for(int j=0;j<et.ss1.size();j++){//取出子弹Shot enemyshot=et.ss1.get(j);if(enemyshot.isLive){g.setColor(Color.RED);g.fill3DRect(enemyshot.x-1, enemyshot.y, 3, 3, false);}else{//如果敌人子弹死亡就把他从Vector中去掉et.ss1.remove(enemyshot);}}}//有敌人被消灭就在画一个,而且不能超过10个if(!et.isLive&&EnemyTank.counter<EnemyTank.newlife){et.ets.remove(et);//重载this.startEnemyTank();EnemyTank.counter++;}}}//判断子弹是否击中敌方坦克public void hitTank(Shot s,Tank et){//判断敌人坦克方向switch(et.direct){case 0:case 2:if(s.x>et.x&&s.x<et.x+20&&s.y>et.y&&s.y<et.y+30){//创建炸弹Bomb b=new Bomb(et.x, et.y);//放入Vectorbombs.add(b);//击中//子弹死亡s.isLive=false;//敌人死亡et.isLive=false;if(et!=hero){//敌人数目减少Recorder.reduceEnlife();//记录我的战绩Recorder.deadenemy();}//减少我的生命else if(et==hero){Recorder.reduceMylife();}}break;case 1:case 3:if(s.x>et.x&&s.x<et.x+30&&s.y>et.y&&s.y<et.y+20){//创建炸弹Bomb b=new Bomb(et.x, et.y);//放入Vectorbombs.add(b);//击中//子弹死亡s.isLive=false;//敌人死亡et.isLive=false;if(et!=hero){//敌人数目减少Recorder.reduceEnlife();//记录我的战绩Recorder.deadenemy();}else if(et==hero){Recorder.reduceMylife();}}break;}}//判断敌人是否击中我public void hitMe(){//取出敌人的坦克for(int i=0;i<this.ets.size();i++){//取出坦克EnemyTank et=ets.get(i);//取出每一颗子弹for(int j=0;j<et.ss1.size();j++){//取出子弹Shot enemyshot=et.ss1.get(j);if(hero.isLive){this.hitTank(enemyshot, hero);}}}}//判断是否击中了敌人public void hitenemytank(){//判断是否击中for(int i=0;i<hero.ss.size();i++){//取出子弹Shot myshot=hero.ss.get(i);//判断是否有效if(myshot.isLive){//取出每个坦克与他判断for(int j=0;j<ets.size();j++){//取出坦克EnemyTank et=ets.get(j);if(et.isLive){this.hitTank(myshot, et);}}}// //播放爆炸声音//// AePlayWave ap1=new AePlayWave("D:\\CHEN\\fs.wav");// ap1.start();}}//画坦克的函数public void drawTank(int x,int y,Graphics g, int direct, int type)//direct方向,type类型{switch(type){case 1:g.setColor(Color.CY AN);break;case 0:g.setColor(Color.yellow);break;}//判断方向switch(direct){//向上case 0://画上方向的坦克有五个部件构成//1.左边的矩形g.fill3DRect(x, y, 5, 30,false);//2.y右边的矩形g.fill3DRect(x+15, y, 5, 30,false);//中间矩形g.fill3DRect(x+5, y+6, 10, 19,false);//g.fillRect(x+5, y+6, 10, 19);//中间圆g.setColor(Color.GRAY);g.fillOval(x+5, y+9, 10, 10);//炮筒g.setColor(Color.DARK_GRAY);g.fill3DRect(x+10, y-4, 2, 21,false);g.setColor(Color.blue);g.fill3DRect(x+8, y-8, 5, 3,false);break;case 1://画向右的坦克g.fill3DRect(x, y, 30, 5,false);//上轮g.fill3DRect(x, y+15, 30, 5,false);//下轮g.fill3DRect(x+5, y+6, 19, 10,false);//中间g.setColor(Color.GRAY);g.fillOval(x+9, y+5, 10, 10);//中间圆g.setColor(Color.DARK_GRAY);g.fill3DRect(x+12, y+9, 21, 2,false);//炮筒g.setColor(Color.blue);g.fill3DRect(x+33, y+8, 3, 5,false);break;case 2://向下//1.左边的矩形g.fill3DRect(x, y, 5, 30,false);//hero.getX(),hero.getY()用x y换了//2.y右边的矩形g.fill3DRect(x+15, y, 5, 30,false);//中间矩形g.fill3DRect(x+5, y+4, 10, 19,false);//g.fillRect(x+5, y+6, 10, 19);//中间圆g.setColor(Color.GRAY);g.fillOval(x+5, y+9, 10, 10);//炮筒g.setColor(Color.DARK_GRAY);g.fill3DRect(x+10, y+14, 2, 20,false);g.setColor(Color.blue);g.fill3DRect(x+8, y+33, 5, 3,false);break;case 3://向左g.fill3DRect(x, y, 30, 5,false);//上轮g.fill3DRect(x, y+15, 30, 5,false);//下轮g.fill3DRect(x+7, y+6, 19, 10,false);//中间g.setColor(Color.GRAY);g.fillOval(x+9, y+5, 10, 10);//中间圆g.setColor(Color.DARK_GRAY);g.fill3DRect(x-6, y+9, 21, 2,false);//炮筒g.setColor(Color.blue);g.fill3DRect(x-7, y+8, 3, 5,false);break;}}//键按下处理//a表示向左,s向下,d向右,w向上;或者用方向键也行public void keyPressed(KeyEvent arg0) {// TODO Auto-generated method stubif(arg0.getKeyCode()==KeyEvent.VK_W||arg0.getKeyCode()==KeyEvent.VK_UP) {//System.out.println("ok");//设置我的坦克方向向上if(hero.isLive){this.hero.setDirect(0);this.hero.moveUp();}}else if (arg0.getKeyCode()==KeyEvent.VK_D||arg0.getKeyCode()==KeyEvent.VK_RIGHT){//向右if(hero.isLive){this.hero.setDirect(1);this.hero.moveRight();}}else if (arg0.getKeyCode()==KeyEvent.VK_S||arg0.getKeyCode()==KeyEvent.VK_DOWN){//向下if(hero.isLive){this.hero.setDirect(2);this.hero.moveDown();}}else if (arg0.getKeyCode()==KeyEvent.VK_A||arg0.getKeyCode()==KeyEvent.VK_LEFT){//向左if(hero.isLive){this.hero.setDirect(3);this.hero.moveLeft();}}//判断开火空格键发射if(arg0.getKeyCode()==KeyEvent.VK_SPACE){//只能连发5发子弹if(hero.ss.size()<=4&&hero.isLive){//开火this.hero.shotEnemy();}}// //暂停/继续游戏// if(arg0.getKeyCode()==KeyEvent.VK_P)// {// for(int i=0;i<this.ets.size();i++)// {// if(power%2==0)// {// //取出各个坦克速度// int esp0=ets.get(i).getSpeed();// //记住该速度// tempspeed=esp0;// //设其速度为0// ets.get(i).setSpeed(0);////// //取出各个坦克// EnemyTank et=ets.get(i);// //再取出每一颗子弹// for(int j=0;j<et.ss1.size();j++)// {// //取出各个子弹速度// int ess0=et.ss1.get(j).getSpeed(); // //记住该速度// int ess1=ess0;// //设其速度为0// et.ss1.get(j).setSpeed(0);// }//// }// else// {// ets.get(i).setSpeed(esp1);//// //et.ss1.get(j).setSpeed(0);// }//// }// power++;// }////调用repaint重画this.repaint();}@Overridepublic void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void run() {// TODO Auto-generated method stub//每100毫秒重绘while(true){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//判断是否添加新子弹for(int i=0;i<ets.size();i++){EnemyTank et=ets.get(i);if(et.isLive){//ets.size()为敌人可以连发子弹的数目if(et.ss1.size()<2){Shot s=null;//没有子弹,添加switch(et.direct){case 0:s=new Shot(et.x+9,et.y-10,0);et.ss1.add(s);break;case 1:s=new Shot(et.x+35,et.y+9,1);et.ss1.add(s);break;case 2:s=new Shot(et.x+10,et.y+35,2);et.ss1.add(s);break;case 3:s=new Shot(et.x-9,et.y+9,3);et.ss1.add(s);break;}//创建线程对象Thread t=new Thread(s);//启动t.start();}}}this.hitenemytank();this.hitMe();//重绘this.repaint();}}}package com.TankGame5;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.io.*;import java.util.Vector;import javax.sound.sampled.*;import javax.swing.JPanel;class Node{int x;int y;int direct;public Node(int x,int y,int direct){this.x=x;this.y=y;this.direct=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\\AllRecording.txt");br=new BufferedReader(fr);String n="";//先读取第一行n=br.readLine();deadenemy=Integer.parseInt(n);//用split分割从第二行开始取while((n=br.readLine())!=null){//字符串str中从第一个字符起,//每遇到一个空格则切割为一个元素,//放入[]xyd数组中String []xyd=n.split(" ");//这里的空格数与keepRecAndEnemyTank()中//写入(String record=et.x+" "+et.y+" "+et.direct;)//!!!!!!!!!!!!!! //的空格数要对应,否则会报错!Node node1=new Node(Integer.parseInt(xyd[0]),Integer.parseInt(xyd[1]),Integer.parseInt(xyd[2]));nodes.add(node1);}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//关闭文件//谁先开,谁后关!try {br.close();fr.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return nodes;}public static Vector<EnemyTank> getEts() {return ets;}public static void setEts(Vector<EnemyTank> ets) { Recorder.ets = ets;}//保存击毁敌人的数目和敌人坐标,存盘退出public static void keepRecAndEnemyTank(){try {//创建fw=new FileWriter("d:\\chen\\AllRecording.txt");bw=new BufferedWriter(fw);bw.write(deadenemy+"\r\n");//保存当前敌人的数目和坐标for(int i=0;i<ets.size();i++){//取出第一个坦克EnemyTank et=ets.get(i);//保存活的if(et.isLive){String record=et.x+" "+et.y+" "+et.direct;//写入bw.write(record+"\r\n");}}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//关闭文件//谁先开,谁后关!try {bw.close();fw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}//保存击毁的敌人数目public static void keepRecording(){try {//创建fw=new FileWriter("d:\\chen\\TankRecording.txt");bw=new BufferedWriter(fw);bw.write(deadenemy+"\r\n");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//关闭文件//谁先开,谁后关!try {bw.close();fw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}//读取出上一局击毁的敌人数目public static void getRecording(){try {//创建fr=new FileReader("d:\\chen\\TankRecording.txt");br=new BufferedReader(fr);String n=br.readLine();deadenemy=Integer.parseInt(n);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{//关闭文件//谁先开,谁后关!try {br.close();fr.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public static int getEnlife() {return enlife;}public static void setEnlife(int enlife) {Recorder.enlife = enlife;}public static int getMylife() {return mylife;}public static void setMylife(int mylife) {Recorder.mylife = mylife;}//减少数量public static void reduceMylife() {Recorder.mylife--;}public static void reduceEnlife() {Recorder.enlife--;}public static void deadenemy() {Recorder.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) { this.tempspeed = tempspeed;}//颜色int color;boolean isLive=true;public boolean isLive() {return isLive;}public void setLive(boolean isLive) { this.isLive = isLive;}public int getColor() {return color;}public void setColor(int color) {this.color = color;}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public Tank (int x,int y){this.x=x;this.y=y;}//坦克方向//0上,1右,2下,3左int direct=0;public int getDirect() {return direct;}public void setDirect(int direct) {this.direct = direct;}//坦克的速度int speed=3;public int getSpeed() {return speed;}public void setSpeed(int speed) {this.speed = speed;}}//敌方坦克class EnemyTank extends Tank implements Runnable {//设敌人可以复活10次static int newlife=10;//计数器static int counter=0;//让坦克随机产生步数//每次走多少步int steps=(int)(Math.random()*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){this.ets=vv;}//判断是否撞到了别的敌人坦克public boolean isTouchotherEnemy(){boolean b=false;//判断switch(this.direct){case 0://向上//取出敌人所有坦克for(int i=0;i<ets.size();i++){//取出第一个坦克EnemyTank et=ets.get(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.x<=et.x+20&&this.y>=et.y&&this.y<=et.y+30){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+20&&this.y>=et.y&&this.y<=et.y+30){return true;}}//如果敌人方向是向左或者向右if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.x<=et.x+30&&this.y>=et.y&&this.y<=et.y+20){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+30&&this.y>=et.y&&this.y<=et.y+20){return true;}}}}break;case 1://向右//取出敌人所有坦克for(int i=0;i<ets.size();i++){//取出第一个坦克EnemyTank et=ets.get(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if(et.direct==0||et.direct==2){if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y>=et.y&&this.y<=et.y+30){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+20&&this.y+20>=et.y&&this.y+20<=et.y+30){return true;}}//如果敌人方向是向左或者向右if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.x<=et.x+30&&this.y>=et.y&&this.y<=et.y+20){return true;}if(this.x+30>=et.x&&this.x+30<=et.x+30&&this.y+20>=et.y&&this.y+20<=et.y+20){return true;}}}}break;case 2://向下//取出敌人所有坦克for(int i=0;i<ets.size();i++){//取出第一个坦克EnemyTank et=ets.get(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.x<=et.x+20&&this.y+30>=et.y&&this.y+30<=et.y+30){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+20&&this.y+30>=et.y&&this.y+30<=et.y+30){return true;}}//如果敌人方向是向左或者向右if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.x<=et.x+30&&this.y+30>=et.y&&this.y+30<=et.y+20){return true;}if(this.x+20>=et.x&&this.x+20<=et.x+30&&this.y+30>=et.y&&this.y+30<=et.y+20){return true;}}}}break;case 3://向左//取出敌人所有坦克for(int i=0;i<ets.size();i++){//取出第一个坦克EnemyTank et=ets.get(i);//如果不是自己if(et!=this){//如果敌人方向是向上或者向下if(et.direct==0||et.direct==2){if(this.x>=et.x&&this.x<=et.x+20&&this.y>=et.y&&this.y<=et.y+30){return true;}if(this.x>=et.x&&this.x<=et.x+20&&this.y+20>=et.y&&this.y+20<=et.y+30){return true;}}//如果敌人方向是向左或者向右if(et.direct==1||et.direct==3){if(this.x>=et.x&&this.x<=et.x+30&&this.y>=et.y&&this.y<=et.y+20){return true;}if(this.x>=et.x&&this.x<=et.x+30&&this.y+20>=et.y&&this.y+20<=et.y+20){return true;}}}}break;}return b;}public void run() {// TODO Auto-generated method stubwhile(true){switch(this.direct){case 0://继续让他再走几步for(int i=0;i<steps;i++){if(y>0&&!isTouchotherEnemy()){y-=speed;}// //撞到墙或者队友就转弯||isTouchotherEnemy()// else if(y<=0)// {// //让坦克变向// this.direct=(direct+1)%4;// }try {Thread.sleep(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 1://继续让他再走几步for(int i=0;i<steps;i++){if(x<MyPanel.bx1-20&&!isTouchotherEnemy()){x+=speed;}// //撞到墙或者队友就转弯// else if(x>=MyPanel.bx1-20)// {// //让坦克变向// this.direct=(direct+1)%4;// }try {Thread.sleep(sleeptime);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 2://继续让他再走几步for(int i=0;i<steps;i++){if(y<MyPanel.by1-20&&!isTouchotherEnemy()){y+=speed;}//撞到墙或者队友就转弯// else if(y>=MyPanel.by1-20)// {// //让坦克变向// this.direct=(direct+1)%4;// }。
python实现简单坦克大战
python实现简单坦克⼤战基于对⾯向对象编程的思想完成简单的坦克⼤战游戏。
主要⽬的锻炼⾯相对象编程思想同样的在使⽤python进⾏游戏编写时需要安装pygame模块安装⽅法:pycharm安装⽅式:File --> setting游戏中的主要对象有:坦克⽗类:BaseTank我⽅坦克:HeroTank敌⽅坦克:EnemyTank⼦弹类:Bullet爆炸类:Explode墙类:Wall主进程:MainGame定义⼀个精灵类:# 定义⼀个精灵类class BaseItem(Sprite):def __init__(self, color, width, height):# Call the parent class (Sprite) constructorpygame.sprite.Sprite.__init__(self)坦克⽗类:# 定义类属性,所有坦克对象⾼和宽都是⼀样width = 60height = 60def __init__(self, left, top):self.direction = 'U' # 坦克的⽅向默认向上# 存放图⽚的字典self.images = {'U': pygame.image.load('tank_img/p1tankU.gif'),'D': pygame.image.load('tank_img/p1tankD.gif'),'L': pygame.image.load('tank_img/p1tankL.gif'),'R': pygame.image.load('tank_img/p1tankR.gif')}self.image = self.images[self.direction] # 坦克的图⽚由⽅向决定 self.speed = 5 # 坦克的速度self.rect = self.image.get_rect()# 设置放置的位置self.rect.left = leftself.rect.top = topself.stop = True # 坦克是否停⽌self.live = True # 决定坦克是否消灭了# 保持原来的位置self.oldLeft = self.rect.leftself.oldTop = self.rect.top# 射击⽅法def shot(self):return Bullet(self)# 坦克的移动def move(self):# 保持原来的状态self.oldLeft = self.rect.leftself.oldTop = self.rect.top# 判断坦克的移动⽅向if self.direction == 'U':if self.rect.top > 0:self.rect.top -= self.speedelif self.direction == 'D':if self.rect.top + self.rect.height < WINDOW_HEIGHT:self.rect.top += self.speedelif self.direction == 'L':if self.rect.left > 0:self.rect.left -= self.speedelif self.direction == 'R':if self.rect.left+self.rect.height < WINDOW_WIDTH:self.rect.left += self.speed# 加载坦克def displayTank(self):self.image = self.images[self.direction]MainGame.window.blit(self.image, self.rect)# 撞墙处理def hitWall(self):for wall in MainGame.wallList:if pygame.sprite.collide_rect(wall, self):self.stay()# 处理位置不变def stay(self):self.rect.left = self.oldLeftself.rect.top = self.oldTop我⽅坦克类():# 我⽅坦克class HeroTank(BaseTank):def __init__(self, left, top):super().__init__(left, top)# 我⽅坦克碰撞敌⽅坦克def myTank_hit_enemyTank(self):for enemyTank in MainGame.EnemyTankList:if pygame.sprite.collide_rect(enemyTank, self):self.stay()敌⽅坦克类():super(EnemyTank, self).__init__(left, top)self.images = {'U': pygame.image.load('tank_img/enemy1U.gif'),'D': pygame.image.load('tank_img/enemy1D.gif'),'L': pygame.image.load('tank_img/enemy1L.gif'),'R': pygame.image.load('tank_img/enemy1R.gif')}self.direction = self.RandomDirection()self.image = self.images[self.direction]self.rect = self.image.get_rect()self.rect.left = leftself.rect.top = topself.speed = speedself.step = 60self.enemy_flag = False# 坦克出⽣随机⽅向def RandomDirection(self):num = random.randint(1, 4)if num == 1:return 'U'elif num == 2:return 'D'elif num == 3:return 'L'else:return 'R'# 坦克随机移动def randomMove(self):if self.step < 0:self.direction = self.RandomDirection()self.step = 60else:self.move()self.step -= 1# 坦克射击def shot(self):num = random.randint(1, 100)if num < 4:return Bullet(self)# 敌⽅坦克碰撞我⽅坦克def enemyTank_hit_MyTank(self):for enemy in MainGame.EnemyTankList:if MainGame.my_tank and MainGame.my_tank.live:if pygame.sprite.collide_rect(MainGame.my_tank, enemy):self.stay()⼦弹类():# ⼦弹类class Bullet(BaseItem):def __init__(self, tank):self.image = pygame.image.load('tank_img/tankmissile.gif')self.direction = tank.directionself.rect = self.image.get_rect()# 根据坦克⽅向,⽣成⼦弹位置if self.direction == 'U':self.rect.left = tank.rect.left + tank.rect.width / 2 - self.rect.width / 2 self.rect.top = tank.rect.top - self.rect.heightelif self.direction == 'D':self.rect.left = tank.rect.left + tank.rect.width / 2 - self.rect.width / 2 self.rect.top = tank.rect.top + tank.rect.heightelif self.direction == 'L':self.rect.left = tank.rect.left - self.rect.width / 2 - self.rect.width / 2 self.rect.top = tank.rect.top + tank.rect.height / 2 - self.rect.width / 2 elif self.direction == 'R':self.rect.left = tank.rect.left + tank.rect.widthself.rect.top = tank.rect.top + tank.rect.height / 2 - self.rect.width / 2 # ⼦弹的速度self.speed = 6# ⼦弹状态self.live = True# 加载⼦弹def displayBullet(self):def move(self):if self.direction == 'U':if self.rect.top > 0:self.rect.top -= self.speedelse:self.live = Falseelif self.direction == 'R':if self.rect.left + self.rect.width < WINDOW_WIDTH:self.rect.left += self.speedelse:self.live = Falseelif self.direction == 'D':if self.rect.top + self.rect.height < WINDOW_HEIGHT: self.rect.top += self.speedelse:self.live = Falseelif self.direction == 'L':if self.rect.left > 0:self.rect.left -= self.speedelse:self.live = False# 我⽅⼦弹击中敌⽅坦克def myBullet_hit_enemy(self):for enemytank in MainGame.EnemyTankList:if pygame.sprite.collide_rect(enemytank, self):enemytank.live = Falseself.live = False# 创建爆炸对象explode = Explode(enemytank)MainGame.explodeList.append(explode)# 敌⽅坦克击中我⽅坦克def enemyBullet_hit_myTank(self):if MainGame.my_tank and MainGame.my_tank.live:if pygame.sprite.collide_rect(MainGame.my_tank, self): MainGame.my_tank.live = Falseself.live = False# 创建爆炸对象explode = Explode(MainGame.my_tank)MainGame.explodeList.append(explode)# 射击墙壁def wall_bullet(self):for wall in MainGame.wallList:if pygame.sprite.collide_rect(wall, self):wall.hg -= 1self.live = Falseif wall.hg <= 0:wall.live = False墙壁类():# 墙壁类class Wall:def __init__(self, left, top):self.image = pygame.image.load('tank_img/steels.gif') self.rect = self.image.get_rect()self.rect.left = leftself.rect.top = topself.live = Trueself.hg = 100000000000000# 加载墙壁def displayWall(self):if self.live:MainGame.window.blit(self.image, self.rect)爆炸类:# 爆炸类class Explode:def __init__(self, tank):# 爆炸的位置由坦克决定self.rect = tank.rectself.images = [pygame.image.load('tank_img/blast0.gif'),pygame.image.load('tank_img/blast1.gif'),pygame.image.load('tank_img/blast5.gif'),pygame.image.load('tank_img/blast6.gif'),pygame.image.load('tank_img/blast7.gif')]self.step = 0self.image = self.images[self.step]self.live = True# 加载爆炸类def displayExplode(self):if self.step < len(self.images):self.image = self.images[self.step]self.step += 1MainGame.window.blit(self.image, self.rect)else:self.live = Falseself.step = 0主进程():# 游戏类class MainGame:# 类属性window = Nonemy_tank = None# 敌⽅坦克初始化EnemyTankList = []EnemyTankCount = 5# 存储我⽅⼦弹列表myBulleList = []# 存储敌⽅⼦弹的列表EnemyBulletList = []# 创建爆炸对象列表explodeList = []# 创建墙壁列表wallList = []# 游戏开始⽅法def start_game(self):# 初始化展⽰模块pygame.display.init()# 调⽤创建窗⼝的⽅法self.creat_window()# 设置游戏窗⼝标题pygame.display.set_caption('坦克⼤战')# 初始化我⽅坦克self.createMyTank()# 初始化敌⽅坦克self.creatEnemyTank()# 初始化墙壁self.creatWall()# 程序持续进⾏while True:# 更改背景颜⾊MainGame.window.fill(COLOR_GREEN)# 背景⾳乐# 获取事件self.getEvent()# 调⽤我⽅坦克进⾏显⽰if MainGame.my_tank and MainGame.my_tank.live: MainGame.my_tank.displayTank()if not MainGame.my_tank.stop:MainGame.my_tank.move()MainGame.my_tank.hitWall()MainGame.my_tank.myTank_hit_enemyTank()else:del MainGame.my_tankMainGame.my_tank = None# 加载我⽅⼦弹self.biltMyBullet()# 显⽰敌⽅坦克self.biltEnemyTank()# 显⽰敌⽅⼦弹self.biltEnemyBullet()# 显⽰墙壁self.blitExplode()self.put_more_enemytank()# 窗⼝持续刷新pygame.display.update()time.sleep(0.02)# 重复添加敌⽅坦克def put_more_enemytank(self):while len(MainGame.EnemyTankList) < 5:self.more()# 创建游戏窗⼝⽅法:def creat_window(self):if not MainGame.window:# 创建窗⼝MainGame.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))return MainGame.window# 创建我⽅坦克def createMyTank(self):MainGame.my_tank = HeroTank((WINDOW_WIDTH - HeroTank.width)/2, WINDOW_HEIGHT - HeroTank.height) music = Music('tank_img/start.wav')music.play()# 创建墙壁def creatWall(self):for i in range(60, WINDOW_WIDTH, 60):top = WINDOW_WIDTH // 3left = iwall = Wall(left, top)MainGame.wallList.append(wall)# 显⽰墙壁def blitWall(self):for b in MainGame.wallList:if b.live:b.displayWall()else:MainGame.wallList.remove(b)# 加载我⽅⼦弹def biltMyBullet(self):for bullet in MainGame.myBulleList:if bullet.live:bullet.displayBullet()bullet.move()bullet.myBullet_hit_enemy()bullet.wall_bullet()else:MainGame.myBulleList.remove(bullet)# 后续坦克的添加def more(self):top = 0for i in range(5 - len(MainGame.EnemyTankList)):left = random.randint(0, 750)speed = random.randint(1, 4)enemy = EnemyTank(left, top, speed)MainGame.EnemyTankList.append(enemy)# 创建敌⽅坦克def creatEnemyTank(self):top = 0for i in range(MainGame.EnemyTankCount):left = random.randint(0, 750)speed = random.randint(1, 4)enemy = EnemyTank(left, top, speed)MainGame.EnemyTankList.append(enemy)# 循环遍历显⽰敌⽅坦克def biltEnemyTank(self):for enemytank in MainGame.EnemyTankList:if enemytank.live:enemytank.displayTank()EnemyBullet = enemytank.shot()enemytank.randomMove()enemytank.hitWall()enemytank.enemyTank_hit_MyTank()MainGame.EnemyBulletList.append(EnemyBullet)else:MainGame.EnemyTankList.remove(enemytank)MainGame.EnemyTankCount -= 1# 加载敌⽅⼦弹def biltEnemyBullet(self):for bullet in MainGame.EnemyBulletList:if bullet.live:bullet.displayBullet()bullet.move()bullet.enemyBullet_hit_myTank()bullet.wall_bullet()else:MainGame.EnemyBulletList.remove(bullet)# 加载爆炸效果def blitExplode(self):for explode in MainGame.explodeList:if explode.live:explode.displayExplode()else:MainGame.explodeList.remove(explode)# 获取游戏中的所有事件def getEvent(self):# 获取游戏中的事件列表even_list = pygame.event.get()for e in even_list:# 点击窗⼝的叉号实现游戏结束if e.type == pygame.QUIT:sys.exit()# 通过上下左右键控制坦克的移动if e.type == pygame.KEYDOWN:if MainGame.my_tank and MainGame.my_tank.live:if e.key == pygame.K_DOWN or e.key == pygame.K_s:MainGame.my_tank.direction = 'D'MainGame.my_tank.stop = Falseprint("按下向下的键,向下移动")elif e.key == pygame.K_UP or e.key == pygame.K_w:MainGame.my_tank.direction = 'U'MainGame.my_tank.stop = Falseprint("按下向上的键,向上移动")elif e.key == pygame.K_LEFT or e.key == pygame.K_a:MainGame.my_tank.direction = 'L'MainGame.my_tank.stop = Falseprint("按下向左的键,向左移动")elif e.key == pygame.K_RIGHT or e.key == pygame.K_d:MainGame.my_tank.direction = 'R'MainGame.my_tank.stop = Falseprint("按下向右的键,向右移动")elif e.key == pygame.K_SPACE:print('发射⼦弹')# 创建我⽅⼦弹if len(MainGame.myBulleList) < 10:mybullet = Bullet(MainGame.my_tank)MainGame.myBulleList.append(mybullet)# 射击⾳效Shot_music = Music('tank_img/fire.wav')Shot_music.play()elif e.type == pygame.KEYUP:if e.key == pygame.K_UP or e.key == pygame.K_DOWN or e.key == pygame.K_LEFT or e.key == pygame.K_RIGHT \ or e.key == pygame.K_w or e.key == pygame.K_s or e.key == pygame.K_a or e.key == pygame.K_d:if MainGame.my_tank and MainGame.my_tank.live:MainGame.my_tank.stop = True程序运⾏结果:源码下载:更多关于python游戏的精彩⽂章请点击查看以下专题:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
韩顺平java坦克大战1.0版本_源代码
/**画坦克1。
0*/import java.awt.Color;import java.awt.Graphics;import java.awt.event。
KeyEvent;import java.awt。
event。
KeyListener;import java。
awt。
event.MouseEvent;import java。
awt。
event。
MouseListener;import java。
awt。
event.MouseMotionListener;import java.awt。
event。
WindowEvent;import java.awt。
event。
WindowListener;import javax。
swing。
JFrame;import javax.swing。
JPanel;public class MyTankGame extends JFrame{MyPanel mp=null;public static void main(String[] args){MyTankGame mtk=new MyTankGame();}public MyTankGame(){mp=new MyPanel();this.add(mp);//把面板加入窗体//注册监听this。
addMouseListener(mp);this.addKeyListener(mp);this。
addMouseMotionListener(mp);this.addWindowListener(mp);this.setTitle(”坦克大战");//窗体标题this。
setSize(600,400);//大小,宽,高(像素)this。
setLocation(300,300);//显示位置。
左边距,上边距//禁止用户改变窗口大小this。
setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);//显示}}//我的面板class MyPanel extends JPanel implements WindowListener,MouseListener,MouseMotionListener,KeyListener{//定义一个我的坦克Hero hero=null;Diren diren=null;public MyPanel(){hero=new Hero(300,200);diren=new Diren(100,0);//diren。
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更应如此。
坦克大战程序代码
坦克大战程序代码(总19页) -CAL-FENGHAI.-(YICAI)-Company One1-CAL-本页仅作为文档封面,使用请直接删除import .* ;import .* ;importimport class 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 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 , 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 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 , 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 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 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 + 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] , yf[i] , 40 , 40) ;(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] , yf[i] , 40 , 40) ;(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] , yf[i] , 40 , 40) ;(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] , yf[i] , 40 , 40) ;(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() > {}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}else{opf[i] = 4 ;}}}}if(a % 50 == 21 ) {//坦克的随机移动for (int i = 4; i<6; i++) { if( () > ) {if() > {opf[i] = 1 ;}else{opf[i] = 2 ;}}else{if() > {opf[i] = 3 ;}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() > {}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) ;}() ;}}}。
java坦克大战源代码
package com.cwj.tankGame;import javax.sound.sampled.*;import java.io*;import java.awt.*;import java.io.IOException;import java.util.*;import javax.swing,*;import javax.imageio.ImageIO;import javax.swing.*;class AePlayWave extends Thread {private String filename;public AePlayWave(String wavfile) {filename = wavfile;}public void run() {File soundFile = new File(filename);AudioInputStream audioInputStream = null;try {audioInputStream = AudioSystem.getAudioInputStream(soundFile);} catch (Exception e1) {e1.printStackTrace();return;}AudioFormat format = audioInputStream.getFormat(); SourceDataLine auline = null; info = new (SourceDataLine.class, format); try {auline = (SourceDataLine) AudioSystem.getLine(info);auline.open(format);} catch (Exception e) {e.printStackTrace();return;}auline.start();int nBytesRead = 0;//这是缓冲byte[] abData = new byte[512];try {while (nBytesRead != -1) {nBytesRead = audioInputStream.read(abData, 0, abData.length); if (nBytesRead >= 0)auline.write(abData, 0, nBytesRead);}} catch (IOException e) {e.printStackTrace();return;} finally {auline.drain();auline.close();}}}class Bomb{int x;int y;int lifeTime = 10;boolean isLive=true;public Bomb(int x,int y){this.x=x;this.y=y;}public void lifeDown(){if(lifeTime>0){lifeTime--;}else{this.isLive=false;}}}class EnemyTank extends Tank implements Runnable{int n=1;//敌方坦克转弯n次发射一颗子弹int MaxShot = 10;int runDistance = 10;//变一次方向前进的距离//定义一个向量可以访问MyPanel上所有地方坦克Vector<EnemyTank> ets =new Vector<EnemyTank>();Vector<Shot> ss = new Vector<Shot>();public void setEts(Vector<EnemyTank> v){this.ets=v;}public int abs(int x){if(x>0)return x;elsereturn -x;}public boolean isTouchOther(){switch(this.direction){case 0://上for(int i=0;i<ets.size();i++){EnemyTank t = ets.get(i);if(t!=this)//不是自己这辆坦克{if(abs(this.x-t.x)<=40&&this.y>t.y&&this.y-t.y<=40) {return true;}}}break;case 2://下for(int i=0;i<ets.size();i++){EnemyTank t = ets.get(i);if(t!=this)//不是自己这辆坦克{if(abs(this.x-t.x)<=40&&t.y>this.y&&t.y-this.y<=40) {return true;}}}break;case 1://左for(int i=0;i<ets.size();i++){EnemyTank t = ets.get(i);if(t!=this)//不是自己这辆坦克{if(abs(this.y-t.y)<=40&&this.x>t.x&&this.x-t.x<=40) {return true;}}}break;case 3://右for(int i=0;i<ets.size();i++){EnemyTank t = ets.get(i);if(t!=this)//不是自己这辆坦克{if(abs(this.y-t.y)<=40&&this.x<t.x&&t.x-this.x<=40) {return true;}}}break;}return false;}public EnemyTank(int x,int y){super(x,y);}int time=0;public void sleep(){try{Thread.sleep(50);}catch(Exception e){e.printStackTrace();}}public void run() {while(true){switch(direction){case 0:for(int i =0;i<this.runDistance;i++){if(y>20&&!this.isTouchOther())y-=speed;this.sleep();}break; case 1:for(int i =0;i<this.runDistance;i++){if(x>20&&!this.isTouchOther())x-=speed;this.sleep();}break; case 2:for(int i =0;i<this.runDistance;i++){if(y<580&&!this.isTouchOther())y+=speed;this.sleep();}break; case 3:for(int i =0;i<this.runDistance;i++){if(x<780&&!this.isTouchOther())x+=speed;this.sleep();}break; }this.direction=(int)(Math.random()*4);if(this.isLive==false){break;}else{time++;if(time%n==0)if(ss.size()<MaxShot){Shot s = new Shot(x,y);s.setDirection(direction);ss.add(s);Thread t = new Thread(s);t.start();}}}}}class MyTank extends Tank{int MAXSHOT=20;public int getMAXSHOT() {return MAXSHOT;}public void setMAXSHOT(int mAXSHOT) { MAXSHOT = mAXSHOT;}Shot shot=null;Vector<Shot> ss = new Vector<Shot>(); public MyTank(int x,int y){super(x,y);}public void fire(){if(this.isLive==true){shot = new Shot(x,y);ss.add(shot);Thread t = new Thread(shot);t.start();shot.setDirection(this.direction);}}public void moveUp(){if(y>20)y-=speed;}public void moveLeft(){if(x>20)x-=speed;}public void moveDown(){if(y<580)y+=speed;}public void moveRight(){if(x<780)x+=speed;}class Node {int x;public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getDirection() {return direction;}public void setDirection(int direction) { this.direction = direction;}int y;int direction;public Node(int x,int y){this.x=x;this.y=y;}}class Record {//记录每关有多少敌人private static int etNum=20;private static int sum = 0;private static FileWriter fw=null;private static BufferedWriter bw = null; private static FileReader fr = null; private static BufferedReader br = null; private static Vector<Node> nodes=null; public static Vector<Node> getNodes() { return nodes;public static void setNodes(Vector<Node> nodes) { Record.nodes = nodes;}public static Vector<EnemyTank> ets = null;public static Vector<EnemyTank> getEts() {return ets;}public static void setEts(Vector<EnemyTank> ets) { Record.ets = ets;}public static void restoreRecord(){try {nodes = new Vector<Node>();File file = new File("e:\\tankGame.txt");if(!file.isDirectory()){if(file.createNewFile())System.out.println("成功创建文件e:\\tankGame.txt"); }fr = new FileReader("e:\\tankGame.txt");br = new BufferedReader(fr);String strSum = br.readLine();if(strSum!=null)sum = Integer.parseInt(strSum);else return;String str="";while((str=br.readLine())!=null){String []xyd=str.split(" ");int x,y,direction;x = Integer.parseInt(xyd[0]);y = Integer.parseInt(xyd[1]);direction = Integer.parseInt(xyd[2]);Node node = new Node(x,y);node.setDirection(direction);nodes.add(node);}for(int i=0;i<nodes.size();i++){System.out.println(nodes.get(i).x+" "+nodes.get(i).y+" "+nodes.get(i).direction); }} catch (Exception e) {e.printStackTrace();}finally{try {if(br!=null)br.close();if(fr!=null)fr.close();} catch (IOException e) {e.printStackTrace();}}}public static void keepRecord(){try {fw = new FileWriter("e:\\tankGame.txt");bw = new BufferedWriter(fw);bw.write(sum+"\r\n");for(int i =0;i<ets.size();i++){EnemyTank et = ets.get(i);if(et.isLive==true){String record = et.x+" "+et.y+" "+et.getDirection()+"\r\n";bw.write(record);}}} catch (Exception e) {e.printStackTrace();}finally{try {if(bw!=null)bw.close();if(fw!=null)fw.close();} catch (IOException e) {e.printStackTrace();}}}public static int getSum() {return sum;}public static void setSum(int sum) { Record.sum = sum;}public static void addSum(){sum++;}public static int getEtNum() {return etNum;}public static void setEtNum(int etNum) { Record.etNum = etNum;}public static int getMyLife() {return myLife;}public static void setMyLife(int myLise) { Record.myLife = myLise;}//生命数private static int myLife=3;public static void reduceEtNum(){etNum--;}public static void reduceMyLife(){myLife--;}}class Shot implements Runnable{int x;int speed=5;int y;int direction;boolean isLive=true;public void run(){while(true){try{Thread.sleep(100);}catch(Exception e){e.printStackTrace();}switch(this.direction){case 0:y-=speed;break;case 1:x-=speed;break;case 2:y+=speed;break;case 3:x+=speed;break;}if(x<0||x>800||y<0||y>600){this.isLive=false;break;}}//while}public int getSpeed() {return speed;}public void setSpeed(int speed) { this.speed = speed;}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getDirection() {return direction;}public void setDirection(int direction) { this.direction = direction;}public Shot(int x,int y){this.x=x;this.y=y;}}class Tank{boolean isLive=true;int x=0;int y=0;int color;public int getColor() {return color;}public void setColor(int color) {this.color = color;}int speed=3;int direction=0;//0上1左2下3右public int getSpeed() {return speed;}public void setSpeed(int speed) { this.speed = speed;}public int getDirection() {return direction;}public void setDirection(int direction) { this.direction = direction;}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public Tank(int x,int y){this.x=x;this.y=y;}}public class TankGame extends JFrame implements ActionListener{ MyPanel mp=null;MyStartPanel msp = null;JMenuBar jmb =null;JMenu jm1=null;JMenuItem jmi11 =null;JMenuItem jmi12 = null;JMenuItem jmi13 = null;JMenuItem jmi14 = null;public static void main(String[]args){TankGame t = new TankGame();}public TankGame(){/*mp=new MyPanel();this.add(mp);Thread t = new Thread(mp);t.start();this.addKeyListener(mp);*/jmb = new JMenuBar();jm1 = new JMenu("游戏(G)");jm1.setMnemonic('G');jmi11 = new JMenuItem("开始游戏(N)");jmi11.addActionListener(this);jmi11.setActionCommand("newgame");jmi11.setMnemonic('N');jmi12 = new JMenuItem("退出游戏(E)");jmi12.addActionListener(this);jmi12.setActionCommand("exitgame");jmi12.setMnemonic('E');jmi13 = new JMenuItem("退出并保存(O)");jmi13.addActionListener(this);jmi13.setActionCommand("exitandsave");jmi13.setMnemonic('O');jmi14 = new JMenuItem("继续游戏(S)");jmi14.addActionListener(this);jmi14.setActionCommand("continue");jmi14.setMnemonic('S');jm1.add(jmi11);jm1.add(jmi13);jm1.add(jmi14);jm1.add(jmi12);jmb.add(jm1);this.setJMenuBar(jmb);msp = new MyStartPanel();Thread t = new Thread(msp);t.start();this.add(msp);this.setSize(900, 700);this.setLocationRelativeTo(null);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setTitle("坦克大战欢迎加qq1036624975交流学习编程爱好者学习交流群294787264");this.setVisible(true);}public void actionPerformed(ActionEvent e) {if(e.getActionCommand().equals("newgame")){if(mp!=null)this.remove(mp);mp = new MyPanel("newGame");Thread t = new Thread(mp);t.start();this.remove(msp);this.add(mp);this.addKeyListener(mp);this.setVisible(true);AePlayWave apw = new AePlayWave("e://tank.wav"); new Thread(apw).start();}else if(e.getActionCommand().equals("exitgame")){System.exit(0);}else if(e.getActionCommand().equals("exitandsave")) {Record.setEts(mp.et);Record.keepRecord();System.exit(0);}else if(e.getActionCommand().equals("continue")){Record.restoreRecord();if(mp!=null)this.remove(mp);mp = new MyPanel("oldGame");Thread t = new Thread(mp);t.start();this.remove(msp);this.add(mp);this.addKeyListener(mp);this.setVisible(true);}}}class MyStartPanel extends JPanel implements Runnable {int count=0;public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 800, 600);if(count%6==0)g.setColor(Color.YELLOW);else if(count%6==1)g.setColor(Color.BLUE);else if(count%6==2)g.setColor(Color.CYAN);else if(count%6==3)g.setColor(Color.GREEN);else if(count%6==4)g.setColor(Color.ORANGE);else if(count%6==5)g.setColor(Color.PINK);g.setFont(new Font("黑体",Font.PLAIN,100));g.drawString("第一关",250,300);g.setFont(new Font("黑体",Font.PLAIN,20));g.drawString("w上s下a左d右j发射子弹", 0, 20);if(count>20000)count=0;}public void run() {while(true){try {Thread.sleep(300);} catch (Exception e) {e.printStackTrace();}count++;this.repaint();}}}class MyPanel extends JPanel implements KeyListener,Runnable {Image bomb1=null;Image bomb2=null;Image bomb3=null;MyTank mt = null;//我的坦克Vector<EnemyTank>et=new Vector<EnemyTank>();Vector<Bomb>bombs = new Vector<Bomb>();Vector<Node>nodes =null;int enemyTankNum=20;public MyPanel(String ifNew){Record.restoreRecord();mt = new MyTank(300,570);mt.setSpeed(7);mt.setColor(0);//初始化敌人的坦克if(ifNew.equals("newGame")){for(int i =0;i<enemyTankNum;i++){EnemyTank tank = null;if(i<10){tank=new EnemyTank((i+1)*70,20);}else{tank = new EnemyTank(((i-9))*70,80);}tank.setDirection(2);Thread t = new Thread(tank);t.start();Shot s = new Shot(tank.x,tank.y);s.setDirection(tank.direction);new Thread(s).start();tank.ss.add(s);tank.setColor(1);et.add(tank);tank.setEts(et);}}else if(ifNew.equals("oldGame")){nodes=Record.getNodes();for(int i =0;i<nodes.size();i++){Node node = nodes.get(i);EnemyTank tank = null;tank = new EnemyTank(node.getX(),node.getY()); tank.setDirection(node.getDirection());Thread t = new Thread(tank);t.start();Shot s = new Shot(tank.x,tank.y);s.setDirection(tank.direction);new Thread(s).start();tank.ss.add(s);tank.setColor(1);et.add(tank);tank.setEts(et);}}//三张图片,组成一颗炸弹try {bomb1=ImageIO.read(new File("image/bomb_1.gif"));bomb2=ImageIO.read(new File("image/bomb_2.gif"));bomb3=ImageIO.read(new File("image/bomb_3.gif"));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}//以下方式加载图片第一次爆炸效果不明显/*bomb1=Toolkit.getDefaultToolkit().getImage("image/bomb_1.gif"); bomb2=Toolkit.getDefaultToolkit().getImage("image/bomb_2.gif"); bomb3=Toolkit.getDefaultToolkit().getImage("image/bomb_3.gif");*/ }public void showMessage(Graphics g){this.paintTank(825, 20, g, 0, 1);this.paintTank(825, 80, g, 0, 0);g.setColor(Color.BLACK);g.drawString("x"+Record.getEtNum(),850,20);g.drawString("x"+Record.getMyLife(), 850, 80);g.setFont(new Font("华文彩云",Font.BOLD,20));g.drawString("总成绩", 2, 620);g.drawString(""+Record.getSum(), 76, 620);}public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 800, 600);this.showMessage(g);if(mt.isLive==true)paintTank(mt.getX(),mt.getY(),g,mt.getDirection(),mt.getColor());//画敌人坦克for(int i=0;i<et.size();i++){EnemyTank t = et.get(i);if(t.isLive==true){paintTank(t.getX(),t.getY(),g,t.getDirection(),t.getColor());for(int j = 0;j<t.ss.size();j++)//画子弹{if(s.isLive==true){g.setColor(Color.RED);g.fillRect(s.getX(), s.getY(), 5,5);}else{t.ss.remove(s);}}}else{et.remove(t);}}//爆炸效果for(int i=0;i<bombs.size();i++){Bomb b = bombs.get(i);if(b.lifeTime>6){g.drawImage(bomb1,b.x,b.y,40,40,this);}else if(b.lifeTime>3){g.drawImage(bomb2,b.x,b.y,40,40,this);}else{g.drawImage(bomb3,b.x,b.y,40,40,this);}b.lifeDown();if(b.lifeTime==0){bombs.remove(b);}}for(int i =0;i<mt.ss.size();i++)//我的画子弹{Shot s = mt.ss.get(i);if(s!=null&&s.isLive==true){g.setColor(Color.YELLOW);g.fillRect(s.getX(), s.getY(),5, 5);}if(s.isLive==false) //子弹清空,才能打下一发子弹{}}}//被攻击public void hitMyTank(){for(int i=0;i<et.size();i++){EnemyTank e=et.get(i);for(int j=0;j<e.ss.size();j++){Shot enemyShot = e.ss.get(j); boolean res=false;res = this.isHitTank(enemyShot, mt); if(res==true)Record.reduceMyLife();}}}//攻击敌方坦克public void hitEnemyTank(){for(int i=0;i<mt.ss.size();i++){Shot shot = mt.ss.get(i);if(shot.isLive==true){for(int j =0;j<et.size();j++){EnemyTank etank = et.get(j);if(etank.isLive==true){boolean res=false;res=this.isHitTank(shot, etank);if(res==true){Record.reduceEtNum();Record.addSum();}}}}}}//判断子弹是否击中坦克public boolean isHitTank(Shot shot,Tank etank){boolean res=false;if(shot.x>etank.x-20&&shot.x<etank.x+20&&shot.y>etank.y-20&&shot.y<etank.y+20&&et ank.isLive==true)//子弹击中{shot.isLive=false;etank.isLive=false;Bomb bomb = new Bomb(etank.getX()-20,etank.getY()-20);bombs.add(bomb);res = true;}return res;}public void paintTank(int x,int y,Graphics g,int direction,int type){switch(type)//判断坦克类型{case 0:g.setColor(Color.yellow);//自己的break;case 1:g.setColor(Color.RED);//敌人的break;}switch(direction){case 0://上g.fillRect(x-20, y-20, 40, 40);g.fill3DRect(x-5, y-20, 10, 20,false);break;case 1://左g.fillRect(x-20, y-20, 40, 40);g.fill3DRect(x-20, y-5, 20, 10,false);break;case 2://下g.fillRect(x-20, y-20, 40, 40);g.fill3DRect(x-5, y, 10, 20,false);break;case 3://右g.fillRect(x-20, y-20, 40, 40);g.fill3DRect(x, y-5, 20, 10,false);break;}}@Overridepublic void keyTyped(KeyEvent e) {// TODO Auto-generated method stub}@Overridepublic void keyPressed(KeyEvent e) {// TODO Auto-generated method stubif(e.getKeyCode()==KeyEvent.VK_J)//发射子弹{if(this.mt.ss.size()<this.mt.getMAXSHOT()) {this.mt.fire();}}if(e.getKeyCode()==KeyEvent.VK_W){mt.setDirection(0);this.mt.moveUp();}else if(e.getKeyCode()==KeyEvent.VK_A) {mt.setDirection(1);this.mt.moveLeft();}else if(e.getKeyCode()==KeyEvent.VK_S) {mt.setDirection(2);this.mt.moveDown();}else if(e.getKeyCode()==KeyEvent.VK_D) {mt.setDirection(3);this.mt.moveRight();}this.repaint();}@Overridepublic void keyReleased(KeyEvent e) {// TODO Auto-generated method stub}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(50);//50毫秒重绘一次} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.hitEnemyTank();//判断己方坦克是否击中敌方坦克this.hitMyTank();//判断敌方坦克是否击中己方坦克this.repaint();}}}。
Java游戏开发之坦克大战代码
Java游戏开发之坦克大战代码标题:Java游戏开发之坦克大战代码关键词:Java坦克大战,坦克大战Java代码这是一个Java坦克大战的源码,实现了大部分功能,是学习Java绘图技术的好例子主类:package com.qq.TankGame;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Image;import java.awt.Paint;import java.awt.Panel;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Vector;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JTextArea;/////**// * 功能:java绘图// * @author Administrator// *// */public class TankGame extends JFrame implements ActionListener{MyPanel mp = null;myStartPanel msp = null;EnemyTask em = null;JMenuBar jmb = null;JMenu jm = null;JMenuItem jmi1 = null;JMenuItem jmi2 = null;JMenuItem jmi3 = null;public static void main(String[] args) {TankGame tankGame = new TankGame();}public TankGame(){jmb = new JMenuBar();jm = new JMenu("游戏(G)");jm.setMnemonic('G');jmi1 = new JMenuItem("开始游戏(S)");jmi1.setMnemonic('S');jmi1.addActionListener(this);jmi1.setActionCommand("newGame");jmi2 = new JMenuItem("继续游戏(O)");jmi2.setMnemonic('O');jmi3 = new JMenuItem("退出游戏(X)");jmi3.setMnemonic('X');jmi3.addActionListener(this);jmi3.setActionCommand("exit");//启动mp线程//em = new EnemyTask();//mp = new MyPanel();msp = new myStartPanel();this.setJMenuBar(jmb);this.add(msp);//this.add(mp);jmb.add(jm);jm.add(jmi1);jm.add(jmi2);jm.add(jmi3);this.setSize(600,500);//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true);//this.addKeyListener(mp);Thread t1 = new Thread(msp);t1.start();// Thread t = new Thread(mp);// t.start();}@Overridepublic void actionPerformed(ActionEvent arg0) {if(arg0.getActionCommand().equals("newGame")){mp = new MyPanel();Thread t = new Thread(mp);t.start();this.remove(msp);this.remove(mp);this.add(mp);this.setVisible(true);this.addKeyListener(mp);//Recoder.getRecording();}else if(arg0.getActionCommand()== "exit"){//Recoder.KeepRecording();Recoder.KeepExit();//KeepExit();System.exit(0);}}}class myStartPanel extends JPanel implements Runnable{ int times = 0;public void paint(Graphics g ){super.paint(g);g.fillRect(0, 0, 400, 300);if(times%2 ==0){g.setColor(Color.BLUE);Font f = new Font("华文新魏", Font.BOLD, 30);g.setFont(f);g.drawString("stage:1", 150, 150);}}@Overridepublic void run() {while(true){try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}this.repaint();times ++;}}}class MyPanel extends JPanel implements KeyListener,Runnable{ int [] TanksX = new int[20];int [] TanksY = new int[20];int [] ShotsX = new int[100];int [] ShotsY = new int[100];// int [][]Tanks = new int[20][2];// int [][]Shots = new int[20][2];int [] ETdirects = new int[20];int [] HeroShotsX = new int[10];int [] HeroShotsY = new int[10];static Hero hero = null;EnemyTask et = null;shot s = null;boolean isPaintShot = true;int a = 0, b = 0 , c = 0;int [] directs = new int [10];static //敌人坦克集合Vector<EnemyTask> ets = new Vector<EnemyTask>();int enSize = 3; //敌人坦克初始数量int enSizes = 5; //敌人坦克画面总数量int hintEnemyTanks = 0;//击中敌人坦克数量public void showInfo(Graphics g ){//画提示信息//画出提出坦克this.drawTank(80, 330, g, 0, 1);this.drawTank(160, 330, g, 0, 0);g.setColor(Color.BLACK);g.drawString(Recoder.getEnNum() + "", 105, 350);g.drawString(Recoder.getMyLife() + "", 185, 350);//画出成绩g.setColor(Color.BLACK);Font f = new Font("宋体", Font.BOLD, 15);g.setFont(f);g.drawString("你的总成绩:", 400, 20);this.drawTank(410, 30, g, 0, 1);g.drawString((20 - Recoder.getEnNum()) + "", 435, 50);}public void paint(Graphics g){super.paint(g);g.fillRect(0, 0, 400, 300);this.showInfo(g);//画出提示信息//自己坦克if(hero.isLive == true){this.drawTank(hero.getX(), hero.getY(), g, hero.direct, hero.type); }else{if(Recoder.getMyLife() > 0){hero = new Hero(30, 270 ,0,0,10 , true);hero.isLive = true;}}//画出敌人坦克for(int i = 0; i <ets.size(); i++){EnemyTask et = ets.get(i);if(!et.isLive){ets.remove(i);if(Recoder.getEnNum() >0){this.drawTank(50, 0, g, 1, 1);ets.add(et);//et.isLive = true;Thread t = new Thread(et);t.start();}// if(Recoder.getEnNum() > 0){// et.isLive = true;// }}if(et.isLive){this.drawTank(et.getX(), et.getY(),g, et.direct, et.type);System.out.println("et.ss.size()"+et.ss.size());for(int j = 0; j < et.ss.size(); j++){//敌人坦克子弹s = et.ss.get(j);if(s.isLive){if(isPaintShot){g.fill3DRect(s.x, s.y, 5, 10, false);}}else{et.ss.remove(j);}}}// if(!et.isLive){// ets.remove(i);// }}//画出子弹for(int i = 0; i< hero.ss.size(); i++){if(hero.ss.get(i)!= null && hero.ss.get(i).isLive == true){ g.fill3DRect(hero.ss.get(i).x, hero.ss.get(i).y, 5, 10, false); }if(hero.ss.get(i).isLive == false){hero.ss.remove(hero.ss.get(i));}}}// public void hintTank2(shot s , Hero et){// switch (et.direct) {// case 0:// case 1:// if(s.x < et.x + 20 && s.x > et.x// && s.y < et.y + 30 && s.y > et.y){// s.isLive = false;// et.isLive = false;// }// //break;// case 2:// case 3:// if(s.x < et.x + 30 && s.x > et.x// && s.y < et.y + 20 && s.y > et.y){// s.isLive = false;// et.isLive = false;// }// //break;////// default://// break;// }//// }public boolean hintTank(shot s , Tank et){boolean b = false;switch (et.direct) {case 0:case 1:if(s.x < et.x + 20 && s.x > et.x&& s.y < et.y + 30 && s.y > et.y){s.isLive = false;et.isLive = false;b = true;}break;case 2:case 3:if(s.x < et.x + 30 && s.x > et.x&& s.y < et.y + 20 && s.y > et.y){s.isLive = false;et.isLive = false;b = true;}break;// default:// break;}return b;}public void drawTank (int x , int y , Graphics g , int direct , int type){ switch(type){//坦克类型case 0:g.setColor(Color.RED);break;case 1:g.setColor(Color.BLUE);break;}switch (direct) {case 0://向上g.fill3DRect(x, y, 5, 30, false );g.fill3DRect(x + 15, y, 5, 30, false );g.fill3DRect(x + 5, y + 5, 10, 20, false );g.fillOval(x + 5, y + 10, 10, 10);g.drawLine(x + 10, y,x + 10, y + 15);break;case 1://向下g.fill3DRect(x, y, 5, 30, false );g.fill3DRect(x + 15, y, 5, 30, false );g.fill3DRect(x + 5, y + 5, 10, 20, false );g.fillOval(x + 5, y + 10, 10, 10);g.drawLine(x + 10, y + 15,x + 10,y + 30 ); break;case 2://向左g.fill3DRect(x, y, 30, 5, false );g.fill3DRect(x , y + 15, 30, 5, false );g.fill3DRect(x + 5, y + 5, 20, 10, false );g.fillOval(x + 10, y + 5, 10, 10);g.drawLine(x , y + 10,x + 15,y + 10 );break;case 3://向右g.fill3DRect(x, y, 30, 5, false );g.fill3DRect(x , y + 15, 30, 5, false );g.fill3DRect(x + 5, y + 5, 20, 10, false );g.fillOval(x + 10, y + 5, 10, 10);g.drawLine(x + 15,y + 10, x + 30 , y + 10); break;default:break;}}public MyPanel (){hero = new Hero(30, 270 ,0,0,10 , true);//tanks = new tank(100,100, 2 ,1);//初始化敌人坦克Recoder.setHero(hero);for(int i = 0; i < enSize; i++){//创建敌人坦克的对象Recoder.getRecording();EnemyTask et = new EnemyTask((i + 1)*50, 0, 1, 1, 5 ,true); et.setEts(ets);Recoder.setEtss(ets);//传ets到RecoderThread t = new Thread(et);t.start();shot s = new shot(et.x + 10 , et.y + 30, et.direct);et.ss.add(s);Thread t2 = new Thread(s);t2.start();ets.add(et);//加入到集合中//et.setColor(1);}Recoder.setEnSize(enSize);}@Overridepublic void keyPressed(KeyEvent arg0) {// TODO Auto-generated method stubif(arg0.getKeyCode() == KeyEvent.VK_S){//hero.setX(hero.getX() ++ 1);// int i= hero.getY();// i += hero.speed;// hero.setY(i);this.hero.MoveDown();hero.setD(1);}if(arg0.getKeyCode() == KeyEvent.VK_W){//hero.setX(hero.getX() ++ 1);// int i= hero.getY();// i -= hero.speed;// hero.setY(i);hero.MoveUp();hero.setD(0);}if(arg0.getKeyCode() == KeyEvent.VK_D){//hero.setX(hero.getX() ++ 1);// int i= hero.getX();// i += hero.speed;// hero.setX(i);hero.MoveRight();hero.setD(3);}if(arg0.getKeyCode() == KeyEvent.VK_A){//hero.setX(hero.getX() ++ 1);// int i= hero.getX();// i -= hero.speed;// hero.setX(i);hero.MoveLeft();hero.setD(2);}//判断是否按下Jif(arg0.getKeyCode() == KeyEvent.VK_J){if(hero.ss.size() <= 4){this.hero.shotEnemy();//System.out.println("j");}}if(arg0.getKeyCode() == KeyEvent.VK_SPACE){//空格暂停 if(hero.speed != 0){a = hero.speed ;hero.speed = 0;for(int i = 0; i < ets.size(); i ++){//System.out.println("aaaaaaaaaaaaaa");EnemyTask et = ets.get(i);//System.out.println("speed" + et.speed);b = et.speed;et.speed = 0;directs[i] = et.direct;//System.out.println(et.direct);//System.out.println(directs[i]);//et.direct = 0;et.isdirects = false;for(int j = 0 ; j < et.ss.size(); j ++){shot s = et.ss.get(j);c = s.speed;s.speed = 0;System.out.println("aa");}}//System.out.println("b1 =" + b);isPaintShot = false;}else{hero.speed = a;//System.out.println("a2 =" + a);for(int i = 0; i < ets.size(); i ++){//System.out.println("bbbbbbbbbbbbbbbbbbb");EnemyTask et = ets.get(i);et.isdirects = true;et.speed = b;et.direct = directs[i];for(int j = 0 ; j < et.ss.size(); j ++){shot s = et.ss.get(j);s.speed = c;isPaintShot = true;}}s.isShot = true;}}if(arg0.getKeyCode() == KeyEvent.VK_K){this.KeepExit();System.exit(0);}if(arg0.getKeyCode() == KeyEvent.VK_L){this.GetKeeper();}this.repaint();}@Overridepublic void keyReleased(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void keyTyped(KeyEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void run() {//每隔100mswhile(true){try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.hintEnemyTank();this.hintMyTank();// for(int i = 0; i < et.ss.size(); i ++){// shot myshot = et.ss.get(i);// if(et.isLive == true){//// if(hero.isLive = true){// this.hintTank2(myshot, hero);// }//// }// }this.repaint();}}private void hintMyTank() {for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);for(int j = 0; j < et.ss.size(); j++ ){shot s = et.ss.get(j);if(s != null){if(hero.isLive){this.hintTank(s, hero);if(this.hintTank(s, hero)){//判断是否击中,返回true则hero数量减一Recoder.setMyLife(Recoder.getMyLife() - 1 );}}}}}}private void hintEnemyTank() {for(int i = 0; i < hero.ss.size(); i ++){shot myshot = hero.ss.get(i);if(myshot.isLive == true){for(int j = 0; j < ets.size(); j ++){EnemyTask et = ets.get(j);if(et.isLive = true){this.hintTank(myshot, et);if(this.hintTank(myshot, et)){hintEnemyTanks ++;Recoder.setEnNum(Recoder.getEnNum() - 1);}}}}}}private void KeepExit(){int [] heros = new int[]{hero.getX(),hero.getY(),hero.direct,};for(int i = 0 ; i < ets.size(); i ++){EnemyTask et = ets.get(i);TanksX[i] = et.getX();TanksY[i] = et.getY();ETdirects [i] = et.direct;for(int j = 1 ; j < et.ss.size(); j++){shot s = et.ss.get(j);ShotsX[j] = s.x;ShotsY[j] = s.y;}}for(int i = 0 ; i < hero.ss.size(); i++ ){shot s = hero.ss.get(i);HeroShotsX[i] = s.x ;HeroShotsY[i] = s.y;}BufferedWriter bw = null;try {bw = new BufferedWriter(new FileWriter("d:\\aa\\TanksX.txt")); for(int i = 0 ; i < enSize ; i ++){bw.write(TanksX[i] + "\r\n");bw.write(TanksY[i] + "\r\n");}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public void GetKeeper (){//继续游戏时还原数据BufferedReader br = null ;try {br = new BufferedReader(new FileReader("d:\\aa\\TanksX.txt")); for(int i = 0; i < enSize*2 ; i ++){if(i % 2 !=0){TanksY[i] = Integer.parseInt(br.readLine());System.out.println("TanksY" + TanksY[i]);}else{TanksX[i] = Integer.parseInt(br.readLine());System.out.println("TanksX" + TanksX[i]);}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}//class tank extends Tank{//// public tank(int x, int y, int direct,int type) {// super(x, y, direct,type);// // TODO Auto-generated constructor stub// }////}下面是工具类:package com.qq.TankGame;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Vector;class Recoder{/****/private static Vector<EnemyTask> ets = new Vector<EnemyTask>(); public static Vector<EnemyTask> getEts() {return ets;}public static void setEtss(Vector<EnemyTask> ets) {Recoder.ets = ets;}private static int enSize ;public static int getEnSize() {return enSize;}public static void setEnSize(int enSize) {Recoder.enSize = enSize;}private static Hero hero ;public static Hero getHero() {return hero;}public static void setHero(Hero hero) { Recoder.hero = hero;}public static void KeepExit(){//System.out.println(hero.getX());int [] TanksX = new int[20];int [] TanksY = new int[20];int [] ShotsX = new int[100];int [] ShotsY = new int[100];int [] ETdirects = new int[20];int [] HeroShotsX = new int[10];int [] HeroShotsY = new int[10];int [] heros = new int[]{hero.getX(),hero.getY(),hero.direct};for(int i = 0 ; i < ets.size(); i ++){EnemyTask et = ets.get(i);TanksX[i] = et.getX();TanksY[i] = et.getY();ETdirects [i] = et.direct;for(int j = 1 ; j < et.ss.size(); j++){shot s = et.ss.get(j);ShotsX[j] = s.x;ShotsY[j] = s.y;}}for(int i = 0 ; i < hero.ss.size(); i++ ){ shot s = hero.ss.get(i);HeroShotsX[i] = s.x ;HeroShotsY[i] = s.y;}BufferedWriter bw = null;BufferedWriter bw1 = null ;try {bw = new BufferedWriter(new FileWriter("d:\\aa\\TanksX.txt"));for(int i = 0 ; i < enSize ; i ++){bw.write(TanksX[i] + "\r\n");bw.write(TanksY[i] + "\r\n");}bw1 = new BufferedWriter(new FileWriter("d:\\aa\\KeepRecoding.txt")); bw1.write((20 - getEnNum()) + "\r\n" );} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {bw1.close();bw.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}private static int enNum = 5;public static int getEnNum() {return enNum;}public static void setEnNum(int enNum) {Recoder.enNum = enNum;}public static int getMyLife() {return myLife;}public static void setMyLife(int myLife) {Recoder.myLife = myLife;}private static int myLife = 3;private static BufferedReader br = null;public static void getRecording(){try {br = new BufferedReader(new FileReader("d:\\aa\\KeepRecoding.txt")); String n ;while((n = br.readLine()) != null ){String a = n;enNum = 20 - Integer.parseInt(n);}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {try {br.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}private static BufferedWriter bw = null;public static void KeepRecording (){try {bw = new BufferedWriter(new FileWriter("d:\\aa\\KeepRecoding.txt")); bw.write((20 - getEnNum()) + "\r\n" );} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {bw.close();//先开后关//new FileWriter("d:\\aa\\KeepRecoding.txt").close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public class Tank {int x = 0 ;int y = 0;int direct = 0; //方向int type = 0 ;//类型int speed = 30;//速度int color;boolean isLive;public int getColor() {return color;}public void setColor(int color) {this.color = color;}public int getS() {return speed;}public void setS(int speed) {this.speed = speed;}public Tank(int x , int y , int direct , int type, int speed, boolean isLive){ this.x = x;this.y = y;this.direct = direct;this.type= type;this.speed = speed;this.isLive = isLive;}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getD() {return direct;}public void setD(int direct) {this.direct = direct;}public int getT() {return type;}public void setT(int type) {this.type = type;}}class EnemyTask extends Tank implements Runnable{Vector<shot> ss = new Vector<shot>();Vector<EnemyTask> ets = new Vector<EnemyTask>();boolean isdirects = true;public EnemyTask(int x, int y, int direct, int type, int speed ,boolean isLive) {super(x, y, direct, type, speed, isLive);// TODO Auto-generated constructor stub}public boolean isTouchOhterTank (){boolean b = false;switch (this.direct) {case 0://此坦克向上for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);if(et != this){if(et.direct == 0 || et.direct == 1){//上或下if((this.x>=et.x && this.x <= et.x + 20//第一个点x在内&& this.y>=et.y && this.y <= et.y + 30)//第一个点y在内||(this.x + 20>=et.x && this.x+ 20 <= et.x + 20//第二个点x在内&& this.y >=et.y && this.y <= et.y + 30)//第二个点y在内){b = true;}}if(et.direct == 2 || et.direct == 3){//左或右if((this.x>=et.x && this.x <= et.x + 30//第一个点x在内&& this.y>=et.y && this.y <= et.y + 20)//第一个点y在内||(this.x + 20>=et.x && this.x+ 20 <= et.x + 30//第二个点x在内&& this.y >=et.y && this.y <= et.y + 20)//第二个点y在内){b = true;}}}}break;case 1://向下for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);if(et != this){if(et.direct == 0 || et.direct == 1){//上或下if((this.x>=et.x && this.x <= et.x + 20//第一个点x在内&& this.y + 30>=et.y && this.y + 30 <= et.y + 30)//第一个点y在内||(this.x + 20>=et.x && this.x+ 20 <= et.x + 20//第二个点x在内&& this.y + 30>=et.y && this.y + 30 <= et.y + 30)//第二个点y在内){b = true;}}if(et.direct == 2 || et.direct == 3){//左或右if((this.x>=et.x && this.x <= et.x + 30//第一个点x在内&& this.y + 30 >=et.y && this.y + 30 <= et.y + 20)//第一个点y在内||(this.x + 20 >=et.x && this.x+ 20 <= et.x + 30//第二个点x在内&& this.y + 30 >=et.y && this.y + 30 <= et.y + 20)//第二个点y在内){b = true;}}}}break;case 2:for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);if(et != this){if(et.direct == 0 || et.direct == 1){//上或下if((this.x>=et.x && this.x <= et.x + 20//第一个点x在内&& this.y>=et.y && this.y <= et.y + 30)//第一个点y在内||(this.x >=et.x && this.x<= et.x + 20//第二个点x在内&& this.y + 20 >=et.y && this.y + 20 <= et.y + 30)//第二个点y在内){b = true;}}if(et.direct == 2 || et.direct == 3){//左或右if((this.x>=et.x && this.x <= et.x + 30//第一个点x在内&& this.y>=et.y && this.y <= et.y + 20)//第一个点y在内||(this.x >=et.x && this.x<= et.x + 30//第二个点x在内&& this.y + 20>=et.y && this.y + 20 <= et.y + 20)//第二个点y在内){b = true;}}}}break;case 3:for(int i = 0; i < ets.size(); i++){EnemyTask et = ets.get(i);if(et != this){if(et.direct == 0 || et.direct == 1){//上或下if((this.x + 30>=et.x && this.x + 30 <= et.x + 20//第一个点x在内&& this.y>=et.y && this.y <= et.y + 30)//第一个点y在内||(this.x + 30 >=et.x && this.x+ 30 <= et.x + 20//第二个点x在内&& this.y + 20 >=et.y && this.y + 20 <= et.y + 30)//第二个点y在内){b = true;}}if(et.direct == 2 || et.direct == 3){//左或右if((this.x + 30>=et.x && this.x + 30 <= et.x + 30//第一个点x在内&& this.y>=et.y && this.y <= et.y + 20)//第一个点y在内||(this.x + 30>=et.x && this.x+ 30 <= et.x + 30//第二个点x在内&& this.y + 20>=et.y && this.y + 20 <= et.y + 20)//第二个点y在内){b = true;}}}}break;default:break;}return b ;}@Overridepublic void run() {int a = (int) (Math.random() * 10 + 2);//连动步数int times = 0;while(true){try {Thread.sleep(300);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}//if(x > 0 && x < 400 - 30 & y > 0 && y < 300 - 30){ //if(!this.isTouchOhterTank()){switch(this.direct){case 0://System.out.println(isTouchOhterTank());for(int i = 0 ;i < a ; i++){if(y - this.speed > 0 && !this.isTouchOhterTank()){y -= this.speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 1:for(int i = 0 ;i < a ; i++){if(y + speed < 300 - 30 && !this.isTouchOhterTank()){ y += this.speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 2:for(int i = 0 ;i < a ; i++){if(x - speed > 0 && !this.isTouchOhterTank()){x -= this.speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;case 3:for(int i = 0 ;i < a ; i++){if(x + speed < 400 - 30 && !this.isTouchOhterTank()){ x += this.speed;}try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}break;}//}times ++;if(times % 2 == 0){if(isLive){if(ss.size() < 3){shot s = null;switch (direct) {case 0://向上s = new shot(x + 10 , y ,0);ss.add(s);break;case 1://向下s = new shot(x + 10 , y + 30 , 1);ss.add(s);break;case 2://向左s = new shot(x , y + 10 , 2);ss.add(s);break;case 3://右s = new shot(x + 30 , y + 10 , 3);ss.add(s);break;default:break;}Thread t = new Thread(s);t.start();}}}//}// //随机改变方向// public void changeDirect(){//// }if(isdirects){this.direct = (int) (Math.random() * 4); }if(this.isLive == false){break;}if(ss.size() < 3){}}}public void setEts(Vector<EnemyTask> ets) { this.ets = ets;}// @Override// public void run() {// while(true){// try {// Thread.sleep(50);// } catch (InterruptedException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }//// y ++ ;// System.out.println(y);// }//// }}class Hero extends Tank{//public Hero(int x , int y, int direct, int type,int speed, boolean isLive){super(x, y, direct, type,speed , isLive);}Vector<shot> ss = new Vector<shot>();shot s = null;//开火public void shotEnemy(){//System.out.println("shotEnemy");if(Recoder.getMyLife() > 0){//生命没有了,不能发子弹 switch (this.direct) {case 0://向上s = new shot(x + 10 , y ,0);ss.add(s);break;case 3://右s = new shot(x + 30 , y + 10 , 3);ss.add(s);break;case 1://向下s = new shot(x + 10 , y + 30 , 1);ss.add(s);break;case 2://向左s = new shot(x , y + 10 , 2);ss.add(s);break;default:break;}Thread t = new Thread(s);t.start();}}//向上,下,左,右public void MoveUp(){if(y - this.speed > 0){y -= speed;}}public void MoveDown(){if(y + this.speed < 300 -30){y += speed;}}public void MoveLeft(){if(x - this.speed > 0){x -= speed;}}public void MoveRight(){if(x + this.speed < 400 -30){x += speed;}}}class shot implements Runnable{int x ,y;int direct;int speed = 20; //子弹速度boolean isShot = true;boolean isLive = true;//子弹是否活着 public shot(int x,int y, int direct){this.x = x;this.y = y;this.direct = direct;}@Overridepublic void run() {while(true){try {Thread.sleep(50);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}if(isShot){switch (direct) {case 0://向上y -= speed;break;case 1://下y += speed;break;case 2://右x -= speed;break;case 3://左x += speed;break;default:break;}}//System.out.println(x + " " + y);if(x < 0 || x > 400 || y < 0 || y > 300){ //System.out.println("this.islive = false");this.isLive = false;break;}}} }。
坦克大战java源代码
有些图片路径会出错要注意package ;import 坦克类class Tank{int x=0;int y=0;int color=0;int speed=1;int direct=0;boolean isLive=true;public Tank(int x,int y){=x;=y;}public int getX() {return x;}public void setX(int x) {= x;}public int getY() {return y;}public void setY(int y) {= y;}public int getDirect() {return direct;}public void setDirect(int direct) {= direct;}public int getColor() {return color;}public void setColor(int color) {= color;}};import .*;import .*;import .*;public class MyTankGame4 extends JFrame implements ActionListener{MyPanel mp=null;MyStartPanel msp=null;quals("New Game")){(msp);mp=new MyPanel();Thread mt=new Thread(mp);();(mp);(mp);(true);}}}etImage"/.jpg"));etImage"/"));image2=().getImage"/"));image3=().getImage"/"));}//控制坦克移动public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stubif()=={}else if()== {}else if()== {}else if()== {}else if()== {=0;=0;}//发射子弹(连发5枚子弹)if {if()=={(),(),());}}//控制坦克不能跑出边界if if if if//面板重绘();}public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub}public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub}public void run() {while(true){try {(50);} catch (InterruptedException e) {// TODO Auto-generated catch block();}//不停地调用敌人是否打中自己坦克函数for(int i=0;i<();i++){et=(i);for(int j=0;j< {Shot enshot= if==true&&==true){(enshot, hero);}}}//不停地调用是否打中敌人坦克函数for(int i=0;i< {Shot s= if(s!=null&&==true){for(int j=0;j<();j++){EnemyTank et=(j);if(et!=null&&==true){(s, et);}}}}//面板重绘();}}}。
c语言坦克大战最新代码
judge_tank_my(map,key);/*判断己方坦克运动函数*/
} aaa: ; } void map_all(int map[15][15])/*初始化地图函数*/ { int i,j; for(i=0;i<15;i++)
for(j=0;j<15;j++) switch(map[j][i]) { case 0: break; case 5:map_wall(i,j);break;/*地形*/ case 6:map_steel(i,j);break; case 7:map_water(i,j);break; case 8:map_border(i,j);break; case 9:map_base(i,j);break; }
void uptank(int i,int j,int color);/*画坦克函数*/ void downtank(int i,int j,int color); void lefttank(int i,int j,int color); void righttank(int i,int j,int color);
/* Note:Your choice is C IDE */ #include "graphics.h" #include "stdlib.h" #include "stdio.h"
#define a_UP 0x4800/*定义A坦克按键*/ #define a_DOWN 0x5000 #define a_LEFT 0x4b00 #define a_RIGHT 0x4d00 #define a_shoot 0x1c0d
void judge_moveshootway(int map[15][15],int i);/*炮弹运动时判断炮弹方 向函数*/ void judge_shoot(int m,int map[15][15],int i);/*判断炮弹打中的物体函数 */ void judge_shootway(int map[15][15],int i);/*炮弹打中物体时判断方向函 数*/
c语言坦克大战源代码
c语言坦克大战源代码/*游戏的整体思路大概是这样的?首先是欢迎界面,然后进入游戏界面,最后是gameover的界面。
本来打算做单人游戏,后来发现让敌人自主移动比较困难,所以改成了双人游戏?layer1控制按键是up,down,left,right,enter,player2控制按键是a,s,d,w,space。
*/#include<stdio.h>#include<string.h>#include<stdlib.h>#include<graphics.h>/*定义鼠标键值常量*/#define ESC 0x011b/*玩家1坦克按键*/#define UP 0x4800#define DOWN 0x5000#define LEFT 0x4b00#define RIGHT 0x4d00#define ENTER 0x1c0d#define up 0x1177/*玩家2坦克按键*/#define down 0x1f73#define left 0x1e61#define right 0x2064#define fire 0x246a/*定义游戏常量*//*双人游戏*/#define NUM 2/*坦克宽度*/#define WIDTH 20/*坦克的数量,宽度*//*定义global变量*******************************************//*子弹的属性*/struct myboom{/*如果子弹life为0则代表子弹没有发射*/int life;int x,y;int direction;};/*子弹们的初始属性*/struct myboom iboom[NUM]={{0},{0}};/*坦克的属性*/struct mytank{int life;int x,y;int direction;};/*坦克们的初始属性*/struct mytank itank[NUM]={{3,10*WIDTH,22*WIDTH},{1,440,40}};pre[NUM][2]={{10*WIDTH,22*WIDTH},{440,40}};/*xy[0]代表自己的坦克; xy[1]及以后代表敌军; 坦克坐标*//*存被子弹覆盖的图像*/void *boom_save[NUM];/*malloc开辟图像空间的大小*/int size;/*动画显示*/void *save[NUM];/*后来加上的。
坦克大战游戏编程实现
坦克大战游戏编程实现游戏编程实现坦克大战坦克大战是一款经典的电子游戏,在游戏中,玩家将控制一个坦克,通过操作坦克的移动和攻击,与其他玩家或电脑进行战斗。
本文将介绍如何使用编程语言实现坦克大战游戏。
设计思路在实现坦克大战游戏之前,首先需要明确游戏的基本要素和规则。
玩家将操作一个坦克,通过键盘或操纵杆控制坦克的移动和攻击。
游戏画面由地图、坦克、子弹等元素构成。
坦克可以向前、向后、向左、向右移动,可以发射子弹进行攻击。
玩家需要躲避敌方坦克的攻击,同时尽可能击败敌方坦克。
编程实现坦克的移动和攻击可以通过编程语言来实现。
以下是使用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的主窗口,并在窗口中添加了一个玩家坦克、敌方坦克和子弹的列表。
坦克大战源码
坦克大战源码根据韩顺平老师视频所作/**坦克大战* 防重叠*/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 {();();}}}。
python实现坦克大战游戏附详细注释
python实现坦克⼤战游戏附详细注释本⽂实例为⼤家分享了python实现坦克⼤战的具体代码,供⼤家参考,具体内容如下#功能实现游戏主窗⼝import pygame,time,random#导⼊模块_display = pygame.display#赋值给⼀个变量调⽤时⽅便color_red = pygame.Color(255,0,0)#同上 vclass MainGame(object):screen_width = 900#游戏界⾯宽度screen_height = 550#界⾯的⾼度Tank_p1 = None#坦克对象window = None #窗⼝对象EnemyTank_list = []# 存储所有敌⽅坦克EnemTank_count = 10# 要创建的敌⽅坦克的数量Bullet_list = [] #创建我⽅⼦弹列表EnemyTank_bullet_list = []Explode_list= []wall_list = []def startGame(self):pygame.display.init()#初始化游戏模块的显⽰MainGame.window = _display.set_mode([MainGame.screen_width,MainGame.screen_height])#⽣成并加载游戏窗⼝、\#pygame.display模块及set_mode⽅法和pygame相关⽅法调⽤设置# 见<<https:///docs/ref/display.html#pygame.display.set_mode>> UC浏览器实现⾃动翻译pygame.display.set_caption("坦克⼤战v1.0")#s设置游戏标题self.creatEnemyTank()#类中调⽤初始敌⽅坦克⽅法self.creatMyTank()#创建我⽅坦克self.creatWalls()#创建障碍物while True:#⽆限循环所有⾏为⽅法都要⽆限制的显⽰MainGame.window.fill(pygame.Color(0,0,0))#窗⼝颜⾊设置 Window在开始⽅法已设置为游戏窗⼝self.getEvent()#死循环中获取事件的值对其进⾏相应处理MainGame.window.blit(self.drawText("剩余敌⽅数量%d" %len(MainGame.EnemyTank_list)),(7, 7))#循环游戏窗⼝加载⽂本 bilt⽅法在页⾯写⼊另⼀个 self.blitWalls()if MainGame.Tank_p1 and MainGame.Tank_p1.alive:MainGame.Tank_p1.displayTank()#循环调⽤⽣成的坦克对象(显⽰)⽅法self.blitEnemyTank()# 此类中⽤self 循环展⽰敌⽅坦克if MainGame.Tank_p1 and not MainGame.Tank_p1.stop:MainGame.Tank_p1.move()# 移动MainGame.Tank_p1.hitWall()#撞击墙壁MainGame.Tank_p1.hitEnemyTank()#撞击敌⽅坦克⽅法self.blitEnemyBullet()#显⽰敌⽅坦克⼦弹self.blitBullet()#显⽰炮弹self.blitExplode()#显⽰爆炸效果time.sleep(0.02)_display.update()#获取更新#将带有⽂字的surface 绘制到窗⼝中循环# 创建敌⽅坦克def creatEnemyTank(self):#创建敌⽅坦克top = 100for i in range(MainGame.EnemTank_count):#MainGame.EnemTank_count=5 五次循环创建敌⽅坦克speed = random.randint(3, 6) # 随机模块 random.randint# 每次都随机⽣成⼀个left值left = random.randint(1, 7)eTank = EnemyTank(left * 100, top, speed)#⽣成敌⽅坦克类对象传⼊参数 left为随机MainGame.EnemyTank_list.append(eTank)#将创建的每⼀个敌⽅坦克添加到列表# 将坦克加⼊到窗⼝中def creatMyTank(self):MainGame.Tank_p1 = MyTank(400, 480) # ⽣成⼀个坦克类的实例对象music = Music("img/start.wav")music.play()def creatWalls(self):for i in range(1,10):wall = Wall(60*i,250)MainGame.wall_list.append(wall)def blitWalls(self):for wall in MainGame.wall_list:if wall.live == True:wall.displayWall()else:MainGame.wall_list.remove(wall)def blitEnemyTank(self):#显⽰敌⽅坦克若出现坦克图⽚重叠也是符合逻辑for eTank in MainGame.EnemyTank_list:if eTank.live :eTank.displayTank()#将列表中每⼀个进⾏显⽰ eTank为敌⽅坦克类对象调⽤⽗类Tank类中显⽰⽅法eTank.randMove()eTank.hitWall()eTank.hitMyTank()ebullet = eTank.shot()if ebullet:#如果不为空MainGame.EnemyTank_bullet_list.append(ebullet)else:MainGame.EnemyTank_list.remove(eTank)def blitEnemyBullet(self):#将敌⽅坦克加⼊到窗⼝中for ebullet in MainGame.EnemyTank_bullet_list:if ebullet.alive:ebullet.display_bullet()ebullet.bulletMove()ebullet.hitWalls()if MainGame.Tank_p1.alive:ebullet.hitMyTank()else:MainGame.EnemyTank_bullet_list.remove(ebullet)def blitBullet(self):#显⽰⼦弹for bullet in MainGame.Bullet_list:#事件中获的⼦弹的列表进⾏遍历类似显⽰坦克⽅法逐个展⽰if bullet.alive:#Bullet类中设置的标签来判断⼦弹的存活 True为⽣根据炮弹移动⽅法bulletmove()中所加限制条件 bullet.display_bullet()#调⽤列表中⼦弹对象的显⽰⽅法bullet.bulletMove()#⼦弹的移动bullet.hitEnemyTank()#调⽤与敌⽅坦克的碰撞检测⽅法bullet.hitWalls()#d调⽤⼦弹碰撞墙壁else:MainGame.Bullet_list.remove(bullet)#如果为False bulletmove()中触碰墙壁就是False 就从列表删除循环执⾏ def blitExplode(self):for explode in MainGame.Explode_list:if explode.live:explode.display_explode()music = Music("img/blast.wav")music.play()else:MainGame.Explode_list.remove(explode)def drawText(self,content):#⽂本写⼊游戏窗⼝pygame.font.init()#初始化字体font = pygame.font.SysFont("kaiti",18)#创建字体对象text_sf = font.render(content,True,color_red)#字体样式对象return text_sf #返回内容的surfacedef getEvent(self):#获取所有事件eventlist = pygame.event.get()#所有事件列表for event in eventlist:#遍历每⼀个事件进⾏判断键盘输⼊的字符#type属性if event.type == pygame.QUIT:#如果是QUIT(就是点击窗⼝的退出按钮叉号)print("退出游戏")self.gameOver()#退出⽅法if event.type == pygame.KEYUP:#如果键盘按钮抬起并且是上下左右键if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP\or event.key == pygame.K_DOWN:if MainGame.Tank_p1 and MainGame.Tank_p1.alive:MainGame.Tank_p1.stop = True#stop为True 按钮抬起就停⽌ start⽅法中的开关实现坦克按住按钮持续移动 if event.type == pygame.KEYDOWN:#如果事件的类型为按下按键进⾏如下判断if event.key == pygame.K_ESCAPE :self.creatMyTank()if MainGame.Tank_p1 and MainGame.Tank_p1.alive:if event.key == pygame.K_LEFT:#如果为左⽅向键如下为同⼀类型print("向左移动")MainGame.Tank_p1.direction = "L"#设置坦克⽅向进⾏判断向左就是L,# 并设置游戏窗⼝的界限还可以利⽤⽅向作为字典的键获取坦克图⽚坦克的移动⽅向#就是加载不同⽅向的坦克图⽚呈现出移动的效果MainGame.Tank_p1.stop = False#坦克移动的开关循环使⽤ False为移动if event.key == pygame.K_RIGHT:print("向右移动")MainGame.Tank_p1.direction = "R"MainGame.Tank_p1.stop = Falseif event.key ==pygame.K_UP:print("向上移动")MainGame.Tank_p1.direction = "U"MainGame.Tank_p1.stop = Falseif event.key == pygame.K_DOWN:print("向下移动")MainGame.Tank_p1.direction = "D"MainGame.Tank_p1.stop = Falseif event.key == pygame.K_SPACE:#空格键发射⼦弹if len(MainGame.Bullet_list) < 3:#控制⼦弹在屏幕显⽰的数量太多没有游戏体验列表中存储三个m = Bullet(MainGame.Tank_p1)#⼦弹类对象添加到列表开始⽅法调⽤显⽰⼦弹⼦弹触碰墙壁列表内移除对象MainGame.Bullet_list.append(m)music =Music("img/fire.wav")music.play()def gameOver(self):#游戏结束⽅法exit()class BaseItem(pygame.sprite.Sprite):def __init__(self):pygame.sprite.Sprite.__init__(self)class Tank(BaseItem):#坦克的⽗类def __init__(self,left,top):#坦克图⽚集合self.images = {"U":pygame.image.load("img/p1tankU.gif"),"D": pygame.image.load("img/p1tankD.gif"),"L":pygame.image.load("img/p1tankL.gif"),"R": pygame.image.load("img/p1tankR.gif"),}#坦克各⽅向图⽚的加载#坦克的⽅向self.direction = "U"#坦克初始化时候的默认图⽚,根据坦克的⽅向从字典⾥去提取self.image = self.images[self.direction]#坦克的区域(left,top,width,height)坦克位置以及坦克的⼤⼩self.rect = self.image.get_rect()self.rect.left = left#坦克距离左边位置修改默认参数指定的位置self.rect.top = top#将坦克距离上边的位置修改我指定的位置self.speed = 15#设置坦克的速度self.stop = True #设置移动的开关self.oldtop = self.rect.topself.oldleft = self.rect.leftdef move(self):self.oldtop = self.rect.topself.oldleft = self.rect.leftif self.direction == "U":#向上时if self.rect.top > 0:#self.rect = self.image.get_rect()# self.rect.top = top#将坦克距离上边的位置修改我指定的位置self.rect.top -= self.speed#坦克的速度距离每⼀次调⽤时相减直到<0时elif self.direction == "D":#向下时if self.rect.top < MainGame.screen_height-MainGame.Tank_p1.rect.height:#下边界⼩于窗⼝的⾼度减去坦克⾃⾝的⾼度的距离 self.rect.top += self.speed #距离加速度的距离循环⼀次添加⼀次elif self.direction == "L":if self.rect.left > 0:self.rect.left -= self.speedelif self.direction == "R":if self.rect.left < MainGame.screen_width -MainGame.Tank_p1.rect.width:self.rect.left += self.speeddef stay(self):self.rect.left = self.oldleftself.rect.top = self.oldtopdef hitWall(self):for wall in MainGame.wall_list:if pygame.sprite.collide_rect(wall,self):self.stay()def shot(self):return Bullet(self)def displayTank(self):#坦克显⽰⽅法#1.重新设置坦克的图⽚self.image = self.images[self.direction]#2.将坦克加⼊到窗⼝中MainGame.window.blit(self.image,self.rect)#调⽤MainGame window⽅法# 传⼊图⽚和位置 self.rect = self.image.get_rect()class MyTank(Tank):def __init__(self,left,top):super(MyTank,self).__init__(left,top)def hitEnemyTank(self):for etank in MainGame.EnemyTank_list:if pygame.sprite.collide_rect(etank,self):self.stay()class EnemyTank(Tank):#敌⽅坦克类def __init__(self,left,top,speed):#初始化敌⽅坦克三个参数self.images = {"U": pygame.image.load("img/enemy1U.gif"),"D": pygame.image.load("img/enemy1D.gif"),"L": pygame.image.load("img/enemy1L.gif"),"R": pygame.image.load("img/enemy1R.gif"), }#加载敌⽅坦克图⽚# 坦克的⽅向self.direction = self.randDirection()#⾃定义坦克的随机⽅向self.image = self.images[self.direction]#坦克的信息从字典中以键获得值# 坦克所在的区域 Rect->self.rect = self.image.get_rect()#获得坦克图⽚的距离距左和距上# 指定坦克初始化位置分别距x,y轴的位置self.rect.left = left#距左的位置>>形参self.rect.top = top#距上的位置# 新增速度属性self.speed = speed #速度>>初始化时设置self.stop = Trueself.step = 50#设置步数self.live = Truedef randDirection(self):#随机⽣成敌⽅坦克的⽅向图⽚num = random.randint(1, 4)if num == 1:return 'U'elif num == 2:return 'D'elif num == 3:return 'L'elif num == 4:return 'R'def randMove(self):#敌⽅坦克随机移动if self.step <= 0:#如果步数为0self.direction = self.randDirection()#⽅向为随机⽅向self.step = 30# 重置步数else:self.move()#移动坦克位置不断改变self.step -= 1#步数每次循环减⼀def shot(self):s = random.randint(1,1000)if s <30:return Bullet(self)def hitMyTank(self):if pygame.sprite.collide_rect(self,MainGame.Tank_p1):self.stay()class Bullet(BaseItem):#炮弹类def __init__(self,tank):self.image = pygame.image.load("img\enemymissile.gif")self.direction = tank.direction#⼦弹速度self.speed = 18self.rect = self.image.get_rect()#获得⼦弹的对象的坐标只计算距离左侧和和上⾯#⼦弹初始化位置要根据坦克⼤⽅向进⾏调整可以⾃⼰画图计算if self.direction == "U":#⼦弹的位置 left += 坦克宽度的⼀半 - ⼦弹的宽度的⼀半self.rect.left = tank.rect.left + tank.rect.width/2 - self.rect.width/2self.rect.top = tank.rect.top - self.rect.heightelif self.direction == "D":self.rect.left = tank.rect.left + tank.rect.width / 2 - self.rect.width / 2self.rect.top = tank.rect.top - self.rect.heightelif self.direction == "L":self.rect.left = tank.rect.left - tank.rect.width / 2 - self.rect.width / 2self.rect.top = tank.rect.top + tank.rect.width/2 -self.rect.width/2elif self.direction == "R":self.rect.left = tank.rect.left + tank.rect.width / 2self.rect.top = tank.rect.top + tank.rect.width/2 -self.rect.width/2speed = 10#速度alive = True#设置⼀个⼩标签作判断def bulletMove(self):#炮弹移动if self.direction == "U":if self.rect.top > 0 :#距离限制计算 self⼦弹对象本⾝ rect.top距离窗⼝上⽅ rect.left左侧 self.rect.top -= self.speedelse:self.alive = False#此为<0时的情况同下都是触碰墙壁时的情况elif self.direction == "D":if self.rect.top < MainGame.screen_height - self.rect.height:#屏幕⾼度 - ⼦弹的⾼度 self.rect.top += self.speedelse:self.alive = Falseelif self.direction == "L":if self.rect.left > 0:self.rect.left -= self.speedelse:self.alive = Falseelif self.direction == "R":if self.rect.left < MainGame.screen_width - self.rect.width: self.rect.left += self.speedelse:self.alive = Falsedef hitEnemyTank(self):#我⽅⼦弹与敌⽅坦克相碰for etank in MainGame.EnemyTank_list:#敌⽅坦克列表if pygame.sprite.collide_rect(etank,self):#sprite中的相撞测试 explode = Explode(etank)#产⽣⼀个爆炸效果MainGame.Explode_list.append(explode)self.alive = Falseetank.live = Falsedef hitMyTank(self):if pygame.sprite.collide_rect(self,MainGame.Tank_p1):explode = Explode(MainGame.Tank_p1)MainGame.Explode_list.append(explode)MainGame.Tank_p1.alive = Falseself.alive = Falsedef hitWalls(self):for wall in MainGame.wall_list:if pygame.sprite.collide_rect(wall,self):self.alive = Falsewall.hp -= 1if wall.hp <= 0:wall.live = Falsedef display_bullet(self):#显⽰⼦弹⽅法MainGame.window.blit(self.image,self.rect)#窗⼝写⼊class Explode:#爆炸效果def __init__(self,tank):self.step = 0self.rect = tank.rectself.images = [pygame.image.load("img/blast0.gif"),pygame.image.load("img/blast1.gif"),pygame.image.load("img/blast2.gif"),pygame.image.load("img/blast3.gif"),pygame.image.load("img/blast4.gif"),pygame.image.load("img/blast5.gif"),pygame.image.load("img/blast6.gif"),pygame.image.load("img/blast7.gif"),]self.live = Trueself.image = self.images[self.step]def display_explode(self):#显⽰爆炸效果if self.step < len(self.images):MainGame.window.blit(self.image,self.rect)self.image = self.images[self.step]self.step += 1else:self.live = Falseself.step = 0class Wall:def __init__(self,left,top):self.image = pygame.image.load("img/steels.gif")self.rect = self.image.get_rect()self.rect.left = leftself.rect.top = topself.live = Trueself.hp = 3def displayWall(self):#显⽰障碍物MainGame.window.blit(self.image,self.rect)class Music:#⾳效def __init__(self,filename):self.filename = filenamepygame.mixer.init()#混合器的初始pygame.mixer.music.load(self.filename)#加载⾳乐⽂件def play(self):pygame.mixer.music.play(loops=0)#播放⾳乐MainGame().startGame()更多关于python游戏的精彩⽂章请点击查看以下专题:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
坦克大战的游戏代码
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;//}}}。
坦克大战代码
坦克大战代码// 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;。
马士兵坦克大战经典源代码
package com.bjsxt.tank;import java.awt.*;import java.awt.event.*;import java.util.List;import java.util.ArrayList;/*** 这个类的作用是坦克游戏的主窗口* @author mashibing**/public class TankClient extends Frame {/*** 整个坦克游戏的宽度*/public static final int GAME_WIDTH = 800;public static final int GAME_HEIGHT = 600;Tank myTank = new Tank(50, 50, true, Tank.Direction.STOP, this);Wall w1 = new Wall(100, 200, 20, 150, this), w2 = new Wall(300, 100, 300, 20, this);List<Explode> explodes = new ArrayList<Explode>();List<Missile> missiles = new ArrayList<Missile>();List<Tank> tanks = new ArrayList<Tank>();Image offScreenImage = null;Blood b = new Blood();public void paint(Graphics g) {/** 指明子弹-爆炸-坦克的数量* 以及坦克的生命值*/g.drawString("missiles count:" + missiles.size(), 10, 50);g.drawString("explodes count:" + explodes.size(), 10, 70);g.drawString("tanks count:" + tanks.size(), 10, 90);g.drawString("tanks life:" + myTank.getLife(), 10, 110);if(tanks.size() <= 0) {for(int i=0; i<5; i++) {tanks.add(new Tank(50 + 40*(i+1), 50, false, Tank.Direction.D, this));}}for(int i=0; i<missiles.size(); i++) {Missile m = missiles.get(i);m.hitTanks(tanks);m.hitTank(myTank);m.hitWall(w1);m.hitWall(w2);m.draw(g);//if(!m.isLive()) missiles.remove(m);//else m.draw(g);}for(int i=0; i<explodes.size(); i++) {Explode e = explodes.get(i);e.draw(g);}for(int i=0; i<tanks.size(); i++) {Tank t = tanks.get(i);t.collidesWithWall(w1);t.collidesWithWall(w2);t.collidesWithTanks(tanks);t.draw(g);}myTank.draw(g);myTank.eat(b);w1.draw(g);w2.draw(g);b.draw(g);}public void update(Graphics g) {if(offScreenImage == null) {offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT);}Graphics gOffScreen = offScreenImage.getGraphics();Color c = gOffScreen.getColor();gOffScreen.setColor(Color.GREEN);gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);gOffScreen.setColor(c);paint(gOffScreen);g.drawImage(offScreenImage, 0, 0, null);}/*** 本方法显示坦克主窗口**/public void lauchFrame() {for(int i=0; i<10; i++) {tanks.add(new Tank(50 + 40*(i+1), 50, false, Tank.Direction.D, this));}//this.setLocation(400, 300);this.setSize(GAME_WIDTH, GAME_HEIGHT);this.setTitle("TankWar");this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});this.setResizable(false);this.setBackground(Color.GREEN);this.addKeyListener(new KeyMonitor());setVisible(true);new Thread(new PaintThread()).start();}public static void main(String[] args) {TankClient tc = new TankClient();uchFrame();}private class PaintThread implements Runnable {public void run() {while(true) {repaint();try {Thread.sleep(50);} catch (InterruptedException e) {e.printStackTrace();}}}}private class KeyMonitor extends KeyAdapter {public void keyReleased(KeyEvent e) {myTank.keyReleased(e);}public void keyPressed(KeyEvent e) {myTank.keyPressed(e);}}}package com.bjsxt.tank;import java.awt.*;import java.awt.event.*;import java.util.*;public class Tank {public static final int XSPEED = 5;public static final int YSPEED = 5;public static final int WIDTH = 30;public static final int HEIGHT = 30;private boolean live = true;private BloodBar bb = new BloodBar();private int life = 100;TankClient tc;private boolean good;private int x, y;private int oldX, oldY;private static Random r = new Random();private boolean bL=false, bU=false, bR=false, bD = false;enum Direction {L, LU, U, RU, R, RD, D, LD, STOP};private Direction dir = Direction.STOP;private Direction ptDir = Direction.D;private int step = r.nextInt(12) + 3;public Tank(int x, int y, boolean good) {this.x = x;this.y = y;this.oldX = x;this.oldY = y;this.good = good;}public Tank(int x, int y, boolean good, Direction dir, TankClient tc) { this(x, y, good);this.dir = dir;this.tc = tc;}public void draw(Graphics g) {if(!live) {if(!good) {tc.tanks.remove(this);}return;}Color c = g.getColor();if(good) g.setColor(Color.RED);else g.setColor(Color.BLUE);g.fillOval(x, y, WIDTH, HEIGHT);g.setColor(c);if(good) bb.draw(g);switch(ptDir) {case L:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y + Tank.HEIGHT/2);break;case LU:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y);break;case U:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH/2, y);break;case RU:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y);break;case R:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y + Tank.HEIGHT/2);break;case RD:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH, y + Tank.HEIGHT);break;case D:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x + Tank.WIDTH/2, y + Tank.HEIGHT);break;case LD:g.drawLine(x + Tank.WIDTH/2, y + Tank.HEIGHT/2, x, y + Tank.HEIGHT);break;}move();}void move() {this.oldX = x;this.oldY = y;switch(dir) {case L:x -= XSPEED;break;case LU:x -= XSPEED;y -= YSPEED;break;case U:y -= YSPEED;break;case RU:x += XSPEED;y -= YSPEED;break;case R:x += XSPEED;break;case RD:x += XSPEED;y += YSPEED;break;case D:y += YSPEED;break;case LD:x -= XSPEED;y += YSPEED;break;case STOP:break;}if(this.dir != Direction.STOP) {this.ptDir = this.dir;}if(x < 0) x = 0;if(y < 30) y = 30;if(x + Tank.WIDTH > TankClient.GAME_WIDTH) x = TankClient.GAME_WIDTH - Tank.WIDTH;if(y + Tank.HEIGHT > TankClient.GAME_HEIGHT) y = TankClient.GAME_HEIGHT - Tank.HEIGHT;if(!good) {Direction[] dirs = Direction.values();if(step == 0) {step = r.nextInt(12) + 3;int rn = r.nextInt(dirs.length);dir = dirs[rn];}step --;if(r.nextInt(40) > 38) this.fire();}}private void stay() {x = oldX;y = oldY;}public void keyPressed(KeyEvent e) {int key = e.getKeyCode();switch(key) {case KeyEvent.VK_F2 :if(!this.live) {this.live = true;this.life = 100;}break;case KeyEvent.VK_LEFT :bL = true;break;case KeyEvent.VK_UP :bU = true;break;case KeyEvent.VK_RIGHT :bR = true;break;case KeyEvent.VK_DOWN :bD = true;break;}locateDirection();}void locateDirection() {if(bL && !bU && !bR && !bD) dir = Direction.L;else if(bL && bU && !bR && !bD) dir = Direction.LU;else if(!bL && bU && !bR && !bD) dir = Direction.U;else if(!bL && bU && bR && !bD) dir = Direction.RU;else if(!bL && !bU && bR && !bD) dir = Direction.R;else if(!bL && !bU && bR && bD) dir = Direction.RD;else if(!bL && !bU && !bR && bD) dir = Direction.D;else if(bL && !bU && !bR && bD) dir = Direction.LD;else if(!bL && !bU && !bR && !bD) dir = Direction.STOP; }public void keyReleased(KeyEvent e) {int key = e.getKeyCode();switch(key) {case KeyEvent.VK_CONTROL:fire();break;case KeyEvent.VK_LEFT :bL = false;break;case KeyEvent.VK_UP :bU = false;break;case KeyEvent.VK_RIGHT :bR = false;break;case KeyEvent.VK_DOWN :bD = false;break;case KeyEvent.VK_A :superFire();break;}locateDirection();}public Missile fire() {if(!live) return null;int x = this.x + Tank.WIDTH/2 - Missile.WIDTH/2;int y = this.y + Tank.HEIGHT/2 - Missile.HEIGHT/2;Missile m = new Missile(x, y, good, ptDir, this.tc);tc.missiles.add(m);return m;}public Missile fire(Direction dir) {if(!live) return null;int x = this.x + Tank.WIDTH/2 - Missile.WIDTH/2;int y = this.y + Tank.HEIGHT/2 - Missile.HEIGHT/2;Missile m = new Missile(x, y, good, dir, this.tc);tc.missiles.add(m);return m;}public Rectangle getRect() {return new Rectangle(x, y, WIDTH, HEIGHT);}public boolean isLive() {return live;}public void setLive(boolean live) {this.live = live;}public boolean isGood() {return good;}/*** 撞墙* @param w 被撞的墙* @return 撞上了返回true,否那么false*/public boolean collidesWithWall(Wall w) {if(this.live && this.getRect().intersects(w.getRect())) {this.stay();return true;}return false;}public boolean collidesWithTanks(java.util.List<Tank> tanks) {for(int i=0; i<tanks.size(); i++) {Tank t = tanks.get(i);if(this != t) {if(this.live && t.isLive() && this.getRect().intersects(t.getRect())) { this.stay();t.stay();return true;}}}return false;}private void superFire() {Direction[] dirs = Direction.values();for(int i=0; i<8; i++) {fire(dirs[i]);}}public int getLife() {return life;}public void setLife(int life) {this.life = life;}private class BloodBar {public void draw(Graphics g) {Color c = g.getColor();g.setColor(Color.RED);g.drawRect(x, y-10, WIDTH, 10);int w = WIDTH * life/100 ;g.fillRect(x, y-10, w, 10);g.setColor(c);}}public boolean eat(Blood b) {if(this.live && b.isLive() && this.getRect().intersects(b.getRect())) { this.life = 100;b.setLive(false);return true;}return false;}}package com.bjsxt.tank;import java.awt.*;import java.util.List;public class Missile {public static final int XSPEED = 10;public static final int YSPEED = 10;public static final int WIDTH = 10;public static final int HEIGHT = 10;int x, y;Tank.Direction dir;private boolean good;private boolean live = true;private TankClient tc;public Missile(int x, int y, Tank.Direction dir) {this.x = x;this.y = y;this.dir = dir;}public Missile(int x, int y, boolean good, Tank.Direction dir, TankClient tc) { this(x, y, dir);this.good = good;this.tc = tc;}public void draw(Graphics g) {if(!live) {tc.missiles.remove(this);return;}Color c = g.getColor();g.setColor(Color.BLACK);g.fillOval(x, y, WIDTH, HEIGHT);g.setColor(c);move();}private void move() {switch(dir) {case L:x -= XSPEED;break;case LU:x -= XSPEED;y -= YSPEED;break;case U:y -= YSPEED;break;case RU:x += XSPEED;y -= YSPEED;break;case R:x += XSPEED;break;case RD:x += XSPEED;y += YSPEED;break;case D:y += YSPEED;break;case LD:x -= XSPEED;y += YSPEED;break;case STOP:break;}if(x < 0 || y < 0 || x > TankClient.GAME_WIDTH || y > TankClient.GAME_HEIGHT) { live = false;}}public boolean isLive() {return live;}public Rectangle getRect() {return new Rectangle(x, y, WIDTH, HEIGHT);}public boolean hitTank(Tank t) {if(this.live && this.getRect().intersects(t.getRect()) && t.isLive() && this.good != t.isGood()) {if(t.isGood()) {t.setLife(t.getLife()-20);if(t.getLife() <= 0) t.setLive(false);} else {t.setLive(false);}this.live = false;Explode e = new Explode(x, y, tc);tc.explodes.add(e);return true;}return false;}public boolean hitTanks(List<Tank> tanks) {for(int i=0; i<tanks.size(); i++) {if(hitTank(tanks.get(i))) {return true;}}return false;}public boolean hitWall(Wall w) {if(this.live && this.getRect().intersects(w.getRect())) {this.live = false;return true;}return false;}}package com.bjsxt.tank;import java.awt.*;public class Explode {int x, y;private boolean live = true;private TankClient tc ;int[] diameter = {4, 7, 12, 18, 26, 32, 49, 30, 14, 6};int step = 0;public Explode(int x, int y, TankClient tc) {this.x = x;this.y = y;this.tc = tc;}public void draw(Graphics g) {if(!live) {tc.explodes.remove(this);return;}if(step == diameter.length) {live = false;step = 0;return;}Color c = g.getColor();g.setColor(Color.ORANGE);g.fillOval(x, y, diameter[step], diameter[step]);g.setColor(c);step ++;}}package com.bjsxt.tank;import java.awt.*;public class Blood {int x, y, w, h;TankClient tc;int step = 0;private boolean live = true;//指明血块运动的轨迹,由pos中各个点构成private int[][] pos = {{350, 300}, {360, 300}, {375, 275}, {400, 200}, {360, 270}, {365, 290}, {340, 280}};public Blood() {x = pos[0][0];y = pos[0][1];w = h = 15;}public void draw(Graphics g) {if(!live) return;Color c = g.getColor();g.setColor(Color.MAGENTA);g.fillRect(x, y, w, h);g.setColor(c);move();}private void move() {step ++;if(step == pos.length){step = 0;}x = pos[step][0];y = pos[step][1];}public Rectangle getRect() {return new Rectangle(x, y, w , h);}public boolean isLive() {return live;}public void setLive(boolean live) {this.live = live;}}package com.bjsxt.tank;import java.awt.*;public class Wall {int x, y, w, h;TankClient tc ;public Wall(int x, int y, int w, int h, TankClient tc) { this.x = x;this.y = y;this.w = w;this.h = h;this.tc = tc;}public void draw(Graphics g) {g.fillRect(x, y, w, h);}public Rectangle getRect() {return new Rectangle(x, y, w, h);}}。
c语言编写坦克大战源代码
#include "tank.h"#include "ConOperator.h"#include <time.h>#include <windows.h>#include <conio.h>#include <iostream>using namespace std;TankGame::TankGame(int w, int h){// 设定当前关数no = 1;// 设定游戏整体高宽wide = w;high = h;HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);COORD sizePos = {2 * wide, high};SetConsoleScreenBufferSize(hStdOut, sizePos);// 分配游戏空间状态表gameSpace = new GameSpace*[high];for (int i = 0; i != high; i++)gameSpace[i] = new GameSpace[wide];// 添加围墙wall = new Wall(gameSpace, wide, high);wall->draw();}void TankGame::load_init(){// 初始化游戏空间for (int y = 1; y != high-1; y++) {for (int x = 1; x != wide-1; x++) {gameSpace[y][x].have = false;gameSpace[y][x].kind = 0;gameSpace[y][x].no = 0;}}// 添加地图map.load(gameSpace, no);// 初始化自己坦克me.init_xy();me.trans_direction(1);me.set_no(0);me.init_move(gameSpace, wide / 2 - 2, high - 5);// 按顺序诞生敌人坦克creatPlace = 0;for (int i = 0; i != 3; i++) {freezeTime[i] = REBIRTHTIME;enemy[i].init_xy();enemy[i].set_kind(2);enemy[i].set_no(i+1);reset(enemy[i]);}// 数目初始化leftCount = 17;existCount = 3;// 显示图片me.draw_tank();for (int i = 0; i != 3; i++)enemy[i].draw_tank();map.draw();}TankGame::~TankGame(){if (wall)delete wall;if (gameSpace) {for (int i = 0; i != high; i++)delete[] gameSpace[i];delete[] gameSpace;}}void TankGame::reset(Tank& tank){bool success = false;int t = 3;while (t && !success) {creatPlace++;if (creatPlace == 4)creatPlace = 1;// 诞生地点选择switch (creatPlace) {case 1:tank.trans_direction(3); //朝下if (tank.reset(gameSpace,1,1))success = true;break;case 2:tank.trans_direction(3);if (tank.reset(gameSpace,wide / 2 - 2, 1))success = true;break;case 3:tank.trans_direction(3);if (tank.reset(gameSpace,wide - 4, 1))success = true;break;}if (!success)t--;}}void TankGame::start(){char command;enter_picture(command);if (command != ENTER)return;while (me.blood > 0) {// init data for runingload_init();// run a taskruning_a_task();// determine why returnif (me.blood > 0) {no++;if (no > map.total) {success_gameover();break;}char command;turn_to_next_task(command);if (command != ENTER)break;}else game_over();}}//voidvoid TankGame::runing_a_task(){while ((leftCount || existCount) && me.blood) {clock_t now = clock();char command = -1; // 主人命令while (clock() - now < TIME_UNIT) // 小于一个时间片,暂停update_keyBoard_char(command);/*更新敌人坦克*/for (int i = 0; i != 3; i++) {if (enemy[i].blood == 0)continue;if (enemy[i].freezeTime == 0) {enemy[i].rand_direction(gameSpace); // 产生随机方向}else {if (enemy[i].speed == 0) {enemy[i].move(gameSpace);if (bullet[i+1].disapper) {int shot = -1;bullet[i+1] = enemy[i].rand_shot(gameSpace,i+1, shot);if (shot == 0)me.be_shot(gameSpace);bullet[i+1].registration(gameSpace);}enemy[i].freezeTime--;} else {enemy[i].speed--;}}}/*更新自己坦克*/if (command >=0 && command < 4) {me.trans_to_direction(command);me.move(gameSpace);}/*更新子弹*/for (int i = 0; i !=4; i++) {if (!bullet[i].disapper) { // 存在的子弹int shot;bullet[i].move(gameSpace, shot); // 运行,是否射中if (shot == 0)me.be_shot(gameSpace);else if (shot >= 1 && shot <= 3) {enemy[shot-1].be_shot(gameSpace);existCount--;} else if (shot >= 7 && shot <= 10) {bullet[shot-7].unregistration(gameSpace);bullet[shot-7].clear();bullet[shot-7].init(bullet[shot-7].kind);}}}/*自己产生子弹*/if (bullet[0].disapper) {if (command == 32) {int shot;bullet[0] = me.make_bullet(gameSpace,0, shot);if (shot >= 1 && shot <= 3) {enemy[shot-1].be_shot(gameSpace);existCount--;}bullet[0].registration(gameSpace);}}/*诞生缺损敌人*/if (leftCount > 0) {for (int i = 0; i != 3; i++) {if (enemy[i].blood == 0) {if (freezeTime[i] == 0) {freezeTime[i] = REBIRTHTIME;reset(enemy[i]);existCount++;leftCount--;}else freezeTime[i]--;}}}}}void TankGame::update_keyBoard_char(char& c){if (_kbhit()) {c = getch();if (c == -32) {c = getch();if (c != UP && c != DOWN && c != LEFT && c != RIGHT)c = -1;else if (c == RIGHT)c = 0;else if (c == UP)c = 1;else if (c == LEFT)c = 2;elsec = 3;}elsec = 32;}}void TankGame::enter_picture(char &command){string captions[6];captions[0] = "◥◣◢◤■■■■■◥◣◢◤";captions[1] = " ◥◣◢◤◢◤◥◣◢◤";captions[2] = " ◥◣◢◤◢◤◥◣◢◤";captions[3] = " ◢◤◢◤◢◤◥◣";captions[4] = " ◢◤◢◤◢◤◥◣";captions[5] = " ◢◤■■■■■◢◤◥◣";string s = " ";color(0x0e);for (int i = 0; i != 6; i++)grid(7, 6 + i, captions[i]);Frame frame(30,15);frame.draw_frame(4,19,0x09);string sentence[3];sentence[0] = "This small game is made by yzx in 2010.";sentence[1] = "Wlecome to play it.";sentence[2] = "All Rights Reserved.";color(0x0e);for (int i = 0; i != 3; i++) {for (int k = 0; k != sentence[i].size(); k++) {grid(14+k,21+2*i,sentence[i][k]);sleep(50);}sleep(1000);}grid(7, 28,"Enter : 开始ESC : 退出");while (true) {if (_kbhit()) {command = getch();if (command == ENTER || command == ESC)break;}}// clear screen picture in wallclear_picture();}void TankGame::turn_to_next_task(char& command){clear_picture();color(0x0e);grid(18, 20, "第");grid(20, 20, no);grid(22, 20, "关");while (true) {if (_kbhit()) {command = getch();if (command == ENTER || command == ESC)break;}}grid(18, 20," ");}void TankGame::success_gameover(){clear_picture();Frame frame(30,15);frame.draw_frame(4,10,0x09);string sentence[3];sentence[0] = "Congratulations for Successfully finishing all tasks";sentence[1] = "Thank you for using it deeply.";sentence[2] = "And welcome to use it next time.";color(0x0e);for (int i = 0; i != 3; i++) {for (int k = 0; k != sentence[i].size(); k++) {grid(12+k,14+2*i,sentence[i][k]);sleep(50);}sleep(1000);}while (true) {if (_kbhit()) {char command = getch();if (command == ENTER || command == ESC)break;}}}void TankGame::game_over(){clear_picture();Frame frame(30,15);frame.draw_frame(4,15,0x09);string sentence[4];sentence[0] = "Game over, but you can try it again.";sentence[1] = "Thank you for using it deeply.";sentence[2] = "And welcome to use it next time.";sentence[3] = "All rights reserved.(Violators will be prosecuted.) .";color(0x0e);for (int i = 0; i != 4; i++) {for (int k = 0; k != sentence[i].size(); k++) {grid(13+k,18+2*i,sentence[i][k]);sleep(50);}sleep(1000);}while (true) {if (_kbhit()) {char command = getch();if (command == ENTER || command == ESC)break;}}}void TankGame::clear_picture(){int cirX = wide / 2;int cirY = high / 2;int depth = cirY > cirX ? cirY + 2 : cirX + 2;int lx, rx, uy, by;int l, r, u, b;for (int i = 0; i != depth; i++) {lx = cirX - i;rx = cirX + i;uy = cirY - i;by = cirY + i;uy <= 0 ? u = 1 : u = uy;by >= high - 1 ? b = high - 2 : b = by;lx <= 0 ? l = 1 : l = lx;rx >= wide -1 ? r = wide - 2 : r = rx;if (rx < wide - 1) {for (int k = u; k <= b; k++)grid(rx, k, " ");}if (lx > 0) {for (int k = u; k <= b; k++)grid(lx, k, " ");}if (by < high - 1) {for (int k = l; k <= r; k++)grid(k, by, " ");}if (uy > 0) {for (int k = l; k <= r; k++)grid(k, uy, " ");}}}void TankGame::test(){for (int y = 0; y != 40; y++) {for (int x = 0; x != 40; x++) {if (gameSpace[y][x].have)// && gameSpace[y][x].kind == 3)grid(x, 42+y, (char)gameSpace[y][x].no);elsegrid(x, 42+y, " ");}}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
private static Random r=new Random();
Wall w1=new Wall(300,100,300,40,this),w2=new Wall(100,150,40,300,this);
tk.getImage(Tank.class.getClassLoader().getResource("images/tankU.gif")),
tk.getImage(Tank.class.getClassLoader().getResource("images/tankRU.gif")),
tk.getImage(Tank.class.getClassLoader().getResource("images/tankR.gif")),
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.*;
public class TankClient extends Frame
{
private static final long serialVersionUID = 1L;
this.h = h;
this.tc = tc;
}
public void draw(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(x, y, w, h);
}
public Rectangle getRect()
{
return new Rectangle(x,y,w,h);
import java.awt.Toolkit;
public class Tank
{
public static final int LARGE_T=40;
public static final int LARGE_M=10;
public int XSPEED=4;
public int YSPEED=4;
{
public void windowClosing(WindowEvent e) {
System.exit(0);//表示正常退出
}
}
);
this.setBackground(Color.GREEN);
this.setResizable(false);//禁止窗口改变大小
this.setVisible(true);
g.drawString("tanks count:" + tanks.size(), 10, 70);
g.drawString("exlpode count:" +explodes.size(), 10, 90);
g.drawString("mytank life:" + myTank.getLife(), 10, 110);
AddBlood Addb=new AddBlood();
List<Explode> explodes = new ArrayList<Explode>();
Image offScreenImage=null;
public void paint(Graphics g)
{
g.drawString("missles count:"+missles.size(), 10,50);
for(int i=0;i<missles.size();i++)
{
Missle m=(Missle) missles.get(i);
if(!m.isMissle_live())
missles.remove(m);
else
m.draw(g);
m.hitTanks(tanks);
m.hitTank(myTank);
private int step=0,rn=0;
TankClient tc;
int life=100;
int dir=3;
public Tank(int x, int y,TankClient tc,boolean good)
{
this.x = x;
this.y = y;
this.oldx=x;
this.oldy=y;
}
this.setLocation(40, 40);
this.setSize(GAME_WIDTH, GAME_HIGH);
this.setTitle("TankWar");
//setBounds(40,40,800,600);
this.addWindowListener(new WindowAdapter()
{
Addb.setLive(true);
}
}
Addb.draw(g);
myTank.eat(Addb);
w1.draw(g);
w2.draw(g);
}
public void update(Graphics g)
{
if(offScreenImage==null)
{
offScreenImage=this.createImage(GAME_WIDTH,GAME_HIGH);
tk.getImage(Tank.class.getClassLoader().getResource("images/tankL.gif")),
tk.getImage(Tank.class.getClassLoader().getResource("images/tankLU.gif"))
};
public void draw(Graphics tank)
{
if(!live)
{
tc.missles.remove(this);
return;
}
//Color c=tank.getColor();
if(good)
{
tank.setColor(Color.RED);
drawBlood(tank);
}
else
tank.setColor(Color.BLUE);
}
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.awt.Image;
t.draw(g);
}
for(int i=0; i<explodes.size(); i++) {
Explode e = explodes.get(i);
e.draw(g);
}
myTank.collidesTanks(tanks);
myTank.collidesWall(w1);
myTank.collidesWall(w2);
tank.drawImage(images[dir], x, y,null);
tank.setColor(Color.BLACK);
if(!good)
{
dir=direction(dir);
if(r.nextInt(fire(dir));
move(dir);
new Thread(new ThreadPaint()).start();
this.addKeyListener(new KeyMonitor());
}
public static void main(String[] args)
{
TankClient tc=new TankClient();
tc.showFrame();
this.tc=tc;
this.good=good;
}
private static Toolkit tk=Toolkit.getDefaultToolkit();
private static Image [] images={
tk.getImage(Tank.class.getClassLoader().getResource("images/tank1U.gif")),
}
else
{
if(direction(dir)==0)
stay();
else dir=direction(dir);
move(dir);
}
}
void move(int dir)
{
oldx=x;
oldy=y;
tk.getImage(Tank.class.getClassLoader().getResource("images/tankRD.gif")),
tk.getImage(Tank.class.getClassLoader().getResource("images/tankD.gif")),
tk.getImage(Tank.class.getClassLoader().getResource("images/tankLD.gif")),
gOffScreen.setColor(c);
paint(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
}