python3坦克大战
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                python3坦克大战
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                
                            
                            
                            # coding = utf-8import pygame, sys, timefrom pygame.locals import *from random import randint'''坦克大戰(zhàn)主窗口'''class TankMain(object):width = 700height = 600wall_list = []my_tank = Nonehome = Nonelives = 3# enemy_list = []     # 敵方坦克列表enemy_list = pygame.sprite.Group()  # 敵方坦克(精靈)族群my_tank_missile = []    # 我方子彈列表enemy_tank_missile = pygame.sprite.Group()  # 敵方子彈(精靈)族群explode_list = []       # 爆炸效果列表# 開(kāi)始游戲def startGame(self):    # 開(kāi)始游戲pygame.init()   # pygame模塊初始化,加載系統(tǒng)資源# 設(shè)置一個(gè)窗口,第一個(gè)參數(shù):(寬,高),第二個(gè)參數(shù):窗口可變{0,RESIZABLE,FULLSCREEM,..},第三個(gè)參數(shù):顏色位數(shù){32,64,..}# screem是一個(gè)Surface表面對(duì)象screem = pygame.display.set_mode((TankMain.width, TankMain.height), 0, 32)# 給窗口設(shè)置標(biāo)題pygame.display.set_caption("坦克大戰(zhàn)")# 生成我方坦克,敵方坦克,障礙物等self.creat(screem)# 循環(huán)顯示屏幕內(nèi)容,形成動(dòng)態(tài)效果while True:screem.fill((0, 0, 0))    # 設(shè)置背景顏色 RGB (255,255,255):白色 (0,0,0):黑色# 顯示self.show(screem)# 事件處理self.get_event(TankMain.my_tank, screem)  # 獲取事件進(jìn)行處理time.sleep(0.05)    # 每次休息0.05秒跳到下一幀pygame.display.update()     # 顯示重置# 在屏幕上顯示文字內(nèi)容def write_text(self):font = pygame.font.SysFont('simhei', 13)  # 定義一個(gè)字體 參數(shù): 字體 大小 粗細(xì)text_sf0 = font.render("我方坦克生命:%d"%TankMain.lives, True, (255, 0, 0))  # 根據(jù)字體創(chuàng)建一個(gè)文字的圖像 參數(shù):內(nèi)容 抗鋸齒 顏色 背景text_sf1 = font.render("敵方坦克數(shù)量:%d"%len(TankMain.enemy_list), True, (255, 0, 0))# 根據(jù)字體創(chuàng)建一個(gè)文字的圖像 參數(shù):內(nèi)容 抗鋸齒 顏色 背景text_sf2 = font.render("我方坦克屏幕子彈數(shù)量:%d"%len(TankMain.my_tank_missile), True,(255, 0, 0))  # 根據(jù)字體創(chuàng)建一個(gè)文字的圖像 參數(shù):內(nèi)容 抗鋸齒 顏色 背景return text_sf0, text_sf1, text_sf2# 生產(chǎn),創(chuàng)建我方坦克,敵方坦克def creat(self, screem):# 生產(chǎn)墻列表for i in range(1, 14):if i % 3 == 0:TankMain.wall_list.append(GrassBarrier(screem, i * Barrier.width, TankMain.height - 400))TankMain.wall_list.append(CobWallBarrier(screem, i * Barrier.width, 300))elif i % 4 == 0:passelif i % 5 == 0:TankMain.wall_list.append(GrassBarrier(screem, i * Barrier.width, TankMain.height-400))TankMain.wall_list.append(IronWallBarrier(screem, i * Barrier.width, 300))elif i % 7 == 0:TankMain.wall_list.append(CobWallBarrier(screem, i * Barrier.width, 300))else:TankMain.wall_list.append(IronWallBarrier(screem, i * Barrier.width, 300))TankMain.wall_list.append(WaterBarrier(screem, i * Barrier.width, TankMain.height - 400))TankMain.wall_list.append(GrassBarrier(screem, i * Barrier.width, i*Barrier.height))TankMain.wall_list.append(WaterBarrier(screem, TankMain.width-i * Barrier.width, i * Barrier.height))# 生成我方坦克的家for i in range(0, 3):if i == 1:TankMain.home = HomeBarrier(screem, TankMain.width/2-HomeBarrier.width/2,TankMain.height-HomeBarrier.width)TankMain.wall_list.append(CobWallBarrier(screem, (TankMain.width+(2*i-3)*HomeBarrier.width)/2,TankMain.height-HomeBarrier.width*2))else:TankMain.wall_list.append(CobWallBarrier(screem, (TankMain.width+(2*i-3)*HomeBarrier.width)/2,TankMain.height-HomeBarrier.width))TankMain.wall_list.append(CobWallBarrier(screem, (TankMain.width+(2*i-3)*HomeBarrier.width)/2,TankMain.height-HomeBarrier.width*2))# 生產(chǎn)我方坦克TankMain.my_tank = MyTank(screem)# 生產(chǎn)敵方坦克for i in range(1, 6):if i % 3 == 0:TankMain.enemy_list.add(EnemyTankQ(screem))  # 在族群中添加3個(gè)普通坦克,就會(huì)有一個(gè)強(qiáng)坦克TankMain.enemy_list.add(EnemyTank(screem))  # 在族群中添加一個(gè)精靈sprite(坦克)# 在屏幕上顯示(矩形rect, sprite, image,等)def show(self, screem):# 顯示文字for i, text in enumerate(self.write_text(), 0):screem.blit(text, (0, 5 + (13 * i)))  # 在左上角顯示文字 參數(shù):源 位置(x,y)# 顯示我方坦克的家if TankMain.home and TankMain.home.live:TankMain.home.display()TankMain.home.hit_other()else:TankMain.home = NoneTankMain.lives = 0TankMain.my_tank = None# 顯示敵方坦克for enemy_tank in TankMain.enemy_list:if enemy_tank.live:enemy_tank.display()# enemy_tank.hit_ourself()enemy_tank.random_move()enemy_tank.random_fire()else:TankMain.enemy_list.remove(enemy_tank)# 顯示我方坦克if TankMain.my_tank and TankMain.my_tank.live:TankMain.my_tank.enemy_hit_mytank()TankMain.my_tank.display()TankMain.my_tank.move()elif TankMain.lives:TankMain.my_tank = MyTank(screem)TankMain.my_tank.live = TrueTankMain.lives -= 1else:TankMain.my_tank = Nonepass# 顯示我方炮彈for mm in TankMain.my_tank_missile:if mm.live:mm.display()mm.hit_tank()  # 檢測(cè)是否命中敵方坦克mm.move()else:TankMain.my_tank_missile.remove(mm)# 顯示敵方炮彈for em in TankMain.enemy_tank_missile:if em.live:em.display()em.move()else:TankMain.enemy_tank_missile.remove(em)# 顯示墻for wall in TankMain.wall_list:if wall.live:wall.display()wall.hit_other()else:TankMain.wall_list.remove(wall)# 顯示爆炸效果for explode in TankMain.explode_list:if explode.live:explode.display()else:TankMain.explode_list.remove(explode)# 顯示勝利if not TankMain.enemy_list:finall_text = pygame.font.SysFont('simhei', 50).render("YOU WIN", True, (255, 0, 0), (0, 255, 0))screem.blit(finall_text, (TankMain.width / 2 - 70, TankMain.height / 2 - 25))# 顯示失敗if (TankMain.lives == 0 and not TankMain.my_tank) or not TankMain.home :finall_text = pygame.font.SysFont('simhei', 50).render("YOU LOSE", True, (127, 127, 127), (255, 0, 0))screem.blit(finall_text, (TankMain.width / 2 - 80, TankMain.height / 2 - 25))# 獲取所有事件(敲擊鍵盤(pán),點(diǎn)擊鼠標(biāo)等)def get_event(self, my_tank, screem):for event in pygame.event.get():if event.type == QUIT:  # 退出事件self.stopGame()     # 退出# if event.type == KEYDOWN and not my_tank and TankMain.lives and event.key == K_RETURN:#     TankMain.lives -= 1#     TankMain.my_tank = MyTank(screem)if event.type == KEYDOWN and my_tank:       # 敲擊鍵盤(pán)事件if event.key == K_ESCAPE:   # 敲擊鍵盤(pán)ESCself.stopGame()     # 退出if event.key == K_LEFT or event.key == K_a:     # 敲擊鍵盤(pán)方向鍵向左my_tank.direction = 'L'my_tank.stop = Falseif event.key == K_RIGHT or event.key == K_d:    # 敲擊鍵盤(pán)方向鍵向右my_tank.direction = 'R'my_tank.stop = Falseif event.key == K_UP or event.key == K_w:       # 敲擊鍵盤(pán)方向鍵向上my_tank.direction = 'U'my_tank.stop = Falseif event.key == K_DOWN or event.key == K_s:     # 敲擊鍵盤(pán)方向鍵向下my_tank.direction = 'D'my_tank.stop = Falseif  event.key == K_SPACE:mm = my_tank.fire()TankMain.my_tank_missile.append(mm)if event.type == KEYUP and my_tank:if event.key == K_LEFT or event.key == K_RIGHT or event.key == K_UP or event.key == K_DOWN \or event.key == K_a or event.key == K_d or event.key == K_w or event.key == K_s:my_tank.stop = Trueif TankMain.my_tank and event.type == MOUSEBUTTONDOWN:  # 鼠標(biāo)事件mm = my_tank.fire()TankMain.my_tank_missile.append(mm)# 關(guān)閉游戲def stopGame(self):  # 停止游戲sys.exit()# 坦克大戰(zhàn)游戲中的基礎(chǔ)父類class BaseIetm(pygame.sprite.Sprite):def __init__(self, screem):pygame.sprite.Sprite.__init__(self)self.screem = screem  # 坦克,炮彈,墻移動(dòng)顯示要用到的屏幕窗口# 把坦克顯示在游戲窗口上def display(self):if self.live:self.image = self.images[self.direction]self.screem.blit(self.image, self.rect)# 坦克父類class Tank(BaseIetm):# 定義屬性,所有坦克的寬高都是一樣的width = 47height = 47def __init__(self, screem, left, top):super().__init__(screem)self.direction = 'D'    # 表示坦克方向,默認(rèn)向下(U,D,L,R)self.speed = 5          # 坦克默認(rèn)速度self.stop = Falseself.images = {}        # 表示坦克圖片字典,key:方向,value:圖片(surface)self.images['L'] = pygame.image.load("image/T_L.png")   # 我方坦克self.images['R'] = pygame.image.load("image/T_R.png")self.images['U'] = pygame.image.load("image/T_U.png")self.images['D'] = pygame.image.load("image/T_D.png")self.image = self.images[self.direction]    # 坦克的圖片由坦克的方向決定self.rect = self.image.get_rect()   # 獲得圖片的邊界self.rect.left = left       # 設(shè)置圖片位置xself.rect.top = top         # 設(shè)置圖片位置yself.live = True    # 決定坦克生死self.oldtop = self.rect.topself.oldleft = self.rect.left# 坦克碰到障礙物,停止前進(jìn)def stay(self):self.rect.top = self.oldtopself.rect.left = self.oldleft# 坦克的移動(dòng)def move(self):if not self.stop:self.oldtop = self.rect.topself.oldleft = self.rect.leftif self.direction == 'L':if self.rect.left > 0:self.rect.left -= self.speedelse:self.rect.left = 0elif self.direction == 'R':if self.rect.right < TankMain.width:self.rect.right += self.speedelse:self.rect.right = TankMain.widthelif self.direction == 'U':if self.rect.top > 0:self.rect.top -= self.speedelse:self.rect.top = 0elif self.direction == 'D':if self.rect.bottom < TankMain.height:self.rect.bottom += self.speedelse:self.rect.bottom = TankMain.height# 坦克開(kāi)火,發(fā)射炮彈def fire(self):pass# 我方坦克class MyTank(Tank):def __init__(self, screem):super().__init__(screem, TankMain.width/2-MyTank.width/2, TankMain.height-150)  # 我方坦克初始化位置self.direction = 'U'        # 我方坦克默認(rèn)朝上self.stop = Truedef enemy_hit_mytank(self):if TankMain.enemy_tank_missile:em_list = pygame.sprite.spritecollide(self, TankMain.enemy_tank_missile, False)for em in em_list:em.live = Falseself.live = Falseexplode = Explode(self.screem, self.rect)TankMain.explode_list.append(explode)# if TankMain.enemy_list:#     tank_list = pygame.sprite.spritecollide(self, TankMain.enemy_list, False)#     for tank in tank_list:#         tank.stop = True#         tank.stay()# 坦克開(kāi)火,發(fā)射炮彈def fire(self):mm = MyMissile(self.screem, self)return mm# 敵方坦克class EnemyTank(Tank):def __init__(self, screem):super().__init__(screem, randint(0, TankMain.width), randint(0, TankMain.height-350))self.images['L'] = pygame.image.load("image/tan_l.png")     # 敵方坦克self.images['R'] = pygame.image.load("image/tan_r.png")self.images['U'] = pygame.image.load("image/tan_u.png")self.images['D'] = pygame.image.load("image/tan_d.png")self.speed = 4   # 敵方坦克速度self.step = 8    # 敵方坦克按照一個(gè)方向移動(dòng)6步self.get_random_direction()# 獲得一個(gè)隨機(jī)方向def get_random_direction(self):r = randint(0, 4)if r == 0:self.stop = Trueelif r == 1:self.direction = 'L'self.stop = Falseelif r == 2:self.direction = 'R'self.stop = Falseelif r == 3:self.direction = 'U'self.stop = Falseelif r == 4:self.direction = 'D'self.stop = False# 敵方坦克確定一個(gè)隨機(jī)方向移動(dòng)8步,然后再次改變方向移動(dòng)def random_move(self):if self.live:if self.step == 0:  # 如果已經(jīng)移動(dòng)了8步,則又隨機(jī)獲得一個(gè)方向self.get_random_direction()self.step = 8else:self.move()self.step -= 1# 坦克開(kāi)火,發(fā)射炮彈def random_fire(self):if randint(1, 100) > 95:em = EnemyMissile(self.screem, self)TankMain.enemy_tank_missile.add(em)else:return# 敵方坦克class EnemyTankQ(EnemyTank):def __init__(self, screem):super().__init__(screem)self.images['L'] = pygame.image.load("image/tank_l.png")     # 敵方坦克self.images['R'] = pygame.image.load("image/tank_r.png")self.images['U'] = pygame.image.load("image/tank_u.png")self.images['D'] = pygame.image.load("image/tank_d.png")# 炮彈父類class Missile(BaseIetm):width = 12height = 12def __init__(self, screem, tank):super().__init__(screem)self.tank = tankself.direction = tank.direction  # 表示炮彈方向,由坦克方向決定self.speed = 12  # 炮彈默認(rèn)速度self.images = {}    # 表示炮彈圖片字典,key:方向,value:圖片(surface)self.images['L'] = pygame.image.load("image/pao2.png")  # 我方炮彈self.images['R'] = pygame.image.load("image/pao2.png")self.images['U'] = pygame.image.load("image/pao2.png")self.images['D'] = pygame.image.load("image/pao2.png")self.image = self.images[self.direction]  # 炮彈的圖片由炮彈的方向決定self.rect = self.image.get_rect()  # 獲得炮彈的邊界self.rect.left = tank.rect.left + (tank.width - self.width)/2  # 設(shè)置炮彈位置xself.rect.top = tank.rect.top + (tank.height - self.height)/2   # 設(shè)置炮彈位置yself.live = True  # 決定炮彈生死# 炮彈移動(dòng)def move(self):if self.live:if self.direction == 'L':if self.rect.left > 0:self.rect.left -= self.speedelse:self.live = Falseelif self.direction == 'R':if self.rect.right < TankMain.width:self.rect.right += self.speedelse:self.live = Falseelif self.direction == 'U':if self.rect.top > 0:self.rect.top -= self.speedelse:self.live = Falseelif self.direction == 'D':if self.rect.bottom < TankMain.height:self.rect.bottom += self.speedelse:self.live = False# 炮彈擊中坦克,第一種:我方炮彈擊中敵方坦克,需要我方炮彈的邊界和所有敵方坦克邊界比對(duì),看是否重疊,返回重疊位置# 第二種:敵方炮彈擊中我方坦克,需要敵方炮彈和我方坦克位置比對(duì),若重疊,返回位置def hit_tank(self):if TankMain.enemy_list:   # 我方炮彈擊中敵方坦克#  在與另一個(gè)精靈相交的組中查找精靈,檢測(cè)是否碰撞 參數(shù):本精靈 目標(biāo)精靈組 是否刪除組中所有碰撞的(Sprite)精靈em_list = pygame.sprite.spritecollide(self, TankMain.enemy_list, False)for em in em_list:self.live = Falseem.live = Falseexplode = Explode(self.screem, em.rect)  # 產(chǎn)生一個(gè)爆炸對(duì)象TankMain.explode_list.append(explode)# 我方炮彈class MyMissile(Missile):def __init__(self, screem, tank):super().__init__(screem, tank)# 敵方炮彈class EnemyMissile(Missile):def __init__(self, screem, tank):super().__init__(screem, tank)self.images['L'] = pygame.image.load("image/pao3.png")  # 我方炮彈self.images['R'] = pygame.image.load("image/pao3.png")self.images['U'] = pygame.image.load("image/pao3.png")self.images['D'] = pygame.image.load("image/pao3.png")# 爆炸類class Explode(BaseIetm):def __init__(self, screem, rect):super().__init__(screem)self.live = Trueself.images = [pygame.image.load("image/bao1.png"),pygame.image.load("image/bao2.png"),pygame.image.load("image/bao3.png"),pygame.image.load("image/bao4.png"),pygame.image.load("image/bao5.png"),pygame.image.load("image/bao6.png")]self.step = 0self.image = self.images[self.step]     # 初始化第一張爆炸效果圖self.rect = rectdef display(self):if self.live:if self.step == len(self.images) :  # 顯示最后一張self.live = Falseelse:self.image = self.images[self.step]self.screem.blit(self.image, self.rect)     # 爆炸位置由坦克的rect位置決定self.step += 1else:pass    # 刪除該爆炸效果對(duì)象# 游戲中的靜態(tài)障礙物(建筑,草,水等)class Barrier(BaseIetm):width = 47height = 47def __init__(self, screem, left, top):super().__init__(screem)# self.rect = Rect(left, top, width, height)  # 構(gòu)建一個(gè)rect(一個(gè)物體在屏幕的位置及大小 )self.image = pygame.transform.scale(pygame.Surface((40, 40)), (40, 40))self.rect = self.image.get_rect()self.rect.left = leftself.rect.top = topself.live = Truedef display(self):if self.live:self.screem.blit(self.image, self.rect)# 碰撞檢測(cè)def hit_other(self):pass# 障礙物--鐵墻class IronWallBarrier(Barrier):def __init__(self, screem, left, top):super().__init__(screem, left, top)self.image = pygame.transform.scale(pygame.image.load("image/zhuan.gif"),(Barrier.width, Barrier.height))# 鐵墻碰撞檢測(cè)def hit_other(self):if TankMain.my_tank:if pygame.sprite.collide_rect(self, TankMain.my_tank):TankMain.my_tank.stop = TrueTankMain.my_tank.stay()if TankMain.enemy_list:et_list = pygame.sprite.spritecollide(self, TankMain.enemy_list, False)for et in et_list:et.stop = Trueet.stay()if TankMain.my_tank_missile:mm_list = pygame.sprite.spritecollide(self, TankMain.my_tank_missile, False)for mm in mm_list:mm.live = Falseif TankMain.enemy_tank_missile:em_list = pygame.sprite.spritecollide(self, TankMain.enemy_tank_missile, False)for em in em_list:em.live = False# 障礙物--土墻class CobWallBarrier(Barrier):def __init__(self, screem, left, top):super().__init__(screem, left, top)self.image = pygame.transform.scale(pygame.image.load("image/tu.gif"),(Barrier.width, Barrier.height))# 土墻碰撞檢測(cè)def hit_other(self):if TankMain.my_tank:if pygame.sprite.collide_rect(self, TankMain.my_tank):TankMain.my_tank.stop = TrueTankMain.my_tank.stay()if TankMain.enemy_list:et_list = pygame.sprite.spritecollide(self, TankMain.enemy_list, False)for et in et_list:et.stop = Trueet.stay()if TankMain.my_tank_missile:mm_list = pygame.sprite.spritecollide(self, TankMain.my_tank_missile, False)for mm in mm_list:mm.live = Falseself.live = Falseexplode = Explode(self.screem, self.rect)TankMain.explode_list.append(explode)if TankMain.enemy_tank_missile:em_list = pygame.sprite.spritecollide(self, TankMain.enemy_tank_missile, False)for em in em_list:em.live = Falseself.live = Falseexplode = Explode(self.screem, self.rect)TankMain.explode_list.append(explode)# 障礙物--草class GrassBarrier(Barrier):def __init__(self, screem, left, top):super().__init__(screem, left, top)self.image = pygame.transform.scale(pygame.image.load("image/cao.gif"),(Barrier.width, Barrier.height))# 草碰撞檢測(cè)def hit_other(self):pass# 障礙物--水class WaterBarrier(Barrier):def __init__(self, screem, left, top):super().__init__(screem, left, top)self.image = pygame.transform.scale(pygame.image.load("image/shui.gif"),(Barrier.width, Barrier.height))# 水碰撞檢測(cè)def hit_other(self):pass# 我方坦克的家class HomeBarrier(Barrier):def __init__(self, screem, left, top):super().__init__(screem, left, top)self.image = pygame.transform.scale(pygame.image.load("image/home.gif"),(Barrier.width, Barrier.height))# 家碰撞檢測(cè)def hit_other(self):if TankMain.my_tank:if pygame.sprite.collide_rect(self, TankMain.my_tank):TankMain.my_tank.stop = TrueTankMain.my_tank.stay()if TankMain.enemy_list:et_list = pygame.sprite.spritecollide(self, TankMain.enemy_list, False)for et in et_list:et.stop = Trueet.stay()if TankMain.my_tank_missile:mm_list = pygame.sprite.spritecollide(self, TankMain.my_tank_missile, False)for mm in mm_list:mm.live = Falseself.live = Falseexplode = Explode(self.screem, self.rect)TankMain.explode_list.append(explode)if TankMain.enemy_tank_missile:em_list = pygame.sprite.spritecollide(self, TankMain.enemy_tank_missile, False)for em in em_list:em.live = Falseself.live = Falseexplode = Explode(self.screem, self.rect)TankMain.explode_list.append(explode)# 測(cè)試運(yùn)行if __name__=='__main__':game = TankMain()game.startGame()
 
                        
                        
                        圖片鏈接:http://www.aigei.com/view/63180.html#items 自己下
 運(yùn)行效果圖:
 
 主要用到pygame模塊
 官方文檔:http://www.pygame.org/docs/
總結(jié)
以上是生活随笔為你收集整理的python3坦克大战的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: PWA桌面应用开发
- 下一篇: css3实现一个闪电效果
