Pygame - Python 游戏编程入门 class3-创造出敌人

前言
  在上一节我们完成了对玩家飞机的基本操作,这一节我们就来创造出敌人了(°∀°)ノ~目标有三个,第一个是在屏幕上绘制出敌机,第二个是判断子弹是否击中了敌人,第三个是对被击中的敌人作后续的处理。明白方向后就可以开始了!

正片开始~
  # 1. 绘制敌机

  随机是游戏中一个很重要的元素,不可预测的机制为游戏带44来了更丰富的体验。这次我们要在程序中加入随机数,两行代码:  

# 导入random库中的randint函数
from random import randint
# 返回一个整数N, a<=N<=b
N = randint(a, b)
  这样我们就可以使得敌机每次出现的位置变得不可预测了~(。・ω・。)

  跟之前的风格类似,我们把敌机封装成类,主要是为了能够更方便地使用碰撞检测的功能。
复制代码
 1 # 敌人类
 2 class Enemy(pygame.sprite.Sprite):
 3     def __init__(self, enemy_surface, enemy_init_pos):
 4         pygame.sprite.Sprite.__init__(self)            
 5         self.image = enemy_surface
 6         self.rect = self.image.get_rect()
 7         self.rect.topleft = enemy_init_pos
 8         self.speed = 2
 9 
10     def update(self):
11         self.rect.top += self.speed
12         if self.rect.top > SCREEN_HEIGHT:
13             self.kill()
复制代码

  依然是超出屏幕区域自动销毁对象,最后就是创建敌人对象并在屏幕上绘制出来:

复制代码
 1 ...
 2 # enemy1图片 **********************************************************
 3 enemy1_surface = shoot_img.subsurface(pygame.Rect(534, 612, 57, 43))
 4 # ********************************************************************
 5 ...
 6 
 7 # 事件循环(main loop)
 8 while True:
 9 
10     ...
11 
12     # 产生敌机 *****************************************************
13     if ticks % 30 == 0:
14         enemy = Enemy(enemy1_surface, [randint(0, SCREEN_WIDTH - enemy1_surface.get_width()), -enemy1_surface.get_height()])
15         enemy_group.add(enemy)
16     # 控制敌机
17     enemy_group.update()
18     # 绘制敌机
19     enemy_group.draw(screen)
20     # ************************************************************
21         
22     ...
复制代码

  导入图片资源当然是必不可少的啦;我们使用ticks控制敌人产生的频率,每30ticks产生一架新敌机,然后将敌机对象加入一个group,统一操作,每一tick更新一次全体enemy的位置。现在绘制的任务就完成啦~看一下效果:

  虽然enemy绘制出来了,但是现在出现了两个问题;第一,子弹无法击中敌人;第二,敌人无法击毁玩家飞机。下面我们先来解决第一个问题。

  # 2. 我们的子弹击穿了敌人的铠甲!

  说了那么久,终于说到了“碰撞检测”,游戏中的碰撞检测应用范围很广,不过在pygame中,碰撞检测(collide)的机制其实很简单,就是判断sprite1.rect与sprite2.rect是否重叠。那么在pygame.sprite中,我们可以看到一些函数名中包含collide的函数,这些函数一般是用于检测碰撞的,我们可以大体分为sprite与sprite的碰撞检测,sprite与group的碰撞检测,group与group的碰撞检测。回归问题,子弹是一个group,敌人是一个group,那我们在游戏中检测子弹是否击中了敌人很明显需要用group与group的碰撞检测了~

  pygame.sprite.groupcollide()——检测两个group之间所有sprite的碰撞

  groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict

  group1——精灵组1

  group2——精灵组2

  dokill1——是否杀死发生碰撞时group1中的精灵对象

  dokill2——是否杀死发生碰撞时group2中的精灵对象

  collided——可选参数,可自定义一个回调函数,参数为两个精灵对象,用于自定义两个精灵是否发生碰撞,返回bool值;若忽略此参数,则默认碰撞条件为两个精灵的rect发生重叠

  返回一个包含所有group1中与group2发生碰撞的精灵字典(dict)

  

  现在,我们只需要在程序中加入两行代码:

复制代码

...

# 创建击毁敌人组
enemy1_down_group = pygame.sprite.Group()

# 事件循环(main loop)
while True:

    ...

    # 检测敌机与子弹的碰撞 *******************************************
    enemy1_down_group.add(pygame.sprite.groupcollide(enemy1_group, hero.bullets1, True, True))
      ...
复制代码

  创建一个包含被击毁的敌人的group,然后在每一tick中检测一次是否发生碰撞,再将被击毁的敌人加入这个group,方便后续对坠毁敌机的动画渲染;这样第二部分也完成啦~

  # 3. 华丽的坠毁(`・ω・´)

  现在我们已经实现子弹与敌机的碰撞检测了,但凭空消失是在不咋的,我们来一个华丽一点的爆炸!(°∀°)ノ

  首先导入enemy1爆炸的资源图片

1 enemy1_down_surface = []
2 enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(267, 347, 57, 43)))
3 enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(873, 697, 57, 43)))
4 enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(267, 296, 57, 43)))
5 enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(930, 697, 57, 43)))

  然后就是控制爆炸图片切换的速度了,在主循环中加入:

复制代码
1 for enemy1_down in enemy1_down_group:
2         screen.blit(enemy1_down_surface[enemy1_down.down_index], enemy1_down.rect)
3         if ticks % (ANIMATE_CYCLE//2) == 0:
4             if enemy1_down.down_index < 3:
5                 enemy1_down.down_index += 1
6             else:
7                 enemy1_down_group.remove(enemy1_down)
复制代码

  当index超出图片下标,判断为爆炸效果演示完毕,销毁坠毁的enemy1精灵。

  这样爆炸效果就出来啦~~

  这一节任务完成!~附上完整代码:


# -*- coding = utf-8 -*-
"""
@author: Will Wu
"""
import pygame # 导入pygame库
from pygame.locals import * # 导入pygame库中的一些常量
from sys import exit # 导入sys库中的exit函数
from random import randint
# 定义窗口的分辨率
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 640
# 子弹类
class Bullet(pygame.sprite.Sprite):
def __init__(self, bullet_surface, bullet_init_pos):
 pygame.sprite.Sprite.__init__(self) 
 self.image = bullet_surface
 self.rect = self.image.get_rect()
 self.rect.topleft = bullet_init_pos
 self.speed = 8
# 控制子弹移动
 def update(self):
 self.rect.top -= self.speed
 if self.rect.bottom < 0:
 self.kill()
# 玩家类
class Hero(pygame.sprite.Sprite):

 def __init__(self, hero_surface, hero_init_pos):
 pygame.sprite.Sprite.__init__(self) 
 self.image = hero_surface
 self.rect = self.image.get_rect()
 self.rect.topleft = hero_init_pos
 self.speed = 6
# 子弹1的Group
 self.bullets1 = pygame.sprite.Group()
# 控制射击行为
 def single_shoot(self, bullet1_surface):
 bullet1 = Bullet(bullet1_surface, self.rect.midtop)
 self.bullets1.add(bullet1)
# 控制飞机移动
 def move(self, offset):
 x = self.rect.left + offset[pygame.K_RIGHT] - offset[pygame.K_LEFT]
 y = self.rect.top + offset[pygame.K_DOWN] - offset[pygame.K_UP]
 if x < 0:
 self.rect.left = 0
 elif x > SCREEN_WIDTH - self.rect.width:
 self.rect.left = SCREEN_WIDTH - self.rect.width
 else:
 self.rect.left = x

 if y < 0:
 self.rect.top = 0
 elif y > SCREEN_HEIGHT - self.rect.height:
 self.rect.top = SCREEN_HEIGHT - self.rect.height
 else:
 self.rect.top = y
# 敌人类
class Enemy(pygame.sprite.Sprite):
 def __init__(self, enemy_surface, enemy_init_pos):
 pygame.sprite.Sprite.__init__(self) 
 self.image = enemy_surface
 self.rect = self.image.get_rect()
 self.rect.topleft = enemy_init_pos
 self.speed = 2
# 爆炸动画画面索引
 self.down_index = 0
def update(self):
 self.rect.top += self.speed
 if self.rect.top > SCREEN_HEIGHT:
 self.kill()

###########################################################################
# 定义画面帧率
FRAME_RATE = 60
# 定义动画周期(帧数)
ANIMATE_CYCLE = 30
ticks = 0
clock = pygame.time.Clock()
offset = {pygame.K_LEFT:0, pygame.K_RIGHT:0, pygame.K_UP:0, pygame.K_DOWN:0}
# 初始化游戏
pygame.init() # 初始化pygame
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) # 初始化窗口
pygame.display.set_caption('This is my first pygame-program') # 设置窗口标题
# 载入背景图
background = pygame.image.load('resources/image/background.png')
# 载入资源图片
shoot_img = pygame.image.load('resources/image/shoot.png')
# 用subsurface剪切读入的图片
# Hero图片
hero_surface = []
hero_surface.append(shoot_img.subsurface(pygame.Rect(0, 99, 102, 126)))
hero_surface.append(shoot_img.subsurface(pygame.Rect(165, 360, 102, 126)))
#hero_surface.append(shoot_img.subsurface(pygame.Rect(165, 234, 102, 126))) 
#hero_surface.append(shoot_img.subsurface(pygame.Rect(330, 624, 102, 126)))
#hero_surface.append(shoot_img.subsurface(pygame.Rect(330, 498, 102, 126)))
#hero_surface.append(shoot_img.subsurface(pygame.Rect(432, 624, 102, 126)))
hero_pos = [200, 500]
# bullet1图片
bullet1_surface = shoot_img.subsurface(pygame.Rect(1004, 987, 9, 21))
# enemy1图片 **********************************************************
enemy1_surface = shoot_img.subsurface(pygame.Rect(534, 612, 57, 43))
enemy1_down_surface = []
enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(267, 347, 57, 43)))
enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(873, 697, 57, 43)))
enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(267, 296, 57, 43)))
enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(930, 697, 57, 43)))
# ********************************************************************
# 创建玩家
hero = Hero(hero_surface[0], hero_pos)
# 创建敌人组
enemy1_group = pygame.sprite.Group()
# 创建击毁敌人组
enemy1_down_group = pygame.sprite.Group()
# 事件循环(main loop)
while True:
# 控制游戏最大帧率
 clock.tick(FRAME_RATE)
# 绘制背景
 screen.blit(background, (0, 0))
# 改变飞机图片制造动画
 if ticks >= ANIMATE_CYCLE:
 ticks = 0
 hero.image = hero_surface[ticks//(ANIMATE_CYCLE//2)]
# 射击
 if ticks % 10 == 0:
 hero.single_shoot(bullet1_surface)
 # 控制子弹
 hero.bullets1.update()
 # 绘制子弹
 hero.bullets1.draw(screen)
# 产生敌机 *****************************************************
 if ticks % 30 == 0:
 enemy = Enemy(enemy1_surface, [randint(0, SCREEN_WIDTH - enemy1_surface.get_width()), -enemy1_surface.get_height()])
 enemy1_group.add(enemy)
 # 控制敌机
 enemy1_group.update()
 # 绘制敌机
 enemy1_group.draw(screen)
 # ************************************************************
# 检测敌机与子弹的碰撞 *******************************************
 enemy1_down_group.add(pygame.sprite.groupcollide(enemy1_group, hero.bullets1, True, True))

 for enemy1_down in enemy1_down_group:
 screen.blit(enemy1_down_surface[enemy1_down.down_index], enemy1_down.rect)
 if ticks % (ANIMATE_CYCLE//2) == 0:
 if enemy1_down.down_index < 3:
 enemy1_down.down_index += 1
 else:
 enemy1_down_group.remove(enemy1_down)
 # ************************************************************

 # 绘制飞机
 screen.blit(hero.image, hero.rect)
 ticks += 1 # python已略去自增运算符
# 更新屏幕
 pygame.display.update() 

 # 处理游戏退出
 # 从消息队列中循环取
 for event in pygame.event.get():
 if event.type == pygame.QUIT:
 pygame.quit()
 exit()
# ※ Python中没有switch-case 多用字典类型替代
 # 控制方向 
 if event.type == pygame.KEYDOWN:
 if event.key in offset:
 offset[event.key] = hero.speed
 elif event.type == pygame.KEYUP:
 if event.key in offset:
 offset[event.key] = 0
# 移动飞机
 hero.move(offset)​
本作品采用《CC 协议》,转载必须注明作者和本文链接
嗨,我是波波。曾经创业,有收获也有损失。我积累了丰富教学与编程经验,期待和你互动和进步! 公众号:上海PHP自学中心 付费知识星球:破解面试:程序员的求职导师
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
司机 @ 欣昊玉
文章
273
粉丝
339
喜欢
558
收藏
1106
排名:64
访问:12.2 万
私信
所有博文
社区赞助商