Python 实现飞机大战简单版

这版和网上流传的大部分差不多,没有声音,不能计分。有时间会写个的
首先你得安装了Python3 和pygame ,最好用pycharm编写。

  1. 第一步我们先做一些准备工作:
    测试pygame是否能运行
import pygame

pygame.init()
#创建游戏窗口
screen = pygame.display.set_mode((480,700))
bg = pygame.image.load("./images/background.png")
screen.blit(bg,(0,0))
pygame.display.update()

while True:
    pass
pygame.quit()

上面代码我没写定时关闭,运行时注意

  1. 写英雄图像
import pygame
pygame.init()
#创建游戏窗口
screen = pygame.display.set_mode((480,700))
bg = pygame.image.load("./images/ul0961-7549.jpg")
screen.blit(bg,(0,0))
pygame.display.update()
#英雄图像
hero = pygame.image.load("./images/me1.png")
screen.blit(hero,(200,500))
pygame.display.update()
clock = pygame.time.Clock()
hero_rect = pygame.Rect(200, 500, 102, 126)
while True:
    clock.tick(60)

    for event in  pygame.event.get():

        if event.type == pygame.QUIT:
            print("游戏退出...")
            pygame.quit()
            exit()

    hero_rect.y -= 2
    if hero_rect.y <=0:
        hero_rect.y = 700


    screen.blit(bg,(0,0))
    screen.blit(hero, hero_rect)
    pygame.display.update()


pygame.quit()

“”Python 实现飞机大战简单版_第1张图片

3 写敌机

import pygame
from piane_sprites import*

pygame.init()
#创建游戏窗口
screen = pygame.display.set_mode((480,700))
bg = pygame.image.load("./images/ul0961-7549.jpg")
screen.blit(bg,(0,0))
pygame.display.update()
#英雄图像
hero = pygame.image.load("./images/me1.png")
screen.blit(hero,(200,500))
pygame.display.update()
clock = pygame.time.Clock()
hero_rect = pygame.Rect(200, 500, 102, 126)
enemy = GameSprite("./images/enemy1.png")
enemy1= GameSprite("./images/enemy1.png",2)
enemy_group = pygame.sprite.Group(enemy,enemy1)


while True:
    clock.tick(60)
    for event in  pygame.event.get():

        if event.type == pygame.QUIT:
            print("游戏退出...")
            pygame.quit()
            exit()
    hero_rect.y -= 5
    if hero_rect.y <=0:
        hero_rect.y = 700

    screen.blit(bg,(0,0))
    screen.blit(hero, hero_rect)

    enemy_group.update()
    enemy_group.draw(screen)

    pygame.display.update()
pygame.quit()

接下来就写我们的主程序了
1、主程序:plane_main.py

import pygame
from piane_sprites import*

class PianeGame(object):

    def __init__(self):
        print("游戏初始化")

        #1.创建游戏的窗口
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        #2.创建游戏的时钟
        self.clock = pygame.time.Clock()

        self.__create_sprites()
        pygame.time.set_timer(CREATE_ENEMY_EVENT,1000)
        pygame.time.set_timer(HERO_FIRE_EVENT,500)

    def __create_sprites(self):

        bg1 = Background()
        bg2 = Background(True)
        bg2.rect.y = -bg2.rect.height
        self.back_group = pygame.sprite.Group(bg1,bg2)
        self.enemy_group = pygame.sprite.Group()
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)
    def start_game(self):
        print("游戏开始...")

        while True:
            self.clock.tick(FRAME_SEPER_C)
            self.__event_handler()
            self.__check_collide()
            self.__update_sprites()
            pygame.display.update()

    def __event_handler(self):
        for event in pygame.event.get():
            if event.type ==pygame.QUIT:
                PianeGame.__game_over()
            elif event.type == CREATE_ENEMY_EVENT:
                enemy = Enemy()
                self.enemy_group.add(enemy)
            elif event.type == HERO_FIRE_EVENT:
                self.hero.fire()
            #elif event.type == pygame.KEYDOWN and_event.key == pygme.K_RIG
              #  print("")
                keys_pressed = pygame.key.get_pressed()
                if keys_pressed[pygame.K_RIGHT]:
                    self.hero.speed = 3
                elif keys_pressed[pygame.K_LEFT]:
                    self.hero.speed = -3
                else:
                    self.hero.speed = 0

    def __check_collide(self):
        pygame.sprite.groupcollide(self.hero.bullets,self.enemy_group,True,True)
        enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)
        if len(enemies)>0:
            self.hero.kill()
            self.__game_over()
    def __update_sprites(self):

        self.back_group.update()
        self.back_group.draw(self.screen)

        self.enemy_group.update()
        self.enemy_group.draw(self.screen)

        self.hero_group.update()
        self.hero_group.draw(self.screen)

        self.hero.bullets.update()
        self.hero.bullets.draw(self.screen)
    @staticmethod
    def __game_over(self):
        print("游戏结束")
if __name__ == '__main__':
    game = PianeGame()
    game.start_game()

2.游戏精灵:plane_sprites.py

import pygame
import random

#屏幕大小的常量
SCREEN_RECT = pygame.Rect(0, 0, 480, 700 )
#刷新的帧率
FRAME_SEPER_C = 60
#创建敌机的定时器常量
CREATE_ENEMY_EVENT = pygame.USEREVENT
#英雄发射子弹事件
HERO_FIRE_EVENT = pygame.USEREVENT + 1

class GameSprite(pygame.sprite.Sprite):
    """飞机大战游戏精灵"""
    def __init__(self,image_name, speed=1):
        # 调用父类的初始化方法
        super().__init__()

        # 定义对象的属性
        self.image = pygame.image.load(image_name)
        self.rect  = self.image.get_rect()
        self.speed = speed

    def update(self):
         # 在屏幕的垂直方向上移动
        self.rect.y += self.speed
class Background(GameSprite):
    """游戏背景精灵"""
    def __init__(self,is_alt=False):
        #1.调用父类方法实现精灵的创建
        super().__init__("./images/background.png")

        #2.判断是否交替图像,如果是需要设置初始位置
        if is_alt:
            self.rect.y = -self.rect.height


    def update(self):
         #1.调用父类的方法实现
        super().update()
        #2.判断是否移出屏幕,如果移出屏幕,将设置到屏幕的上方
        if self.rect.y >= SCREEN_RECT.height:
            self.rect.y = -self.rect.height

class Enemy(GameSprite):
    """敌机精灵"""
    def __init__(self):
        super().__init__("./images/enemy1.png")
        self.speed = random.randint(2,4)
        self.rect.bottom = 0
        max_x = SCREEN_RECT.width - self.rect.width
        self.rect.x = random.randint(0, max_x)
    def update(self):
        super().update()
        if self.rect.y >= SCREEN_RECT.height:
            print()
            self.kill()
    def __del__(self):
            print()

class Hero(GameSprite):
    def __init__(self):
        super().__init__("./images/me1.png",0)
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom - 120

        self.bullets = pygame.sprite.Group()
    def update(self):
        self.rect.x += self.speed
        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN_RECT.right:
            self.rect.right = SCREEN_RECT.right
    def fire(self):
        print()
        for i in (0,1,2):

            bullet = Bullet()
            bullet.rect.bottom = self.rect.y - i * 20
            bullet.rect.centerx = self.rect.centerx

            self.bullets.add(bullet)

class Bullet(GameSprite):

    def __init__(self):
        super().__init__("./images/bullet1.png",-2)
    def update(self):
        super().update()
        if self.rect.bottom < 0:
            self.kill()

    def __del__(self):
        pass

你可能感兴趣的:(pygame)