python学习

PYTHON实现坦克大战游戏

2019-09-27  本文已影响0人  9ba4bd5525b9
python开发的坦克大战游戏 
import pygame
from pygame.sprite import Sprite
import sys
import time
import random
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
SCREEN_WIDTH = 780
SCREEN_HEIGHT = 500
BG_COLOR = pygame.Color(0,0,0)
TEXT_COLOR = pygame.Color(255,0,0)
#复活次数

#定义一个精灵类
class BaseItem(Sprite):
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
       pygame.sprite.Sprite.__init__(self)

class MainGame ():

    window = None
    my_tank = None
    REC_TIME=0
    #敌方坦克初始化
    EnemyTankList = []
    EnemyTankCount = 5
    #存储我方子弹列表
    myBulleList = []
    #存储敌方子弹
    EnemyBulletList = []
    #创建爆炸对象列表
    explodeList = []

    #创建墙壁列表
    wallList =[]
    def __init__(self):
        pass

    def starGame(self):
        #初始化,设置标题,屏幕大小
        pygame.display.init()
        MainGame.window =pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
        pygame.display.set_caption("坦克大战1.03")
        #初始化我方坦克
        self.creatMyTank()
        # 初始化敌方坦克
        self.creatEnemyTank()
        #初始化墙壁
        self.creatWall()
        while True:
            #填充颜色
            MainGame.window.fill(BG_COLOR)
            #获取事件
            self.getEvent()
            #绘制文字
            MainGame.window.blit(self.getTextSuface("敌方坦克剩余数量%d"%MainGame.EnemyTankCount),(SCREEN_HEIGHT/2,20))
            #调用我方坦克进行显示
            if MainGame.my_tank and MainGame.my_tank.live:
                MainGame.my_tank.displayTank()
            else:
                del MainGame.my_tank
                MainGame.my_tank =None
            #显示我方子弹
            self.blitMyBullet()
            #敌方坦克进行显示
            self.blitEnenyTank()
            #显示墙壁
            self.blitWall()
            #显示敌方子弹
            self.blitEnenyBullet()
            #显示爆炸效果
            self.blitExplode()
            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()
            if MainGame.EnemyTankCount == 0:
                MainGame.window.blit(self.getTextSuface('恭喜你,顺利通过'), (SCREEN_HEIGHT/2, SCREEN_WIDTH/2))
                time.sleep(2)
                self.endGame()
            pygame.display.update()
            time.sleep(0.02)


    def creatWall(self):
        for i in range(0,SCREEN_WIDTH,SCREEN_WIDTH//6):
            top = SCREEN_HEIGHT//3
            left = i
            wall = Wall(left,top)
            MainGame.wallList.append(wall)

    def creatMyTank(self):
        MainGame.my_tank = MyTank(SCREEN_WIDTH/2,SCREEN_HEIGHT/3*2)
        music = Music("img/start.wav")
        music.play()

    def creatEnemyTank(self):
        top = 100
        for i in range(MainGame.EnemyTankCount):
            left = random.randint(0,600)
            speed = random.randint(1,4)
            enmy =EnemyTank(left,top,speed)
            MainGame.EnemyTankList.append(enmy)

    def blitWall(self):
        for wall in MainGame.wallList:
            if wall.live:
                wall.displayWall()
            else:
                MainGame.wallList.remove(wall)

    def blitEnenyTank(self):
        "循环遍历敌方坦克,展示敌方坦克"
        for enmeyTank in MainGame.EnemyTankList:
            if enmeyTank.live:
                enmeyTank.displayTank()
                enmeyTank.randomMove()
                EnemyBullet = enmeyTank.shot()
                enmeyTank.hitWall()
                enmeyTank.enemyTank_hit_MyTank()
                #存储敌方子弹
                if EnemyBullet:
                     MainGame.EnemyBulletList.append(EnemyBullet)
            else:
                MainGame.EnemyTankList.remove(enmeyTank)
                MainGame.EnemyTankCount -=1
    def blitMyBullet(self):
        for bullet in MainGame.myBulleList:
            if bullet.live:
                bullet.displayBullet()
                bullet.move()
                bullet.myBullet_hit_enemyTank()
                bullet.wall_bullet()
            else:
                MainGame.myBulleList.remove(bullet)

    def blitEnenyBullet(self):
         for bullet in MainGame.EnemyBulletList:
             if bullet.live:  #随机会产生None
                 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 endGame(self):
        print("欢迎下次游戏")
        sys.exit()
    def getTextSuface(self,text):
        pygame.font.init()
       # print(pygame.font.get_fonts())
        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:
                        if MainGame.REC_TIME < 3:
                             self.creatMyTank()
                             MainGame.REC_TIME +=1
                if MainGame.my_tank and MainGame.my_tank.live:
                    if event.key ==pygame.K_DOWN:
                        MainGame.my_tank.direction ='D'
                        #MainGame.my_tank.move()
                        MainGame.my_tank.stop =False
                        print("按下向下的键,向下移动",)
                    elif event.key == pygame.K_UP:
                        MainGame.my_tank.direction = 'U'
                        #MainGame.my_tank.move()
                        MainGame.my_tank.stop = False
                        print("按下向上的键,向上移动")
                    elif event.key == pygame.K_LEFT:
                        MainGame.my_tank.direction = 'L'
                        #MainGame.my_tank.move()
                        MainGame.my_tank.stop = False
                        print("按下向左的键,向左移动", MainGame.my_tank.direction)
                    elif event.key == pygame.K_RIGHT:
                        MainGame.my_tank.direction = 'R'
                        #MainGame.my_tank.move()
                        MainGame.my_tank.stop = False
                        print("按下向右的键,向右移动", MainGame.my_tank.direction)

                    elif event.key == pygame.K_SPACE:
                        print("发射子弹")
                        #创建我方子弹
                        if len(MainGame.myBulleList) < 3:
                            myBullet =  Bullet(MainGame.my_tank)
                            MainGame.myBulleList.append(myBullet)

                            # 发射子弹音效
                            ShotMusic = Music('img/hit.wav')
                            ShotMusic.play()

            elif event.type == pygame.KEYUP:
                if event.key ==pygame.K_UP or event.key == pygame.K_DOWN or event.key ==pygame.K_LEFT or event.key ==pygame.K_RIGHT:
                   if MainGame.my_tank and MainGame.my_tank.live:
                        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 ='U'
        self.image = self.images[self.direction]
        self.rect = self.image.get_rect()
        #设置放置的位置
        self.rect.left=left
        self.rect.top = top
        self.speed = 4
        #控制坦克开关
        self.stop = True
        self.live = True

        #保持原来的位置
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top

    def hitWall(self):
        for wall in MainGame.wallList:
            if pygame.sprite.collide_rect(wall, self):
                self.stay()

    def stay(self):
        self.rect.left = self.oldLeft
        self.rect.top = self.oldTop

    def shot(self):
        return Bullet(self)
    def move(self):
        #保持原来的状态
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top
        #判断坦克的方向进行移动
        if self.direction =='U':
            if self.rect.top>0:
               self.rect.top -= self.speed
        elif self.direction =='L':
            if self.rect.left>0:
             self.rect.left -=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

    def displayTank(self):
        self.image = self.images[self.direction]
        MainGame.window.blit(self.image,self.rect)

class MyTank(Tank):
    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()

class EnemyTank(Tank):


    def __init__(self,left,top,speed):

        super(EnemyTank,self).__init__(left,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.RandomDirction()

        self.image = self.images[self.direction]
        self.rect =self.image.get_rect()
        self.rect.left = left
        self.rect.top = top
        self.speed =speed
        self.EnemyFlag = False

        self.step = 60

    def RandomDirction(self):
        num = random.randint(1,4)
        if num ==1:
            return "U"
        elif num == 2:
            return "L"
        elif num == 3:
            return "D"
        elif num == 4:
            return "R"
    def randomMove(self):
        if self.step < 0:
            self.direction = self.RandomDirction()
            self.step = 60
        else:
            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('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.height/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.height/2 -self.rect.width/2
        #子弹的速度
        self.speed =6
        #子弹状态
        self.live = True

    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 displayBullet(self):
        MainGame.window.blit(self.image,self.rect)

    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 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 = False
                self.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 -=1
                    self.live =False
                    if wall.hg<=0:
                        wall.live = False


class Wall():
    def __init__(self,left,top):
        self.image = pygame.image.load('img/steels.gif')
        self.rect = self.image.get_rect()
        self.rect.top = top
        self.rect.left =left
        self.live =True
        self.hg = 8

    def displayWall(self):
        if self.live ==True:
            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')]
        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
        #初始化音乐混合器
        pygame.mixer.init()
        pygame.mixer.music.load(filename)
    def play(self):
        pygame.mixer.music.play()


if __name__ == '__main__':
    c = MainGame()
    c.starGame()
上一篇 下一篇

猜你喜欢

热点阅读