目录
13.4.4 向下移动外星人群并改变移动方向
def check_fleet_edges(ai_settings, aliens):
"""有外星人到达边缘时采取相应的措施"""
1 for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settings, aliens)
break
def change_fleet_direction(ai_settings, aliens):
"""将整群外星人下移,并改变它们的方向"""
for alien in aliens.sprites():
2 alien.rect.y += ai_settings.fleet_drop_speed
ai_settings.fleet_direction *= -1
def update_aliens(ai_settings, aliens):
"""
检查是否有外星人位于屏幕边缘,并更新整群外星人的位置
"""
3 check_fleet_edges(ai_settings, aliens)
aliens.update()
# 开始游戏主循环
while True:
gf.check_events(ai_settings, screen, ship, bullets)
ship.update()
gf.update_bullets(bullets)
gf.update_aliens(ai_settings, aliens)
gf.update_screen(ai_settings, screen, ship, aliens, bullets)
13.5 射杀外星人
13.5.1 检测子弹与外星人的碰撞
def update_bullets(aliens, bullets):
"""更新子弹的位置,并删除已消失的子弹"""
--snip--
# 检查是否有子弹击中了外星人
# 如果是这样,就删除相应的子弹和外星人
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
# 开始游戏主循环
while True:
gf.check_events(ai_settings, screen, ship, bullets)
ship.update()
gf.update_bullets(aliens, bullets)
gf.update_aliens(ai_settings, aliens)
gf.update_screen(ai_settings, screen, ship, aliens, bullets)
13.5.2 为测试创建大子弹
13.5.3 生成新的外星人群
def update_bullets(ai_settings, screen, ship, aliens, bullets):
--snip--
# 检查是否有子弹击中了外星人
# 如果是,就删除相应的子弹和外星人
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
1 if len(aliens) == 0:
# 删除现有的子弹并新建一群外星人
2 bullets.empty()
create_fleet(ai_settings, screen, ship, aliens)
# 开始游戏主循环
while True:
gf.check_events(ai_settings, screen, ship, bullets)
ship.update()
gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
gf.update_aliens(ai_settings, aliens)
gf.update_screen(ai_settings, screen, ship, aliens, bullets)
13.5.4 提高子弹的速度
# 子弹设置
self.bullet_speed_factor = 3
self.bullet_width = 3
--snip--
13.5.5 重构 update_bullets()
def update_bullets(ai_settings, screen, ship, aliens, bullets):
--snip
# 删除已消失的子弹
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets)
def check_bullet_alien_collisions(ai_settings, screen, ship, aliens, bullets):
"""响应子弹和外星人的碰撞"""
# 删除发生碰撞的子弹和外星人
collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)
if len(aliens) == 0:
# 删除现有的所有子弹,并创建一个新的外星人群
bullets.empty()
create_fleet(ai_settings, screen, ship, aliens)
13.6 结束游戏
13.6.1 检测外星人和飞船碰撞
def update_aliens(ai_settings, ship, aliens):
"""
检查是否有外星人到达屏幕边缘
然后更新所有外星人的位置
"""
check_fleet_edges(ai_settings, aliens)
aliens.update()
# 检测外星人和飞船之间的碰撞
1 if pygame.sprite.spritecollideany(ship, aliens):
2 print("Ship hit!!!")
# 开始游戏主循环
while True:
gf.check_events(ai_settings, screen, ship, bullets)
ship.update()
gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
gf.update_aliens(ai_settings, ship, aliens)
gf.update_screen(ai_settings, screen, ship, aliens, bullets)
关于“Python”的核心知识点整理大全25-CSDN博客