基于pygame的射击小游戏制作(四)击杀外星人

tech2022-11-26  89

在本篇文章中,主要学习射击子弹时外星人消失,达到击杀外星人的效果

一、编程思路

1.1击杀

我们需要在碰撞发生后让外星人立即消失,故在更新子弹的位置后检测碰撞。我们创建一个字典,这个字典的每一个键都是一颗子弹,而相应的键值则包含击中的外星人。sprite.groupcollide()将每颗子弹的rect与每个rect比较。每当有子弹和外星人的rect重叠时,判断其被子弹击中,groupcollide()就在返回字典中添加一个键-值对。 game_functions.py

def update_bullets(aliens, bullets): """更新子弹的位置,并删除已消失的子弹""" --snip-- # 检查是否有子弹击中了外星人 # 如果是这样,就删除相应的子弹和外星人 collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

紧接着在alien_invasion.py的while循环中加入该方法

# 开始游戏主循环 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)

此时的运行效果如下:

1.2产生新外星人

要在所有外星人被消灭之后再产生新的一群外星人,我们需要检查aliens编组是否为空,如果为空,就调用empty()删除所有元素,从而删除现有的子弹,再调用creat_fleet(),产生一群新的外星人

def update_bullets(ai_settings, screen, ship, aliens, bullets): --snip-- # 检查是否有子弹击中了外星人 # 如果是,就删除相应的子弹和外星人 collisions = pygame.sprite.groupcollide(bullets, aliens,True, True) if len(aliens) == 0: # 删除现有的子弹并新建一群外星人 bullets.empty() create_fleet(ai_settings, screen, ship, aliens)

1.3 重构update_bullets()

把处理子弹和外星人碰撞的代码已到一个独立的函数中,避免该函数过长。

def update_bullets(ai_settings, screen, ship, aliens, bullets): """更新子弹的位置,删除已消失的子弹""" #更新子弹位置 bullets.update() # 删除已经消失的子弹 for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) check_bullet_alien_collisions(ai_settings, screen,ship, aliens, bullets)

1.4 结束游戏

在外星人与飞船碰撞时或者外星人到达屏幕底端就结束游戏。首先我们要检测外星人与飞船是否碰撞,调用方法spritecollideany(),它检查编组中的外星人是否发生碰撞,找到与飞船碰撞的外星人后就停止遍历编组。

# 检测外星人和飞船之间的碰撞 if pygame.sprite.spritecollideany(ship, aliens): print("Ship hit!!!")

新建一个GameStats.py,通过跟踪游戏的统计信息来记录飞船被撞了多少次,reset_stats()中初始化大部分统计信息,然后在__init__中调用,有外星人撞到飞船时,我们将余下的飞船数减1,创建一群新的外星人,并将飞船重新放置到屏幕底端中央,并暂停0.5秒。 game_stats.py

class GameStates(): """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" self.ai_settings = ai_settings self.reset_stats() #游戏刚启动时处于活动状态 self.game_active = True def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" self.ships_left = self.ai_settings.ship_limit

game_functions.py

def ship_hit(ai_settings, stats, screen, ship, aliens, bullets): """响应被外星人撞到的飞船""" if stats.ships_left > 0: #将ships_left减1 stats.ships_left -= 1 #清空外星人列表和子弹列表 aliens.empty() bullets.empty() #创建新的外星人 create_fleet(ai_settings, screen, ship, aliens) ship.center_ship() #暂停 sleep(0.5) else: stats.game_active = False

check_aliens_bottom()在外星人到达屏幕底端时像外星人碰撞飞船一样做出响应

def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets): """检查是否有外星人到达""" screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: #像飞船被撞到一样进行处理 ship_hit(ai_settings, stats, screen, ship, aliens, bullets) break

在game_stats.py的init方法里加入游戏活动状态game_active = True,可以在玩家生命次数用完时game_active = False 结束游戏。

二、源程序

alien_invasion.py

import sys #退出游戏 import pygame #包含开发所需功能 from settings import Settings from ship import Ship from alien import Alien import game_functions as gf from pygame.sprite import Group from game_stats import GameStates def run_game(): # 初始化背景设置 pygame.init() ai_settings = Settings() # 创建游戏窗口 screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") """创建一艘飞船""" ship = Ship(ai_settings, screen) """创建一个外星人""" alien = Alien(ai_settings, screen) """创建一个用于存储子弹的编组""" bullets = Group() aliens = Group() #创建外星人群 gf.create_fleet(ai_settings,screen, ship, aliens) """设置背景色""" bg_color = (230,230,230) """存储游戏统计信息""" stats = GameStates(ai_settings) """游戏主循环""" while True: """监视键鼠事件""" gf.check_events(ai_settings, screen, ship, bullets) if stats.game_active: ship.update() #print(len(bullets)) gf.update_bullets(ai_settings, screen, ship, aliens, bullets) gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets) gf.update_screen(ai_settings, screen, ship, aliens, bullets) run_game()

game_stats.py

class GameStates(): """跟踪游戏的统计信息""" def __init__(self, ai_settings): """初始化统计信息""" self.ai_settings = ai_settings self.reset_stats() #游戏刚启动时处于活动状态 self.game_active = True def reset_stats(self): """初始化在游戏运行期间可能变化的统计信息""" self.ships_left = self.ai_settings.ship_limit

game_functions.py

import sys import pygame from bullet import Bullet from alien import Alien from time import sleep def check_events(ai_settings, screen, ship, bullets): #键鼠响应 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: check_keydown_events(event, ai_settings, screen, ship, bullets) elif event.type == pygame.KEYUP: check_keyup_events(event, ship) def check_keydown_events(event, ai_settings, screen, ship, bullets): """响应按键""" if event.key == pygame.K_RIGHT: # 向右移动飞船 ship.moving_right = True elif event.key == pygame.K_LEFT: ship.moving_left = True elif event.key == pygame.K_SPACE: fire_bullet(ai_settings, screen, ship, bullets) elif event.key == pygame.K_q: sys.exit() def check_keyup_events(event, ship): if event.key == pygame.K_RIGHT: ship.moving_right = False elif event.key == pygame.K_LEFT: ship.moving_left = False def update_screen(ai_settings, screen, ship, aliens, bullets): #更新屏幕图像 # 每次循环时都重绘屏幕 screen.fill(ai_settings.bg_color) #在飞船和外星人后面重绘所有子弹 for bullets in bullets.sprites(): bullets.draw_bullet() ship.blitme() aliens.draw(screen) # 让最近绘制的屏幕可见 pygame.display.flip() # 不断更新屏幕 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) def update_bullets(ai_settings, screen, ship, aliens, bullets): """更新子弹的位置,删除已消失的子弹""" #更新子弹位置 bullets.update() # 删除已经消失的子弹 for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) check_bullet_alien_collisions(ai_settings, screen,ship, aliens, bullets) def fire_bullet(ai_settings, screen, ship, bullets): """如果还没有达到限制,就发射一颗子弹""" # 创建一颗子弹,并将其加入到编组bullets if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) def create_fleet(ai_settings, screen,ship , aliens): """创建外星人群""" #创建一个外星人,并计算一行可以容纳多少个外星人 #外星人间距为外星人宽度 alien = Alien(ai_settings, screen) number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width) number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height) #创建外星人群 for row_number in range(number_rows): for alien_number in range(number_aliens_x): #创建第一个外星人并加入当前行 create_alien(ai_settings, screen, aliens, alien_number, row_number) def get_number_aliens_x(ai_settings, alien_width): """计算每行可容纳多少个外星人""" available_space_x = ai_settings.screen_width - 2 * alien_width number_aliens_x = int(available_space_x / (2 * alien_width)) return number_aliens_x def create_alien(ai_settings, screen, aliens, alien_number , row_number): """创建一个外星人并将其放在当前行""" alien = Alien(ai_settings, screen) alien_width = alien.rect.width alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number aliens.add(alien) def get_number_rows(ai_settings, ship_height, alien_height): """计算屏幕可以容纳多少行外星人""" available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height) number_rows = int(available_space_y / (2 * alien_height)) return number_rows def check_fleet_edges(ai_settings, aliens): """外星人到达边缘时采取相应的措施""" for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) break def change_fleet_direction(ai_setting, aliens): """将整群外星人下移,并改变他们的方向""" for alien in aliens.sprites(): alien.rect.y += ai_setting.fleet_drop_speed ai_setting.fleet_direction *= -1 def update_aliens(ai_settings, stats, screen, ship, aliens, bullets): """检查是否有外星人位于屏幕边缘,并更新整群外星人的位置""" check_fleet_edges(ai_settings, aliens) aliens.update() #检测外星人和飞船之间的碰撞 if pygame.sprite.spritecollideany(ship, aliens): ship_hit(ai_settings, stats, screen, ship, aliens, bullets) """"检查是否到达地端""" check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets) def ship_hit(ai_settings, stats, screen, ship, aliens, bullets): """响应被外星人撞到的飞船""" if stats.ships_left > 0: #将ships_left减1 stats.ships_left -= 1 #清空外星人列表和子弹列表 aliens.empty() bullets.empty() #创建新的外星人 create_fleet(ai_settings, screen, ship, aliens) ship.center_ship() #暂停 sleep(0.5) else: stats.game_active = False def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets): """检查是否有外星人到达""" screen_rect = screen.get_rect() for alien in aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: #像飞船被撞到一样进行处理 ship_hit(ai_settings, stats, screen, ship, aliens, bullets) break

三、运行效果

最新回复(0)