当前位置 主页 > 网站技术 > 代码类 >

    python pygame实现滚动横版射击游戏城市之战

    栏目:代码类 时间:2019-11-25 21:09

    pygame城市之战横版射击游戏,按上下左右方向箭头操作飞机。这是一个横板射击小游戏,在黑夜的城市上空,你将要操作一架飞机去射击敌机,爆炸效果还不错。

    在游戏中定义了滚动的背景类,定义了飞机类Plane,定义了子弹类,敌机类,爆炸类等,是学习Pygame和面向对象编程的好例子。

    代码:

    import math
    import time
    import pygame
    from pygame.locals import *
    from random import choice,randint
     
    class ScrolledBackground(pygame.sprite.Sprite):
     def __init__(self,image,screen):
      pygame.sprite.Sprite.__init__(self)
      self.screen = screen
      self.width = screen.get_width()
      self.height = screen.get_height()
      self.image0 = pygame.image.load(image).convert_alpha()
      self.image1 = pygame.image.load(image).convert_alpha()
     
      self.rect0 = self.image0.get_rect()  
      self.rect1 = self.image1.get_rect()
      self.rect1.left = self.rect0.right
      self.dx = -10
      self.dy = 0
      
     def update(self):
      pass
     
     def draw(self):
      pass
     
     
    class Plane(pygame.sprite.Sprite):
     def __init__(self,image,keys,screen):
      pygame.sprite.Sprite.__init__(self)
      self.keys = keys     # 上下左右按键
      self.image = pygame.image.load(image).convert_alpha()
      self.screen = screen
      self.rect = self.image.get_rect()
      self.rect.centery = self.screen.get_height()//2
      self.xspeed = 0
      self.yspeed = 0
      self.dead = False     # 新增加的属性
      
     def keys_check(self,all_keys): 
      pass
     
     def update(self):
      self.rect.move_ip(self.xspeed,self.yspeed)
      
     def draw(self):
      self.screen.blit(self.image,self.rect)
      
    class Bullet(pygame.sprite.Sprite):
     def __init__(self,image,plane,group,screen):
      pygame.sprite.Sprite.__init__(self)
      self.plane = plane
      self.image = pygame.image.load(image).convert_alpha()
      self.rect = self.image.get_rect()
      self.rect.center = plane.rect.center
      self.group = group
      self.group.add(self)
      self.screen = screen
      self.screen_width = screen.get_width()
      self.screen_height = screen.get_height()  
      
     def update(self):
      self.rect.move_ip(10,0)
      if self.rect.left > self.screen_width :
       self.group.remove(self)
       
    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
     
     pass   
       
    class Explosion(pygame.sprite.Sprite):
     """爆炸效果类,显示一系列帧图"""
     def __init__(self,surimages,position,group):
      pygame.sprite.Sprite.__init__(self)
      self.surimages = surimages      # 爆炸效果用到的surface列表
      self.index = 0
      self.amounts = len(surimages)
      self.image = self.surimages[self.index]   # 初始造型
      self.rect = self.image.get_rect()    # 矩形对象
      self.rect.center = position      # 爆炸位置
      self.group = group
      self.group.add(self)
      self.interval_time = 0.01      # 造型切换时间
      self.begin_time = time.time()     # 爆炸起始时间
      
     def update(self):         # 换造型
      
      if time.time() - self.begin_time >= self.interval_time: # 超时,则换造型
       if self.index < self.amounts:
        self.image = self.surimages[self.index]
        self.index = self.index + 1
        self.begin_time = time.time()
       else:
        self.group.remove(self)     # 造型切换完了则从组中移除自己
        
    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,屏幕对象
      """ 
      pass
      
     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): 
      pass
     
    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()