一、删除已消失的子弹
更新:\FatChickenWars.py:
...
while True:
# 监视键盘和鼠标事件
gf.check_events(fcw_settings, screen, chicken, bullets)
# 更新肥鸡状态
chicken.update()
# 更新子弹状态
bullets.update()
# 删除已消失的子弹
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
# print(len(bullets))
# 更新画面
gf.update_screen(fcw_settings, screen, chicken, bullets)
...
二、限制子弹数量
限制屏幕上最大子弹数为3。
增添:\settings.py:
self.bullets_allowed = 3
更新:\game_functions.py:
...
elif event.key == pygame.K_SPACE:
# 创建一颗子弹,并将其加入编组中
if len(bullets) < fcw_settings.bullets_allowed:
new_bullet = Bullet(fcw_settings, screen, chicken)
bullets.add(new_bullet)
...
现在屏幕上最多有3颗子弹。
三、创建相关函数
将上述代码整合至函数中,精简主循环中的代码。
更新:\game_functions.py:
...
elif event.key == pygame.K_SPACE:
fire_bullet(fcw_settings, screen, chicken, bullets)
...
def update_bullets(bullets):
"""更新子弹位置,并消除已消失的子弹"""
bullets.update()
# 删除已消失的子弹
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet)
def fire_bullet(fcw_settings, screen, chicken, bullets):
"""如果子弹数目未超限,就发射一颗子弹"""
# 创建一颗子弹,并将其加入编组中
if len(bullets) < fcw_settings.bullets_allowed:
new_bullet = Bullet(fcw_settings, screen, chicken)
bullets.add(new_bullet)
更新:\FatChickenWars.py:
...
while True:
# 监视键盘和鼠标事件
gf.check_events(fcw_settings, screen, chicken, bullets)
# 更新肥鸡状态
chicken.update()
# 更新子弹状态
gf.update_bullets(bullets)
# 更新画面
gf.update_screen(fcw_settings, screen, chicken, bullets)
...
多么赏心悦目的代码。
2021.1.22