这篇文章将为大家详细讲解有关用Python制作坦克大战游戏,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

小时候玩的“坦克大战”,你还记得吗?

环境依赖

python3.7

pygame1.9.6

urllib

内置库,如random、sys、time、os等

pygame介绍

Pygame被设计用来写游戏的python模块集合,基于SDL库开发。使用python可以导入pygame来开发具有全部特性的游戏和多媒体软件,Pygame是极度轻便的并且可以运行在几乎所有的平台和操作系统上。

1. 导入依赖 & 通用配置

importrandomimportsysimporttimefromurllib.requestimporturlretrieveimportosimportpygameSCREEN_WIDTH,SCREEN_HEIGHT=1200,700#画面大小MY_BIRTH_LEFT,MY_BIRTH_TOP=SCREEN_WIDTH/2,SCREEN_HEIGHT-60DIRECTION=[U,D,L,R]=[U,D,L,R]#控制键Tank_IMAGE_POSITION=rD:/tank_imgURL=https://gitee.com/tyoui/logo/raw/master/img/

2. 通用加载函数

#加载图片defload_img(name_img):save=Tank_IMAGE_POSITION+os.sep+name_img+.gififnotos.path.exists(save):urlretrieve(URL+name_img+.gif,save)returnpygame.image.load(save)#加载背景音乐defload_music(name_music):save=Tank_IMAGE_POSITION+os.sep+name_music+.wavifnotos.path.exists(save):urlretrieve(URL+name_music+.wav,save)pygame.mixer.music.load(save)pygame.mixer.music.play()

3. 通用基础类

*pygame.sprite模块,官方文档上说这个模块是轻量级的,在游戏开发中也未必要使用。*sprite翻译为精灵,在游戏动画一般是指一个独立运动的画面元素,在pygame中,就可以是一个带有图像(Surface)和大小位置(Rect)的对象。*pygame.sprite.Sprite是pygame精灵的基类,一般来说,需要写一个自己的精灵类继承一下它然后加入自己的代码。classBaseItem(pygame.sprite.Sprite):def__init__(self):super().__init__()

4. 定义bullet类

classBullet(BaseItem):#参数初始化def__init__(self,tank,window):super().__init__()self.direction=tank.directionself.speed=tank.speed*3self.img=load_img(bullet)self.rect=self.img.get_rect()self.window=windowself.live=Trueifself.direction==U:self.rect.left=tank.rect.left+tank.rect.width/2-self.rect.width/2self.rect.top=tank.rect.top-self.rect.heightelifself.direction==D:self.rect.left=tank.rect.left+tank.rect.width/2-self.rect.width/2self.rect.top=tank.rect.top+tank.rect.heightelifself.direction==L:self.rect.left=tank.rect.left-self.rect.width/2-self.rect.width/2self.rect.top=tank.rect.top+tank.rect.height/2-self.rect.height/2else:self.rect.left=tank.rect.left+tank.rect.widthself.rect.top=tank.rect.top+tank.rect.height/2-self.rect.height/2#子弹显示defdisplay_bullet(self):self.window.blit(self.img,self.rect)#通过按键控制子弹移动defbullet_move(self):ifself.direction==U:ifself.rect.top>0:self.rect.top-=self.speedreturnelifself.direction==D:ifself.rect.top<SCREEN_HEIGHT:self.rect.top+=self.speedreturnelifself.direction==L:ifself.rect.left>0:self.rect.left-=self.speedreturnelse:ifself.rect.left<SCREEN_WIDTH:self.rect.left+=self.speedreturnself.live=False#我方坦克子弹击中对方坦克defhit_enemy_tank(self):forenemyinTankGame.enemy_tank_list:hit=pygame.sprite.collide_rect(self,enemy)ifhit:self.live=Falseifenemy.click_count==1:enemy.live=FalsereturnNoneenemy.click_count-=1ifenemy.click_count==2:enemy.load_image=enemy.img32ifenemy.click_count==1:enemy.load_image=enemy.img31load_music(hit)#对方坦克子弹击中我方坦克defhit_my_tank(self,tank):hit=pygame.sprite.collide_rect(self,tank)ifhit:self.live=Falsetank.live=False#子弹击中围墙defbullet_collide_wall(self):forwallinTankGame.wall_list:result=pygame.sprite.collide_rect(self,wall)ifresult:self.live=Falseifwall.count==1:wall.live=Falseelse:load_music(hit)#子弹击中子弹defbullet_collide_bullet(self):forbulletinTankGame.enemy_bullet_list:ifpygame.sprite.collide_rect(bullet,self):bullet.live=Falseself.live=False

5. 定义tank类

classTank(BaseItem):#参数初始化def__init__(self,left,top,window,image,direction,speed):super().__init__()self.window=windowself.load_image=imageself.direction=directionself.img=self.load_image[self.direction]self.rect=self.img.get_rect()self.rect.left=leftself.rect.top=topself.speed=speedself.tank_width=self.rect.widthself.tank_height=self.rect.heightself.wall_switch=Falseself.move_stop=Trueself.live=Trueself.old_left=0self.old_top=0#开火deffire(self):returnBullet(self,self.window)#显示defdisplay(self):self.img=self.load_image[self.direction]self.window.blit(self.img,self.rect)defwall_not(self,direction):ifdirection==U:returnself.rect.top>0elifdirection==D:returnself.rect.top<=SCREEN_HEIGHT-self.tank_heightelifdirection==L:returnself.rect.left>0else:returnself.rect.left<=SCREEN_WIDTH-self.tank_widthdefwall_yes(self,direction):ifdirection==U:ifself.rect.top<0:self.rect.top=SCREEN_HEIGHTelifdirection==D:self.rect.top%=SCREEN_HEIGHTelifdirection==L:ifself.rect.left<0:self.rect.left=SCREEN_WIDTHelse:self.rect.left%=SCREEN_WIDTHdefmove(self,direction):self.old_left=self.rect.leftself.old_top=self.rect.topifself.wall_switch:self.wall_yes(direction)elifnotself.wall_not(direction):returnNoneifdirection==U:self.rect.top-=self.speedelifdirection==D:self.rect.top+=self.speedelifdirection==L:self.rect.left-=self.speedelse:self.rect.left+=self.speeddefstay(self):self.rect.left=self.old_leftself.rect.top=self.old_topdeftank_collide_wall(self):forwallinTankGame.wall_list:ifpygame.sprite.collide_rect(self,wall):self.stay()deftank_collide_tank(self):fortankinTankGame.enemy_tank_list:ifpygame.sprite.collide_rect(self,tank):self.stay()

6. 定义我方 & 对方tank类

classMyTank(Tank):def__init__(self,left,top,window):self.img=dict(U=load_img(p2tankU),D=load_img(p2tankD),L=load_img(p2tankL),R=load_img(p2tankR))self.my_tank_speed=4super().__init__(left,top,window,self.img,U,self.my_tank_speed)classEnemyTank(Tank):def__init__(self,left,top,window):self.img1=dict(U=load_img(enemy1U),D=load_img(enemy1D),L=load_img(enemy1L),R=load_img(enemy1R))self.img2=dict(U=load_img(enemy2U),D=load_img(enemy2D),L=load_img(enemy2L),R=load_img(enemy2R))self.img3=dict(U=load_img(enemy3U),D=load_img(enemy3D),L=load_img(enemy3L),R=load_img(enemy3R))self.img31=dict(U=load_img(enemy3U_1),D=load_img(enemy3D_1),L=load_img(enemy3L_1),R=load_img(enemy3R_1))self.img32=dict(U=load_img(enemy3U_2),D=load_img(enemy3D_2),L=load_img(enemy3L_2),R=load_img(enemy3R_2))#不同的坦克击中的次数不一样image,self.click_count,speed=random.choice([(self.img1,1,4),(self.img3,3,3),(self.img2,1,5)])super().__init__(left,top,window,image,self.random_direction(),speed)self.step=100@staticmethoddefrandom_direction():n=random.randint(0,3)returnDIRECTION[n]defrandom_move(self):ifself.step==0:self.direction=self.random_direction()self.step=random.randint(10,100)else:self.move(self.direction)self.step-=1defrandom_fire(self):ifrandom.randint(0,50)==1andlen(TankGame.enemy_bullet_list)<30:enemy_bullet=self.fire()TankGame.enemy_bullet_list.append(enemy_bullet)

7. 爆炸动作类

classExplode(BaseItem):def__init__(self,tank,window):super().__init__()self.img=[load_img(blast0),load_img(blast1),load_img(blast2),load_img(blast3),load_img(blast4),load_img(blast5),load_img(blast6)]self.rect=tank.rectself.stop=0self.window=windowself.rect.left=tank.rect.left-tank.rect.width/2defdisplay_explode(self):load_music(blast)whileself.stop<len(self.img):self.window.blit(self.img[self.stop],self.rect)self.stop+=1

8. 定义wall类

classWall(BaseItem):def__init__(self,left,top,window):super().__init__()self.count=random.randint(0,1)self.img=[load_img(steels),load_img(walls)][self.count]self.rect=self.img.get_rect()self.rect.left=leftself.rect.top=topself.window=windowself.live=Truedefdisplay_wall(self):self.window.blit(self.img,self.rect)

9. 定义坦克大战类

classTankGame:my_bullet_list=list()enemy_bullet_list=list()enemy_tank_list=list()wall_list=list()def__init__(self):ifnotos.path.exists(Tank_IMAGE_POSITION):os.makedirs(Tank_IMAGE_POSITION)pygame.init()pygame.font.init()self.display=pygame.displayself.window=self.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT],pygame.RESIZABLE,32)self.display.set_caption(坦克世界)self.my_tank=MyTank(MY_BIRTH_LEFT,MY_BIRTH_TOP,self.window)self.creat_enemy_number=10self.my_tank_lift=3self.creat_enemy(self.creat_enemy_number)self.creat_walls()self.font=pygame.font.SysFont(kai_ti,18)self.number=1defcreat_enemy(self,number):for_inrange(number):left=random.randint(0,SCREEN_WIDTH-self.my_tank.tank_width)enemy_tank=EnemyTank(left,20,self.window)TankGame.enemy_tank_list.append(enemy_tank)defcreat_walls(self):foriinrange(SCREEN_WIDTH//60+1):wall_h=random.randint(100,500)w=Wall(60*i,wall_h,self.window)TankGame.wall_list.append(w)@staticmethoddefshow_walls():forwinTankGame.wall_list:ifw.live:w.display_wall()else:TankGame.wall_list.remove(w)defstart_game(self):load_music(start)whileTrue:self.window.fill([0,0,0])self.get_event()len_enemy=len(TankGame.enemy_tank_list)self.window.blit(self.draw_text(敌方坦克*{0},我方生命值*{1},当前{2}关.format(len_enemy,self.my_tank_lift,self.number)),(10,10))iflen_enemy==0:self.creat_enemy_number+=10self.number+=1self.my_tank_lift+=1self.creat_enemy(self.creat_enemy_number)self.wall_list.clear()self.creat_walls()self.show_my_tank()self.show_enemy_tank()self.show_bullet(TankGame.enemy_bullet_list)self.show_bullet(TankGame.my_bullet_list)self.show_walls()self.display.update()time.sleep(0.02)defshow_my_tank(self):ifself.my_tank.live:self.my_tank.display()self.my_tank.tank_collide_tank()self.my_tank.tank_collide_wall()else:Explode(self.my_tank,self.window).display_explode()delself.my_tankifself.my_tank_lift==0:self.end_game()self.my_tank_lift-=1load_music(add)self.my_tank=MyTank(MY_BIRTH_LEFT,MY_BIRTH_TOP,self.window)ifnotself.my_tank.move_stop:self.my_tank.move(self.my_tank.direction)defshow_enemy_tank(self):foreinTankGame.enemy_tank_list:e.random_move()e.tank_collide_wall()ife.live:e.display()else:TankGame.enemy_tank_list.remove(e)Explode(e,self.window).display_explode()e.random_fire()defshow_bullet(self,ls):forbinls:b.bullet_move()b.bullet_collide_wall()iflsisTankGame.my_bullet_list:b.hit_enemy_tank()b.bullet_collide_bullet()else:b.hit_my_tank(self.my_tank)ifb.live:b.display_bullet()else:ls.remove(b)defget_event(self):globalSCREEN_WIDTH,SCREEN_HEIGHTevent_list=pygame.event.get()foreventinevent_list:ifevent.type==pygame.VIDEORESIZE:SCREEN_WIDTH,SCREEN_HEIGHT=event.sizeself.window=self.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT],pygame.RESIZABLE,32)ifevent.type==pygame.QUIT:self.end_game()ifevent.type==pygame.KEYDOWN:ifevent.key==pygame.K_w:self.my_tank.direction=Uelifevent.key==pygame.K_s:self.my_tank.direction=Delifevent.key==pygame.K_a:self.my_tank.direction=Lelifevent.key==pygame.K_d:self.my_tank.direction=Relse:returnNoneself.my_tank.move_stop=Falseelifevent.type==pygame.MOUSEBUTTONDOWN:iflen(TankGame.my_bullet_list)<3:bullet=self.my_tank.fire()load_music(fire)TankGame.my_bullet_list.append(bullet)elifevent.type==pygame.KEYUP:self.my_tank.move_stop=Truedefend_game(self):self.display.quit()sys.exit()defdraw_text(self,content):text_sf=self.font.render(content,True,[255,0,0])returntext_sf

10. 入口

if__name__==__main__:g=TankGame()g.start_game()

执行界面

关于用Python制作坦克大战游戏就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。