[关闭]
@websec007 2020-06-22T11:10:21.000000Z 字数 2410 阅读 961

Alien Invasion - 13.6.1 外星人与飞船碰撞

2020.Python从入门到实践


13.6.1 外星人与飞船碰撞

一、学习理解部分

外星人与飞船的碰撞与响应处置,实际代码需要完成的任务需求有如下2个过程


二、代码实现部分

2.1 外星人与飞船的碰撞检测

++++++++++++++++++gf.update_aliens()++++++++++++++++++++++

  1. def update_aliens(aliens, game_settings, ship, stats, bullets, screen):
  2. """外星人碰壁检查,并更新外星人位置"""
  3. check_fleet_edges(aliens, game_settings)
  4. aliens.update()
  5. # 外星人与飞船的碰撞检测
  6. if pygame.sprite.spritecollideany(ship, aliens):
  7. ship_hit(stats, aliens, bullets, screen, game_settings, ship)

2.2 响应与处置外星人与飞船碰撞结果

++++++++++++++++++gf.ship_hit()++++++++++++++++++++++

  1. """13.6.1 检测外星人与飞船碰撞"""
  2. def ship_hit(stats, aliens, bullets, screen, game_settings, ship):
  3. """响应外星人与飞船碰撞"""
  4. # 将ships_left减1
  5. stats.ships_left -= 1
  6. # 清空外星人与子弹列表
  7. aliens.empty()
  8. bullets.empty()
  9. # 创建新的外星人舰队,并将置飞船于屏幕底部中央
  10. create_fleet(screen, game_settings, ship, aliens)
  11. ship.center_ship()
  12. # 暂停
  13. sleep(1)

++++++++++++++++++alien_invasion.py++++++++++++++++++++++

  1. # 2. screen surface
  2. ...
  3. # 调用gf中的函数创建外星人
  4. gf.create_fleet(screen, game_settings, ship, aliens)
  5. # 创建一个用于存储游戏统计信息的实例
  6. stats = GameStats(game_settings)

++++++++++++++++++gamestats.py++++++++++++++++++++++

  1. # 创建一个跟踪游戏统计信息的类
  2. class GameStats():
  3. """跟踪游戏的统计信息"""
  4. def __init__(self, game_settings):
  5. """初始化统计信息"""
  6. self.game_settings = game_settings
  7. self.reset_stats()
  8. def reset_stats(self):
  9. """初始化在游戏期间可能变化的统计信息"""
  10. self.ships_left = self.game_settings.ship_limit

++++++++++++++++++settings.py++++++++++++++++++++++

  1. # 游戏配置设置
  2. class Settings:
  3. def __init__(self):
  4. self.width = 1000
  5. self.height = 520
  6. self.size = self.width, self.height
  7. self.bg_color = 231, 231, 231
  8. # 飞船基本设置
  9. self.ship_speed_factor = 1.6
  10. self.ship_limit = 3
  11. ...snip...

++++++++++++++++++ship.py++++++++++++++++++++++

  1. import pygame
  2. class Ship():
  3. ...
  4. def center_ship(self):
  5. """重置新飞船置于屏幕中央底部位置"""
  6. self.rect.centerx = self.screen_rect.centerx

2.3 游戏更新与绘制

++++++++++++++++++gf.update_screen()++++++++++++++++++++++

  1. def update_screen(screen, bg_color, ship, bullets, aliens, game_settings, stats):
  2. ...
  3. # 绘制编组中的每一个子弹矩形图形
  4. draw_bullets(bullets)
  5. # 外星人移动更新
  6. update_aliens(aliens, game_settings, ship, stats, bullets, screen)
  7. # 绘制外星人
  8. # 这里是组的方法进行alien逐个绘制方法(精灵自带函数)
  9. aliens.draw(screen)

++++++++++++++++++alien_invasion.py++++++++++++++++++++++

  1. # 3. Game loop
  2. while True:
  3. # (1) process Input
  4. # 重构事件监控
  5. gf.check_events(ship, screen, game_settings, bullets)
  6. # (2) Update Game
  7. # 重构游戏画面绘制与更新
  8. gf.update_screen(screen, bg_color, ship, bullets, aliens, game_settings, stats)
  9. # (3) render
  10. pygame.display.update()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注