飞机大战model.py

model.py

"""

飞机大战:1.0

"""

import pygame

import random

import time

pygame.init()

# 定义常量

SCREEN_SIZE = (520, 854)

SCREEN_RECT = pygame.Rect(0, 0, *SCREEN_SIZE)

class GameSprite(pygame.sprite.Sprite):

"""存放所有游戏精灵类型"""

    def __init__(self, image_path, speed=1):

super().__init__()

self.image = pygame.image.load(image_path)

self.rect =self.image.get_rect()

self.speed = speed

def update(self):

# 默认运动更新方法

        self.rect.y +=self.speed

class BackgroundSprite(GameSprite):

"""背景"""

    def __init__(self, image_path, next=False):

super().__init__(image_path)

if next:

self.rect.y = -SCREEN_SIZE[1]

def update(self):

# 调用父类的方法,执行运动

        super().update()

# 子类中判断边界

        if self.rect.y > SCREEN_SIZE[1]:

self.rect.y = -SCREEN_SIZE[1]

class HeroSprite(GameSprite):

"""英雄飞机精灵组"""

    def __init__(self, image_path):

super().__init__(image_path)

# 初始化英雄飞机位置

        self.rect.centerx = SCREEN_RECT.centerx

self.rect.centery = SCREEN_RECT.centery +200

        # 子弹精灵组对象

        self.bullets = pygame.sprite.Group()

def update(self):

# 水平边界判断

        if self.rect.x <=0:

self.rect.x =0

        elif self.rect.x >= SCREEN_RECT.width -self.rect.width:

self.rect.x = SCREEN_RECT.width -self.rect.width

# 垂直边界判断

        if self.rect.y <=0:

self.rect.y =0

        elif self.rect.y >= SCREEN_RECT.height -self.rect.height:

self.rect.y = SCREEN_RECT.height -self.rect.height

def fire(self):

# 创建子弹对象进行攻击

        if len(self.bullets) <5:

bullet = BulletSprite(self.rect.centerx-30, self.rect.y)

self.bullets.add(bullet)

class BulletSprite(GameSprite):

"""子弹精灵组"""

    def __init__(self, x, y):

super().__init__("./images/bullet1.png", speed=-8)

self.rect.x = x

self.rect.y = y

def update(self):

# 调用父类的方法进行操作

        super().update()

# 边界判断

        if self.rect.y <= -self.rect.height:

# 子弹从精灵组中删除

            self.kill()

def __del__(self):

print("子弹对象已经销毁")

class EnemySprite(GameSprite):

"""敌方飞机精灵组"""

    def __init__(self):

# 初始化敌方飞机的数据:图片,速度

        super().__init__("./images/enemy1.png", speed=random.randint(3, 5))

self.rect.x = random.randint(0, SCREEN_RECT.width -self.rect.width)

self.rect.y = -self.rect.height

def update(self):

super().update()

# 边界判断

        if self.rect.y > SCREEN_RECT.height:

# 飞机一旦超出屏幕,进行销毁操作

            self.kill()

def __del__(self):

self.destroy()

def destroy(self):

print("销毁敌机")

for img_pathin ["./images/down_1.png", "./images/down_2.png"]:

time.sleep(0.05)

self.image = pygame.image.load(img_path)


#  engine.py 见下一篇

你可能感兴趣的:(飞机大战model.py)