python pygame实现飞机大战

#--coding:utf-8--

'''My Function'''

from mydata import *
from myclass import *

def hiteffect(ImagePath, x, y, w, h, Window):
    image = pygame.image.load(ImagePath).convert_alpha()
    screen = pygame.Rect(x, y, w, h)
    Window.blit(image, screen)


def bulletFly(BulletList):
    # 子弹飞行函数
    for bullet in BulletList:
        if bullet.bulletFly('up') >= bullet.height:
            pass
        else:
            BulletList.remove(bullet)


def gun(Parameter_Class, PlaneObject, Bg_Object, Window):
    # 机枪函数
    PlaneObject.fire()
    if Parameter_Class.GunTimeStep <= Parameter_Class.GunSpeed:
        bulletFly(Parameter_Class.BulletList)
        Parameter_Class.GunTimeStep += 1
    else:
        bullet = BulletObject(PlaneObject.screen.x + 39, PlaneObject.screen.y,
                              22, 22, Parameter_Class.BulletPath, Window, Parameter_Class.BulletSpeed, Bg_Object)
        Parameter_Class.BulletList.append(bullet)
        bulletFly(Parameter_Class.BulletList)
        Parameter_Class.GunTimeStep = 0


def enemyattack(EnemyList, Bg_Object):
    # 敌人移动
    for enemy in EnemyList:
        if enemy.EnemyFly() <= (Bg_Object.height - enemy.height):
            pass
        else:
            EnemyList.remove(enemy)


def enemyaction(Parameter_Class, Bg_Object, Window):
    # 所有敌人行为
    if Parameter_Class.EnemyTimeStep <= Parameter_Class.EnemyShowSpeed:
        enemyattack(Parameter_Class.EnemyList, Bg_Object)
        Parameter_Class.EnemyTimeStep += 1
    else:
        x = random.randint(40, 400)
        enemy = EnemyObject(x, 0,
                            57, 43, Parameter_Class.EnemyPath, Window, Parameter_Class.EnemySpeed, Bg_Object)
        Parameter_Class.EnemyList.append(enemy)
        enemyattack(Parameter_Class.EnemyList, Bg_Object)
        Parameter_Class.EnemyTimeStep = 0


def hit(Parameter_Class, PlaneObject, Window):
    # 对象间接触处理函数
    PlaneWRange = (PlaneObject.screen.x + PlaneObject.width * 0.8)
    PlaneWHead = (PlaneObject.screen.x + PlaneObject.width * 0.2)
    PlaneHRange = (PlaneObject.screen.y + PlaneObject.height * 0.9)
    PlaneHHead = (PlaneObject.screen.y + PlaneObject.height * 0.1)
    for bullet in Parameter_Class.BulletList:
        bulletWRange = (bullet.screen.x + bullet.width)
        bulletHRange = (bullet.screen.y + bullet.height)
        for enemy in Parameter_Class.EnemyList:
            enemyWRange = (enemy.screen.x + enemy.width)
            enemyHRange = (enemy.screen.y + enemy.height)
            if bullet.screen.y < enemyHRange and bulletHRange > enemy.screen.y:
                if ((bulletWRange < enemyWRange and bullet.screen.x > enemy.screen.x)
                        or (bulletWRange > enemy.screen.x and bullet.screen.x < enemy.screen.x)
                        or (bulletWRange > enemyWRange and bullet.screen.x < enemyWRange)):
                    for EnemyHitPath in Parameter_Class.EnemyHitPathList:
                        hiteffect(EnemyHitPath, enemy.screen.x,
                                  enemy.screen.y, 57, 51, Window)
                    try:
                        Parameter_Class.EnemyList.remove(enemy)
                        Parameter_Class.BulletList.remove(bullet)
                    except Exception as e:
                        pass
                    finally :
                        Parameter_Class.Point += 1000
                        uplevel(Parameter_Class)
                        print(Parameter_Class.Point)
            if PlaneHHead < enemyHRange and PlaneHRange > enemy.screen.y:
                if ((PlaneWRange > enemyWRange and PlaneWHead < enemy.screen.x)
                        or (PlaneWHead < enemyWRange and PlaneWHead > enemy.screen.x)
                        or (PlaneWRange < enemyWRange and PlaneWRange > enemy.screen.x)):
                    for EnemyHitPath in Parameter_Class.EnemyHitPathList:
                        hiteffect(EnemyHitPath, enemy.screen.x,
                                  enemy.screen.y, 57, 51, Window)
                    for PlaneHitPath in Parameter_Class.PlaneHitPathList:
                        hiteffect(PlaneHitPath, PlaneObject.screen.x,
                                  PlaneObject.screen.y, PlaneObject.width, PlaneObject.height, Window)
                    try:
                        Parameter_Class.EnemyList.remove(enemy)
                    except Exception as e:
                        pass
                    Parameter_Class.Life -= 1
                    upgrade(Parameter_Class)
                    print("受到攻击,减去一条命,剩余%d条命,请注意。" % (Parameter_Class.Life))


def record(Score):
    print("GameOver")
    print("最终得分%d" % (Score))
    # 读取历史最高分
    with open("record.txt", "r") as f:
        record_Score = int(f.read())
    if Score > record_Score:
        with open("record.txt", "w") as f:
            f.write(str(Score))
            print("恭喜你创造了历史最高分!~")
    else:
        print("您没有创造历史最高分,当前历史最高分: %d" % (record_Score))

def uplevel(Parameter_Class):
    # 开局 Level 1 (Min)
    # 提高难度
    # Level 2
    if Parameter_Class.Point > 10000 and Parameter_Class.Level == 1:
        Parameter_Class.EnemyShowSpeed -= 5
        Parameter_Class.EnemySpeed += 3
        Parameter_Class.Level += 1
        print('Level 2')
    # Level 3
    if Parameter_Class.Point > 20000 and Parameter_Class.Level == 2:
        Parameter_Class.EnemyShowSpeed -= 5
        Parameter_Class.EnemySpeed += 5
        Parameter_Class.Level += 1
        print('Level 3')
    # Level 4
    if Parameter_Class.Point > 30000 and Parameter_Class.Level == 3:
        Parameter_Class.EnemyShowSpeed -= 5
        Parameter_Class.EnemySpeed += 5
        Parameter_Class.Level += 1
        print('Level 4')
    # Level 5 (Max)
    if Parameter_Class.Point > 50000 and Parameter_Class.Level == 4:
        Parameter_Class.EnemyShowSpeed -= 5
        Parameter_Class.EnemySpeed += 2
        Parameter_Class.Level += 1
        print('Level 5')


def upgrade(Parameter_Class):
    # 开局 Level 1 (Min)
    # 提高难度
    # Level 2
    if Parameter_Class.Life == 2 and Parameter_Class.Weapon == 1:
        Parameter_Class.GunSpeed -= 5
        Parameter_Class.BulletSpeed += 5
        Parameter_Class.Weapon += 1
        print('Weapon Level 2')
    # Level 3
    if Parameter_Class.Life == 1 and Parameter_Class.Weapon == 2:
        Parameter_Class.GunSpeed -= 10
        Parameter_Class.BulletSpeed += 10
        Parameter_Class.Weapon += 1
        print('Weapon Level 3')


def action(Key, Parameter_Class, Move_Object, Bg_Object, Window):
    key_pressed = Key.get_pressed()
    if key_pressed[K_w] or key_pressed[K_UP]:
        Move_Object.move('up')
    if key_pressed[K_s] or key_pressed[K_DOWN]:
        Move_Object.move('down')
    if key_pressed[K_a] or key_pressed[K_LEFT]:
        Move_Object.move('left')
    if key_pressed[K_d] or key_pressed[K_RIGHT]:
        Move_Object.move('right')
    gun(Parameter_Class, Move_Object, Bg_Object, Window)
    enemyaction(Parameter_Class, Bg_Object, Window)
    hit(Parameter_Class, Move_Object, Window)
    pygame.display.update()


def main():
    # 游戏初始化
    pygame.init()
    window = pygame.display.set_mode((480, 700))
    clock = pygame.time.Clock()

    # 初始化游戏参数
    # parameter: 开火速度, 子弹飞行速度, 敌人出现速度, 敌人飞行速度, 初始生命 , 各种素材路径等
    parameter = ParameterClass(
        20, 15, 30, 2, 3, bulletPath, enemyPath, planeHitPathList, enemyHitPathList)
    background = StaticObject(
        0, 0, 480, 700, backgroundPath, window)
    plane = PlaneObject(
        170, 500, 100, 124, planePath, window, 5, background)

    # 游戏运行内容
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                print("exit")
                # 游戏退出
                pygame.quit()
                sys.exit()
        action(pygame.key, parameter, plane, background, window)
        if parameter.Life == 0:
            record(parameter.Point)
            # 游戏退出
            pygame.quit()
            sys.exit()
        clock.tick(60)
        
#--coding:utf-8--

'''My Data'''

import pygame
import random
import sys
from pygame.locals import *

# 相对路径
planePath = '../images/hero1.png'
backgroundPath = '../images/background.png'
bulletPath = '../images/bullet.png'
enemyPath = '../images/enemy1.png'
enemyHitPathList = ['../images/enemy1_down1.png',
                    '../images/enemy1_down2.png',
                    '../images/enemy1_down3.png',
                    '../images/enemy1_down4.png']
planeHitPathList = ['../images/me_destroy_1.png',
                    '../images/me_destroy_2.png',
                    '../images/me_destroy_3.png',
                    '../images/me_destroy_4.png']

#--coding:utf-8--

'''My Class'''

from mydata import *


class StaticObject(object):
    """静态对象类"""

    origin_x = 0
    origin_y = 0
    width = 0
    height = 0
    imagePath = ''

    def __init__(self, x, y, width, height, imagePath, window):
        self.origin_x = x
        self.origin_y = y
        self.width = width
        self.height = height
        self.image = pygame.image.load(imagePath).convert_alpha()
        self.window = window
        self.screen = pygame.Rect(
            self.origin_x, self.origin_y, self.width, self.height)
        self.window.blit(self.image, self.screen)
        pygame.display.update()

    def bg_draw(self):
        # 静态背景渲染
        self.window.blit(self.image, self.screen)


class MoveObject(StaticObject):
    """动态对象类"""

    speed = 0

    def __init__(self, x, y, width, height, imagePath, window, BackgroundObject, speed):
        StaticObject.__init__(self, x, y, width, height, imagePath, window)
        self.BackgroundObject = BackgroundObject
        self.speed = speed

    def draw(self):
        # 动态对象渲染
        self.screen = pygame.Rect(
            self.screen.x, self.screen.y, self.width, self.height)
        self.window.blit(self.image, self.screen)

    def display(self):
        # 动态对象显示
        self.screen = pygame.Rect(
            self.screen.x, self.screen.y, self.width, self.height)
        self.window.blit(self.image, self.screen)
        pygame.display.update()


class PlaneObject(MoveObject):
    """动态对象类下的飞机类"""

    def __init__(self, x, y, width, height, imagePath, window, speed, BackgroundObject):
        MoveObject.__init__(self, x, y, width, height,
                            imagePath, window, BackgroundObject, speed)

    def move(self, direction):
        # 飞机移动
        if direction == 'up' and self.screen.y > 0:
            self.screen.y -= self.speed
        if direction == 'down' and self.screen.y < (self.BackgroundObject.height - self.height):
            self.screen.y += self.speed
        if direction == 'left' and self.screen.x > 0:
            self.screen.x -= self.speed
        if direction == 'right' and self.screen.x < (self.BackgroundObject.width - self.width):
            self.screen.x += self.speed
        self.BackgroundObject.bg_draw()
        self.draw()

    def fire(self):
        # 飞机开火
        self.BackgroundObject.bg_draw()
        self.draw()


class BulletObject(MoveObject):
    """动态对象类下的子弹类"""

    def __init__(self, x, y, width, height, imagePath, window, speed, BackgroundObject):
        MoveObject.__init__(self, x, y, width, height,
                            imagePath, window, BackgroundObject, speed)

    def bulletFly(self, direction):
        # 让子弹飞
        if direction == 'up' and self.screen.y > 0:
            self.screen.y -= self.speed
        elif direction == 'down' and self.screen.y < (self.BackgroundObject.height - self.height):
            self.screen.y += self.speed
        self.draw()
        return self.screen.y


class EnemyObject(MoveObject):
    """动态对象类下的敌人飞机类"""

    def __init__(self, x, y, width, height, imagePath, window, speed, BackgroundObject):
        MoveObject.__init__(self, x, y, width, height,
                            imagePath, window, BackgroundObject, speed)

    def EnemyFly(self):
        # 让敌人飞
        if self.screen.y < (self.BackgroundObject.height - self.height):
            self.screen.y += self.speed
        self.draw()
        return self.screen.y


class ParameterClass(object):
    """用于初始化游戏参数"""
    GunTimeStep = 0
    EnemyTimeStep = 0
    BulletList = []
    EnemyList = []
    GunSpeed = 10
    BulletSpeed = 10
    EnemyShowSpeed = 30
    EnemySpeed = 2
    Life = 3
    Point = 0
    Level = 1
    Weapon = 1
    BulletList = []
    EnemyList = []
    def __init__(self, gunSpeed, bulletSpeed, enemyShowSpeed,
                 enemySpeed, life, bulletPath, enemyPath, planeHitPathList, enemyHitPathList):
        self.GunSpeed = gunSpeed
        self.BulletSpeed = bulletSpeed
        self.EnemyShowSpeed = enemyShowSpeed
        self.EnemySpeed = enemySpeed
        self.Life = life
        self.BulletPath = bulletPath
        self.EnemyPath = enemyPath
        self.PlaneHitPathList = planeHitPathList
        self.EnemyHitPathList = enemyHitPathList

#--coding:utf-8--

'''Main'''

from myfunction import *

if __name__ == '__main__':
    main()

你可能感兴趣的:(Python,编程,计算机)