python+pygame實現坦克大戰
阿新 • • 發佈:2020-01-09
本文例項為大家分享了python+pygame實現坦克大戰的具體程式碼,供大家參考,具體內容如下
一、首先匯入pygame庫
二、原始碼分享
#coding=utf-8 import pygame import time import random from pygame.sprite import Sprite SCREEN_WIDTH=800 SCREEN_HEIGHT=500 BG_COLOR=pygame.Color(0,0) TEXT_COLOR=pygame.Color(255,0) #定義一個基類 class BaseItem(Sprite): def __init__(self,color,width,height): pygame.sprite.Sprite.__init__(self) class MainGame(): window=None my_tank = None #儲存敵方坦克的列表 enemyTankList=[] enemyTankCount=5 # 儲存我方坦克子彈的列表 myBulletList = [] #儲存敵方子彈的列表 enemyBulletList=[] explodeList = [] #建立牆壁列表 wallList = [] def __init__(self): pass def startGame(self): pygame.display.init() #初始化視窗 MainGame.window=pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT]) #初始化我方坦克 self.createMyTank() pygame.display.set_caption('坦克大戰1.03') #初始化敵方坦克 self.createEnemyTank() self.createWall() while True: time.sleep(0.02) #給視窗設定填充色 MainGame.window.fill(BG_COLOR) self.getEvent() #繪製文字 MainGame.window.blit(self.getTextSuface('敵方坦克剩餘數量%d'%len(MainGame.enemyTankList)),(10,10)) #呼叫坦克顯示方法 if MainGame.my_tank and MainGame.my_tank.live: MainGame.my_tank.displayTank() else: del MainGame.my_tank MainGame.my_tank = None #迴圈遍歷列表顯示敵方坦克 self.blitEnemyTank() #迴圈遍歷爆炸列表 self.blitExplode() #迴圈遍歷牆壁 self.blitWall() #迴圈遍歷我方坦克的子彈 self.blitMyBullet() #迴圈遍歷子彈列表,展示敵方子彈 self.blitEnemyBullet() if MainGame.my_tank and MainGame.my_tank.live: if not MainGame.my_tank.stop: MainGame.my_tank.move() #檢測我方坦克是否與牆壁發生碰撞 MainGame.my_tank.hitWall() MainGame.my_tank.myTank_hit_enemyTank() pygame.display.update() def blitWall(self): for wall in MainGame.wallList: if wall.live: wall.displayWall() else: MainGame.wallList.remove(wall) def createWall(self): #初始化牆壁 for i in range(6): wall = Wall(i*130,220) MainGame.wallList.append(wall) def createMyTank(self): MainGame.my_tank = MyTank(350,300) #建立music物件 music = Music('img/start.wav') music.play() def createEnemyTank(self): top=100 for i in range(MainGame.enemyTankCount): left = random.randint(0,600) speed = random.randint(1,4) enemy=EnemyTank(left,top,speed) MainGame.enemyTankList.append(enemy) def blitExplode(self): for explode in MainGame.explodeList: if explode.live: explode.displayExplode() else: MainGame.explodeList.remove(explode) def blitEnemyTank(self): for enemyTank in MainGame.enemyTankList: if enemyTank.live: EnemyTank.displayTank(enemyTank) enemyTank.randMove() enemyTank.hitWall() if MainGame.my_tank and MainGame.my_tank.live: enemyTank.enemyTank_hit_myTank() #發射子彈 enemyBullet=enemyTank.shot() if enemyBullet: MainGame.enemyBulletList.append(enemyBullet) else:#不活著 刪除 MainGame.enemyTankList.remove(enemyTank) music = Music('img/fire.wav') music.play() def blitMyBullet(self): for myBullet in MainGame.myBulletList: if myBullet.live: myBullet.displayBullet() myBullet.move() #呼叫檢測我方子彈是否與敵方坦克碰撞 myBullet.myBullet_hit_enemyTank() myBullet.hitWall() else: MainGame.myBulletList.remove(myBullet) def blitEnemyBullet(self): for enemyBullet in MainGame.enemyBulletList: if enemyBullet.live: enemyBullet.displayBullet() enemyBullet.move() #呼叫敵方子彈與我方坦克的碰撞方法 enemyBullet.enemyBullet_hit_myTank() enemyBullet.hitWall() else: MainGame.enemyBulletList.remove(enemyBullet) def endGame(self): print('謝謝使用,歡迎再次使用') exit() def getTextSuface(self,text): #初始化字型模組 pygame.font.init() font=pygame.font.SysFont('kaiti',18) textSurface=font.render(text,True,TEXT_COLOR) return textSurface #獲取事件 def getEvent(self): eventList=pygame.event.get() for event in eventList: if event.type == pygame.QUIT: self.endGame() if event.type == pygame.KEYDOWN:#如果按下下鍵 if not MainGame.my_tank: if event.key== pygame.K_ESCAPE: self.createMyTank() if MainGame.my_tank and MainGame.my_tank.live: #判斷上下左右 if event.key == pygame.K_LEFT: MainGame.my_tank.direction='L' #修改坦克開關狀態 MainGame.my_tank.stop=False #MainGame.my_tank.move() print('按下左鍵,坦克向左移動') elif event.key == pygame.K_RIGHT: MainGame.my_tank.direction='R' MainGame.my_tank.stop = False #MainGame.my_tank.move() print('按下右鍵,坦克向右移動') elif event.key == pygame.K_UP: MainGame.my_tank.direction='U' MainGame.my_tank.stop = False # MainGame.my_tank.move() print('按下上鍵,坦克向上移動') elif event.key == pygame.K_DOWN: MainGame.my_tank.direction='D' MainGame.my_tank.stop = False #MainGame.my_tank.move() print('按下下鍵,坦克向下移動') elif event.key == pygame.K_SPACE: print('傳送子彈') if len(MainGame.myBulletList)<3:#最多發射3個子彈 myBullet=Bullet(MainGame.my_tank) MainGame.myBulletList.append(myBullet) music = Music('img/hit.wav') music.play() if event.type == pygame.KEYUP: if MainGame.my_tank and MainGame.my_tank.live: #判斷釋放鍵是上下左右才停止 if event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: MainGame.my_tank.stop = True 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='L' self.image = self.images[self.direction] #根據圖片獲取區域 self.rect = self.image.get_rect() #設定區域的left和TOP self.rect.left=left self.rect.top=top self.speed = 5 #坦克移動的開關 self.stop=True #是否活著 self.live=True #距離原來座標 self.oldLeft = self.rect.left self.oldTop = self.rect.top #tank move def move(self): self.oldLeft = self.rect.left self.oldTop = self.rect.top #判斷坦克方向 if self.direction == 'L': if self.rect.left>0: self.rect.left -=self.speed elif self.direction == 'U': if self.rect.top>0: self.rect.top -=self.speed elif self.direction == 'D': if self.rect.top+self.rect.height<SCREEN_HEIGHT: self.rect.top +=self.speed elif self.direction == 'R': if self.rect.left+self.rect.height<SCREEN_WIDTH: self.rect.left += self.speed #tank shottint def shot(self): return Bullet(self) def stay(self): self.rect.left = self.oldLeft self.rect.top = self.oldTop #檢測坦克是否與牆壁發生碰撞 def hitWall(self): for wall in MainGame.wallList: if pygame.sprite.collide_rect(self,wall): self.stay() def displayTank(self): #獲取展示的物件 #呼叫blit方法展示 self.image = self.images[self.direction] MainGame.window.blit(self.image,self.rect) class MyTank(Tank): def __init__(self,top): super(MyTank,self).__init__(left,top) #檢查我方坦克與敵方坦克發生碰撞 def myTank_hit_enemyTank(self): for enemyTank in MainGame.enemyTankList: if pygame.sprite.collide_rect(self,enemyTank): self.stay() class EnemyTank(Tank): def __init__(self,speed): #呼叫父類的舒適化方法 super(EnemyTank,top) #圖片 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() #根據方向獲取image self.image = self.images[self.direction] self.rect = self.image.get_rect() self.rect.left=left self.rect.top=top self.speed=speed self.flag=True self.step=60 def enemyTank_hit_myTank(self): if pygame.sprite.collide_rect(self,MainGame.my_tank): self.stay() def 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: self.step=60 self.direction = self.randDirection() else: self.move() self.step-=1 def shot(self): #隨機生成100以內的數 num = random.randint(1,100) if num<10: return Bullet(self) class Bullet(BaseItem): def __init__(self,tank): self.image = pygame.image.load('img/enemymissile.gif') #坦克的方向決定子彈的方向 self.direction = tank.direction #獲取區域 self.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.height elif 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.height elif 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.width / 2 - self.rect.width / 2 elif self.direction == 'R': self.rect.left = tank.rect.left + tank.rect.width self.rect.top = tank.rect.top + tank.rect.width / 2 - self.rect.width / 2 #子彈的速度 self.speed=6 #子彈的姿態,是否碰到牆壁,如果是牆壁,修改此狀態 self.live=True #move def move(self): if self.direction == 'U': if self.rect.top>0: self.rect.top-=self.speed else: #修改子彈的狀態 self.live=False elif self.direction == 'R': if self.rect.left+self.rect.width<SCREEN_WIDTH: self.rect.left+=self.speed else: self.live=False elif self.direction == 'D': if self.rect.top+self.rect.height<SCREEN_HEIGHT: self.rect.top+=self.speed else: self.live=False elif self.direction == 'L': if self.rect.left>0: self.rect.left-=self.speed else: self.live=False #我方坦克和敵方子彈的碰撞 def myBullet_hit_enemyTank(self): #迴圈遍歷敵方坦克列表,判斷是否發生碰撞 for enemyTank in MainGame.enemyTankList: if pygame.sprite.collide_rect(enemyTank,self): #修改敵方坦克和我方子彈的狀態 enemyTank.live = False self.live = False #建立爆炸物件 explode = Explode(enemyTank) MainGame.explodeList.append(explode) #子彈是否碰撞牆壁 def hitWall(self): for wall in MainGame.wallList: if pygame.sprite.collide_rect(self,wall): self.live=False wall.hp-=1 if wall.hp<=0: wall.live=False #show def displayBullet(self): MainGame.window.blit(self.image,self.rect) def enemyBullet_hit_myTank(self): if MainGame.my_tank and MainGame.my_tank.live: if pygame.sprite.collide_rect(MainGame.my_tank,self): explode = Explode(MainGame.my_tank) MainGame.explodeList.append(explode) self.live=False MainGame.my_tank.live=False class Wall(): def __init__(self,top): self.image = pygame.image.load('img/steels.gif') self.rect = self.image.get_rect() self.rect.left = left self.rect.top = top self.live = True #設定牆壁生命值 self.hp = 3 def displayWall(self): MainGame.window.blit(self.image,self.rect) class Explode(): def __init__(self,tank): #爆炸的位置有當前子彈打中的位置確定 self.rect=tank.rect self.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'),] self.step=0 self.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+=1 MainGame.window.blit(self.image,self.rect) else: self.live=False self.step=0 class Music(): def __init__(self,fileName): self.fileName = fileName #play music pygame.mixer.init() pygame.mixer.music.load(self.fileName) def play(self): pygame.mixer.music.play() if __name__ == '__main__': MainGame().startGame() #MainGame().getTextSuface()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。