飛機(jī)大戰(zhàn)model.py

model.py

"""

飛機(jī)大戰(zhàn):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):

# 默認(rèn)運(yùn)動(dòng)更新方法

? ? ? ? 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):

# 調(diào)用父類的方法,執(zhí)行運(yùn)動(dòng)

? ? ? ? super().update()

# 子類中判斷邊界

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

self.rect.y = -SCREEN_SIZE[1]

class HeroSprite(GameSprite):

"""英雄飛機(jī)精靈組"""

? ? def __init__(self, image_path):

super().__init__(image_path)

# 初始化英雄飛機(jī)位置

? ? ? ? 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):

# 創(chuàng)建子彈對象進(jìn)行攻擊

? ? ? ? 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):

# 調(diào)用父類的方法進(jìn)行操作

? ? ? ? super().update()

# 邊界判斷

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

# 子彈從精靈組中刪除

? ? ? ? ? ? self.kill()

def __del__(self):

print("子彈對象已經(jīng)銷毀")

class EnemySprite(GameSprite):

"""敵方飛機(jī)精靈組"""

? ? def __init__(self):

# 初始化敵方飛機(jī)的數(shù)據(jù):圖片,速度

? ? ? ? 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:

# 飛機(jī)一旦超出屏幕,進(jìn)行銷毀操作

? ? ? ? ? ? self.kill()

def __del__(self):

self.destroy()

def destroy(self):

print("銷毀敵機(jī)")

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

time.sleep(0.05)

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


# ?engine.py 見下一篇

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容