for b in bullets: if b.active: b.move() screen.blit(b.image, b.rect) enemy_hit = pygame.sprite.spritecollide(b, enemies, False, pygame.sprite.collide_mask) if enemy_hit: b.active = False for e in enemy_hit: if e in mid_enemies or e in big_enemies: e.hit = True e.energy -= 1 if e.energy == 0: e.active = False else: e.active = False
时间: 2023-06-17 08:07:01 浏览: 171
这段代码看起来是一个游戏中的子弹和敌人的碰撞检测部分。
首先,遍历所有的子弹列表。如果子弹处于激活状态,就让它移动,并将它的图像绘制在屏幕上。
随后,使用 `pygame.sprite.spritecollide()` 函数检测子弹是否与敌人发生了碰撞。如果发生了碰撞,就将子弹的活动状态设置为不活动,然后遍历所有与子弹发生碰撞的敌人。如果敌人是中等或大型敌人,就将它的 `hit` 标记设置为 `True`,并将它的能量值减 1。如果敌人的能量值降到了 0,就将它的活动状态设置为不活动。如果敌人是小型敌人,就直接将它的活动状态设置为不活动。
相关问题
def __check_cash(self): """碰撞检测""" # 1. 检测子弹与敌机 start_num = len(self.hero.bullets) for enemy in self.enemy_group: if enemy.modnum == 1: if pygame.sprite.spritecollide(enemy, self.hero.bullets, True): self.hero.bullets_num += 2 enemy.modnum = 2 end_num = len(self.hero.bullets) self.scores += start_num - end_num # 2. 检测敌机与英雄 enemies = pygame.sprite.spritecollide(self.hero, self.enemy_group, False) if enemies: for n in (1, 2, 3, 4): time.sleep(0.2) self.screen.blit(pygame.image.load("./images/me_destroy_%d.png" % n), self.hero.rect) self.screen.blit(pygame.image.load("./images/enemy1_down%d.png" % n), enemies[0].rect) pygame.display.update() self.hero.kill() self.__game_over() 解释一下
这段代码是一个游戏中的碰撞检测函数,在游戏中主要负责检测子弹与敌机、敌机与英雄之间的碰撞。函数中包含了两个部分的碰撞检测。
第一部分的碰撞检测是检测子弹与敌机之间的碰撞。首先,我们使用了`len()`函数获取了英雄飞机中当前子弹的数量,然后对于每个敌机,我们使用`pygame.sprite.spritecollide()`方法检测它是否与英雄飞机的子弹相撞。如果发生碰撞,我们会将子弹销毁,并将敌机的modnum属性设为2,以标记该敌机已被击中。同时,我们还会根据销毁的子弹数量计算得分。
第二部分的碰撞检测是检测敌机与英雄飞机之间的碰撞。我们使用了`pygame.sprite.spritecollide()`方法检测是否有敌机与英雄飞机相撞,如果存在碰撞,我们会播放英雄飞机爆炸和敌机爆炸的动画,然后将英雄飞机删除并结束游戏。
值得注意的是,为了在播放爆炸动画时使其更加流畅,我们使用了`time.sleep()`方法来暂停程序的执行,以便让动画能够展现出来。同时,在播放完爆炸动画后,我们会调用`pygame.display.update()`方法来更新屏幕,以让用户能够看到爆炸动画的效果。
总之,这段代码的主要作用是实现游戏中的碰撞检测功能,以便让游戏能够更加流畅地进行。
利用pygame模块实现飞机大战附加功能如下: (1) 实现碰撞检测(可以消灭敌机,也可以被敌机消灭) (2) 随机出现云朵在天空中漂浮 (3) 随机出现甜甜圈进行能量补给(生命力或子弹类型发生变化) (4) 有GAME OVER条件控制
好的,这里给出一份利用pygame模块实现飞机大战并添加上述附加功能的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小和标题
screen_width = 480
screen_height = 800
pygame.display.set_caption("飞机大战")
screen = pygame.display.set_mode((screen_width, screen_height))
# 加载背景音乐
pygame.mixer.music.load("bgm.mp3")
pygame.mixer.music.play(-1) # 播放背景音乐,-1表示循环播放
# 加载游戏音效
bullet_sound = pygame.mixer.Sound("bullet.wav")
enemy_down_sound = pygame.mixer.Sound("enemy_down.wav")
game_over_sound = pygame.mixer.Sound("game_over.wav")
# 加载游戏图片资源
background_img = pygame.image.load("background.png")
player_img = pygame.image.load("player.png")
enemy_img = pygame.image.load("enemy.png")
bullet_img = pygame.image.load("bullet.png")
cloud_img = pygame.image.load("cloud.png")
donut_img = pygame.image.load("donut.png")
# 定义游戏参数
player_speed = 5
player_rect = player_img.get_rect(center=(screen_width // 2, screen_height - 100))
bullet_speed = 8
bullet_interval = 200 # 发射子弹的时间间隔
bullet_timer = 0
enemy_speed = 2
enemy_interval = 2000 # 产生敌机的时间间隔
enemy_timer = 0
cloud_speed = 1
cloud_interval = 5000 # 产生云朵的时间间隔
cloud_timer = 0
donut_speed = 1
donut_interval = 10000 # 产生甜甜圈的时间间隔
donut_timer = 0
player_life = 3
player_bullet_type = 0 # 玩家子弹类型,0表示普通弹,1表示双排弹
score = 0
# 定义游戏状态常量
GAME_STATUS_START = 0
GAME_STATUS_PLAYING = 1
GAME_STATUS_GAME_OVER = 2
game_status = GAME_STATUS_START
# 创建字体对象
font = pygame.font.SysFont("SimHei", 30)
# 定义函数:绘制得分和生命值
def draw_text():
score_text = font.render("得分:" + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
life_text = font.render("生命值:" + str(player_life), True, (255, 255, 255))
screen.blit(life_text, (screen_width - life_text.get_width() - 10, 10))
# 定义函数:绘制玩家飞机
def draw_player():
screen.blit(player_img, player_rect)
# 定义函数:发射子弹
def fire_bullet():
global player_bullet_type
if player_bullet_type == 0:
bullet_rect = bullet_img.get_rect(midbottom=(player_rect.centerx, player_rect.top))
bullets.append(bullet_rect)
else:
bullet_left_rect = bullet_img.get_rect(midbottom=(player_rect.centerx - 15, player_rect.top))
bullet_right_rect = bullet_img.get_rect(midbottom=(player_rect.centerx + 15, player_rect.top))
bullets.append(bullet_left_rect)
bullets.append(bullet_right_rect)
bullet_sound.play() # 播放发射子弹的音效
# 定义函数:绘制子弹
def draw_bullets():
for bullet_rect in bullets:
screen.blit(bullet_img, bullet_rect)
# 定义函数:移动子弹
def move_bullets():
for bullet_rect in bullets:
bullet_rect.move_ip(0, -bullet_speed)
# 移除已经离开屏幕的子弹
bullets_copy = bullets.copy()
for bullet_rect in bullets_copy:
if bullet_rect.bottom < 0:
bullets.remove(bullet_rect)
# 定义函数:产生敌机
def generate_enemy():
enemy_rect = enemy_img.get_rect(midbottom=(random.randint(0, screen_width), 0))
enemies.append(enemy_rect)
# 定义函数:绘制敌机
def draw_enemies():
for enemy_rect in enemies:
screen.blit(enemy_img, enemy_rect)
# 定义函数:移动敌机
def move_enemies():
for enemy_rect in enemies:
enemy_rect.move_ip(0, enemy_speed)
# 移除已经离开屏幕的敌机
enemies_copy = enemies.copy()
for enemy_rect in enemies_copy:
if enemy_rect.top > screen_height:
enemies.remove(enemy_rect)
# 定义函数:检测碰撞
def check_collision():
global player_life, player_bullet_type, score
# 检测子弹是否击中敌机
bullets_copy = bullets.copy()
for bullet_rect in bullets_copy:
for enemy_rect in enemies:
if bullet_rect.colliderect(enemy_rect):
bullets.remove(bullet_rect)
enemies.remove(enemy_rect)
enemy_down_sound.play() # 播放敌机被击中的音效
score += 10
# 检测敌机是否撞到玩家
for enemy_rect in enemies:
if enemy_rect.colliderect(player_rect):
enemies.remove(enemy_rect)
player_life -= 1
if player_life == 0:
game_over()
# 检测玩家是否吃到甜甜圈
donuts_copy = donuts.copy()
for donut_rect in donuts_copy:
if donut_rect.colliderect(player_rect):
donuts.remove(donut_rect)
player_bullet_type = 1
pygame.time.set_timer(pygame.USEREVENT + 2, 5000) # 设置定时器,5秒后恢复普通弹
break
# 定义函数:产生云朵
def generate_cloud():
cloud_rect = cloud_img.get_rect(midbottom=(random.randint(0, screen_width), 0))
clouds.append(cloud_rect)
# 定义函数:绘制云朵
def draw_clouds():
for cloud_rect in clouds:
screen.blit(cloud_img, cloud_rect)
# 定义函数:移动云朵
def move_clouds():
for cloud_rect in clouds:
cloud_rect.move_ip(0, cloud_speed)
# 移除已经离开屏幕的云朵
clouds_copy = clouds.copy()
for cloud_rect in clouds_copy:
if cloud_rect.top > screen_height:
clouds.remove(cloud_rect)
# 定义函数:产生甜甜圈
def generate_donut():
donut_rect = donut_img.get_rect(midbottom=(random.randint(0, screen_width), 0))
donuts.append(donut_rect)
# 定义函数:绘制甜甜圈
def draw_donuts():
for donut_rect in donuts:
screen.blit(donut_img, donut_rect)
# 定义函数:移动甜甜圈
def move_donuts():
for donut_rect in donuts:
donut_rect.move_ip(0, donut_speed)
# 移除已经离开屏幕的甜甜圈
donuts_copy = donuts.copy()
for donut_rect in donuts_copy:
if donut_rect.top > screen_height:
donuts.remove(donut_rect)
# 定义函数:游戏结束
def game_over():
global game_status
game_status = GAME_STATUS_GAME_OVER
game_over_sound.play() # 播放游戏结束的音效
# 游戏主循环
bullets = []
enemies = []
clouds = []
donuts = []
clock = pygame.time.Clock()
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and game_status == GAME_STATUS_PLAYING:
if pygame.time.get_ticks() - bullet_timer >= bullet_interval:
fire_bullet()
bullet_timer = pygame.time.get_ticks()
elif event.key == pygame.K_RETURN and game_status != GAME_STATUS_PLAYING:
# 开始游戏或重新开始游戏
bullets.clear()
enemies.clear()
clouds.clear()
donuts.clear()
player_life = 3
player_bullet_type = 0
score = 0
player_rect = player_img.get_rect(center=(screen_width // 2, screen_height - 100))
game_status = GAME_STATUS_PLAYING
pygame.time.set_timer(pygame.USEREVENT + 1, enemy_interval) # 设置定时器,产生敌机
pygame.time.set_timer(pygame.USEREVENT + 3, cloud_interval) # 设置定时器,产生云朵
pygame.time.set_timer(pygame.USEREVENT + 4, donut_interval) # 设置定时器,产生甜甜圈
elif event.type == pygame.USEREVENT + 1: # 产生敌机
generate_enemy()
elif event.type == pygame.USEREVENT + 2: # 恢复普通弹
player_bullet_type = 0
elif event.type == pygame.USEREVENT + 3: # 产生云朵
generate_cloud()
elif event.type == pygame.USEREVENT + 4: # 产生甜甜圈
generate_donut()
# 更新游戏状态
if game_status == GAME_STATUS_PLAYING:
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_UP] or pressed_keys[pygame.K_w]:
player_rect.move_ip(0, -player_speed)
if pressed_keys[pygame.K_DOWN] or pressed_keys[pygame.K_s]:
player_rect.move_ip(0, player_speed)
if pressed_keys[pygame.K_LEFT] or pressed_keys[pygame.K_a]:
player_rect.move_ip(-player_speed, 0)
if pressed_keys[pygame.K_RIGHT] or pressed_keys[pygame.K_d]:
player_rect.move_ip(player_speed, 0)
# 限制玩家飞机在屏幕范围内
if player_rect.left < 0:
player_rect.left = 0
elif player_rect.right > screen_width:
player_rect.right = screen_width
if player_rect.top < 0:
player_rect.top = 0
elif player_rect.bottom > screen_height:
player_rect.bottom = screen_height
move_bullets()
move_enemies()
move_clouds()
move_donuts()
check_collision()
# 绘制游戏界面
screen.blit(background_img, (0, 0))
draw_text()
draw_player()
draw_bullets()
draw_enemies()
draw_clouds()
draw_donuts()
if game_status == GAME_STATUS_START:
# 绘制开始界面
start_text = font.render("按回车键开始游戏", True, (255, 255, 255))
screen.blit(start_text, ((screen_width - start_text.get_width()) // 2, screen_height // 2))
elif game_status == GAME_STATUS_GAME_OVER:
# 绘制游戏结束界面
game_over_text = font.render("游戏结束,得分:" + str(score), True, (255, 255, 255))
screen.blit(game_over_text, ((screen_width - game_over_text.get_width()) // 2, screen_height // 2))
restart_text = font.render("按回车键重新开始游戏", True, (255, 255, 255))
screen.blit(restart_text, ((screen_width - restart_text.get_width()) // 2, screen_height // 2 + 50))
pygame.display.update()
clock.tick(60)
```
注意:在执行示例代码前,需要将游戏图片资源、背景音乐和音效资源准备好,并且文件名需要与代码中的相同。
阅读全文