pygame城市之战横版射击游戏

"""pygame城市之战横版射击游戏,按上下左右方向箭头操作飞机。这是一个横板射击小游戏,在黑夜的城市上空,你将要操作一架飞机去射击敌机,爆炸效果还不错。
在游戏中定义了滚动的背景类,定义了飞机类Plane,定义了子弹类,敌机类,爆炸类等,是学习Pygame和面向对象编程的好例子。"""

import math
import time
import pygame
from pygame.locals import *
from random import choice,randint
from scrolledbackground import *   # 导入滚动背景类
from plane import *                # 导入Plane类 
from bullet import *               # 导入Bullet类
from explosion import *            # 导入爆炸类 
             
def split_images(image,rows,cols):
    """image是一张图片,把它切分为若干图,返回列表"""
    global explosion_images_list
    image = pygame.image.load(image)
    step_width = image.get_width()//cols
    step_height = image.get_height()//rows
    
    for r in range(rows):
        for c in range(cols):
            x = c * step_width
            y = r * step_height
            rect = pygame.Rect(x,y,step_width,step_height)
            explosion_images_list.append(image.subsurface(rect))            
 
                
class Enemy(pygame.sprite.Sprite):
    def __init__(self,images,group,screen):
        """images是surface列表"""
        pygame.sprite.Sprite.__init__(self)
        self.screen = screen
        self.screen_width = self.screen.get_width()     # 获取屏幕宽度
        self.screen_height = self.screen.get_height()   # 获取屏幕高度
        self.image = choice(images)                     # 随机选择一个surface
        self.rect = self.image.get_rect()
        self.rect.left = self.screen_width + randint(10,self.screen_width)
        self.rect.centery = randint(0,self.screen_height)
        self.group = group
        self.group.add(self)                            # 加入到自己的组
    def update(self):
        self.rect.move_ip(-5,0)
        if self.rect.right <= 0 :
            self.group.remove(self)
        
class Eullet(pygame.sprite.Sprite):
    """敌方子弹类"""
    def __init__(self,image,selfgroup,enemy_group,plane,screen):
        """参数列表:image,已转换成surface的对象
                     selfgroup,所在的组
                     enemy_group,敌人组.
                     plane,我方飞机
                     screen,屏幕对象
        """
        pygame.sprite.Sprite.__init__(self)
        self.group = selfgroup                    # 自己所在的组
        self.group.add(self)
        self.image = image
        e = choice(list(enemy_group))             # 随机选择一架敌机
        self.rect = self.image.get_rect()         # 矩形对象
        self.rect.center = e.rect.center          # 放在这架敌机的坐标
        self.plane = plane                        # 我方飞机对象
        self.screen = screen
        self.screen_width = screen.get_width()
        self.screen_height = screen.get_height()        
        self.dx = self.rect.centerx - self.plane.rect.centerx
        self.dy = self.rect.centery - self.plane.rect.centery
        
    def update(self):
        self.rect.move_ip(-self.dx//30,-self.dy//30)
        if self.beyond_edge() :
            self.group.remove(self)
    def beyond_edge(self):
        b1 = self.rect.left > self.screen_width
        b2 = self.rect.right < 0
        b3 = self.rect.bottom < 0
        b4 = self.rect.top > self.screen_height
        return b1 or b2 or b3 or b4

def collision_check():
    """对游戏中的对象进行碰撞检测,碰撞检测有以下几种:
       1、我方飞机碰到敌方飞机,都爆炸。给我方飞机增加dead属性。
       2、我方飞机碰到敌方子弹,我方飞机爆炸,游戏结束。
       3、敌方飞机碰到我方子弹,敌方飞机爆炸。
       以下引用的是全局变量
    """
    global enemy_counter
    "我方飞机和敌方飞机任何一架的碰撞"
    if not plane1.dead:
        eny = pygame.sprite.spritecollideany(plane1, group_enemy)
        if  eny!=None :                                                         # 碰到了,我方飞机死,游戏结束             
            Explosion(explosion_images_list,eny.rect.center,group_explosion)    # 在敌方飞机处发生爆炸
            Explosion(explosion_images_list,plane1.rect.center,group_explosion) # 在我方飞机处发生爆炸
            plane1.dead = True
            group_enemy.remove(eny)                                             # 从敌方组中移除碰撞的敌机
            
    "我方飞机碰到敌方子弹,我方死,游戏结束。"
    if not plane1.dead:
        b = pygame.sprite.spritecollideany(plane1, group_enemy_bullet)
        if  b!=None :                                                          # 碰到了,我方飞机死,游戏结束             
            Explosion(explosion_images_list,plane1.rect.center,group_explosion) # 在我方飞机处发生爆炸
            plane1.dead = True
            
    "敌方飞机碰到我方子弹,我方子弹爆,敌方爆炸"
    result_dict = pygame.sprite.groupcollide(group_bullet1, group_enemy, True, True)  # 一颗子弹可能打到几架飞机
    if result_dict !={}:
       missle = list(result_dict.keys())[0]                                      # 碰到我方子弹
       enemy_list = result_dict[missle]
       #Explosion(explosion_images_list,missle.rect.center,group_explosion)
       enemy_counter += len(enemy_list)                          # 大于一定的数量,如果我方战机没死,则成功结束
       for e in enemy_list: Explosion(explosion_images_list,e.rect.center,group_explosion)
       
       pygame.display.set_caption("风火轮少儿编程_城市之战射击游戏,当前打爆敌机数:" + str(enemy_counter) + ",请自行编写游戏成功结束的代码!")
        
       
    
if __name__ == "__main__":

    width,height = 480,360
    enemy_bullet = "images/bullet2.png"
    enemy_images = ["images/enemy0.png","images/enemy1.png","images/enemy2.png","images/enemy3.png"]
    explosion_images =  "images/explosion.png"
    image = "images/night city with street.png"
    plane_image1 = "images/plane.png"
    bullet_image1 = "images/bullet.png"

    pygame.init()
    screen = pygame.display.set_mode((width,height))
    pygame.display.set_caption("城市之战_作者:李兴球,按上下左右操作飞机。风火轮少儿编程_www.scratch8.net")

    enemy_bullet = pygame.image.load(enemy_bullet)
    enemy_images = [pygame.image.load(img) for img in enemy_images]   # 形成敌机的surface列表
    explosion_images_list = []                              # 爆炸效果surface列表
    explosion_images = split_images(explosion_images,2,13)  # 按2行13列切分图形,返回surface列表
 
    
    keys1 = [K_UP,K_DOWN,K_LEFT,K_RIGHT]
    plane1 = Plane(plane_image1,keys1,screen)
    bg = ScrolledBackground(image,screen)
    running = True
    clock = pygame.time.Clock()

    bullet1_shoot_EVENT = USEREVENT + 1
    pygame.time.set_timer(bullet1_shoot_EVENT,500)

    "敌机定时生成事件"
    enemy_EVENT = USEREVENT + 2
    pygame.time.set_timer(enemy_EVENT,1000)
    
    "敌机定时发射子弹事件"
    enemy_shoot_EVENT = USEREVENT + 3
    pygame.time.set_timer(enemy_shoot_EVENT,50)
    
    group_explosion  = pygame.sprite.Group()
    group_bullet1 = pygame.sprite.Group()
    group_enemy = pygame.sprite.Group()
    group_enemy_bullet = pygame.sprite.Group()
    enemy_amounts = 100                         # 大于这个数量则游戏成功结束
    enemy_counter = 0
    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
                break
            if event.type == bullet1_shoot_EVENT: # 我方子弹1发射事件
                if not plane1.dead:
                   Bullet(bullet_image1,plane1,group_bullet1,screen)
            if event.type == enemy_EVENT:         # 定时生成一架敌机
                Enemy(enemy_images,group_enemy,screen)
               
            if event.type == enemy_EVENT:         # 定时生成一枚敌机子弹
                Eullet(enemy_bullet,group_enemy_bullet,group_enemy,plane1,screen)
                
            
        all_keys = pygame.key.get_pressed()   # 所有按键检测
        plane1.keys_check(all_keys)           # 对plane1进行按键检测
        
        bg.update()                           # 更新背景坐标
        group_bullet1.update()                # 我方子弹更新
        if not plane1.dead :
           plane1.update()                    # 飞机1坐标更新
        group_enemy.update()                  # 敌机坐标
        group_enemy_bullet.update()           # 敌机子弹更新
        group_explosion.update()              # 爆炸效果更新
        
        "坐标都更新完后,应该进行碰撞检测"
        collision_check()
        
        screen.fill((0,0,0))
        bg.draw()
        group_bullet1.draw(screen)
        if not plane1.dead :
           plane1.draw()
        group_enemy.draw(screen)
        group_enemy_bullet.draw(screen)
        group_explosion.draw(screen)
        pygame.display.update()
        clock.tick(30)
    pygame.quit()