@websec007
2020-06-22T11:10:21.000000Z
字数 2410
阅读 933
2020.Python从入门到实践
外星人与飞船的碰撞与响应处置,实际代码需要完成的任务需求有如下2个过程
++++++++++++++++++gf.update_aliens()++++++++++++++++++++++
def update_aliens(aliens, game_settings, ship, stats, bullets, screen):
"""外星人碰壁检查,并更新外星人位置"""
check_fleet_edges(aliens, game_settings)
aliens.update()
# 外星人与飞船的碰撞检测
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(stats, aliens, bullets, screen, game_settings, ship)
++++++++++++++++++gf.ship_hit()++++++++++++++++++++++
"""13.6.1 检测外星人与飞船碰撞"""
def ship_hit(stats, aliens, bullets, screen, game_settings, ship):
"""响应外星人与飞船碰撞"""
# 将ships_left减1
stats.ships_left -= 1
# 清空外星人与子弹列表
aliens.empty()
bullets.empty()
# 创建新的外星人舰队,并将置飞船于屏幕底部中央
create_fleet(screen, game_settings, ship, aliens)
ship.center_ship()
# 暂停
sleep(1)
++++++++++++++++++alien_invasion.py++++++++++++++++++++++
# 2. screen surface
...
# 调用gf中的函数创建外星人
gf.create_fleet(screen, game_settings, ship, aliens)
# 创建一个用于存储游戏统计信息的实例
stats = GameStats(game_settings)
++++++++++++++++++gamestats.py++++++++++++++++++++++
# 创建一个跟踪游戏统计信息的类
class GameStats():
"""跟踪游戏的统计信息"""
def __init__(self, game_settings):
"""初始化统计信息"""
self.game_settings = game_settings
self.reset_stats()
def reset_stats(self):
"""初始化在游戏期间可能变化的统计信息"""
self.ships_left = self.game_settings.ship_limit
++++++++++++++++++settings.py++++++++++++++++++++++
# 游戏配置设置
class Settings:
def __init__(self):
self.width = 1000
self.height = 520
self.size = self.width, self.height
self.bg_color = 231, 231, 231
# 飞船基本设置
self.ship_speed_factor = 1.6
self.ship_limit = 3
...snip...
++++++++++++++++++ship.py++++++++++++++++++++++
import pygame
class Ship():
...
def center_ship(self):
"""重置新飞船置于屏幕中央底部位置"""
self.rect.centerx = self.screen_rect.centerx
++++++++++++++++++gf.update_screen()++++++++++++++++++++++
def update_screen(screen, bg_color, ship, bullets, aliens, game_settings, stats):
...
# 绘制编组中的每一个子弹矩形图形
draw_bullets(bullets)
# 外星人移动更新
update_aliens(aliens, game_settings, ship, stats, bullets, screen)
# 绘制外星人
# 这里是组的方法进行alien逐个绘制方法(精灵自带函数)
aliens.draw(screen)
++++++++++++++++++alien_invasion.py++++++++++++++++++++++
# 3. Game loop
while True:
# (1) process Input
# 重构事件监控
gf.check_events(ship, screen, game_settings, bullets)
# (2) Update Game
# 重构游戏画面绘制与更新
gf.update_screen(screen, bg_color, ship, bullets, aliens, game_settings, stats)
# (3) render
pygame.display.update()