前面已经实现外星人的移动,现在开始完成射杀外星人。我们将要使用sprite.groupcollide()检测两个编组的碰撞。我们要在碰撞的时候立马就让外星人消失,所以在更新位置的时候就检测有无碰撞。
在功能模块检测子弹与外星人,方法sprite.groupcollide()将每颗子弹的rect同外星人的rect比较,返回一个字典,其中包含发生碰撞的子弹与外星人,在这个字典里每个键都是一颗子弹,而相应的值都是被击中的外星人。这样两者就相互对应起来了。
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
#游戏的功能模块,包括响应键盘鼠标事件,移动飞船等import sys
import pygame
from bullet import Bullet
from alien import Aliendef 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=Trueelif event.key==pygame.K_SPACE: #响应按空格键fire_bullet(ai_settings,screen,ship,bullets)def fire_bullet(ai_settings,screen,ship,bullets): #发射子弹if len(bullets)<ai_settings.bullets_allowed: new_bullet=Bullet(ai_settings,screen,ship)bullets.add(new_bullet)def check_keyup_events(event,ship): #响应按键松开if event.key==pygame.K_RIGHT:ship.moving_right=Falseelif event.key==pygame.K_LEFT:ship.moving_left=Falsedef 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 update_screen(ai_settings,screen,ship,aliens,bullets): # 更新屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites():bullet.draw_bullet()ship.blitme()aliens.draw(screen)pygame.display.flip()def update_bullets(aliens,bullets): #更新子弹的位置,并删除已消失的子弹bullets.update()for bullet in bullets.copy():if bullet.rect.bottom<=0:bullets.remove(bullet)#检查是否两者碰撞,是的话,删除相应的子弹与外星人collisions=pygame.sprite.groupcollide(bullets,aliens,True,True) #创建外星人群
def get_number_aliens_x(ai_settings,alien_width): #计算每行可以放入多少外星人available_space_x=ai_settings.screen_width-2*alien_widthnumber_aliens_x=int(available_space_x/(2*alien_width))return number_aliens_x def creat_alien(ai_settings,screen,aliens,alien_number,row_number):alien=Alien(ai_settings,screen) #创建一个外星人,放入当前行alien_width=alien.rect.widthalien.x=alien_width+2*alien_width*alien_numberalien.rect.x=alien.xalien.rect.y=alien.rect.height+2*alien.rect.height*row_numberaliens.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_rowsdef creat_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):creat_alien(ai_settings,screen,aliens,alien_number,row_number)#更新外星人的位置
def update_aliens(ai_settings,aliens):check_fleet_edges(ai_settings,aliens)aliens.update()#对于外星人到达边缘采取的措施:
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_settings,aliens):for alien in aliens.sprites():alien.rect.y+=ai_settings.fleet_drop_speedai_settings.fleet_direction*=-1
在函数update_bullets()添加一行代码,这行代码遍历编组里bullets的所有子弹,再遍历aliens的每个外星人,当有两者重叠的时候,groupcollide()就在它返回的字典中添加键-值。两个实参true告知pygame删除发生碰撞的子弹与外星人。(第一个实参true是代表的是删除子弹,第二个实参true是外星人。我们也可以设置子弹不删除,外星人删除,只要子弹与外星人碰撞,就会外星人消失,子弹可以一直移动到顶端,就把第一个布尔实参设为False,第二个布尔实参设为true)
主程序:
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
import pygamefrom setting import Setting
from ship import Ship
import game_functions as gf
from pygame.sprite import Groupdef run_game():pygame.init() #初始化,创建屏幕对象ai_settings=Setting() #创建一个800*800的屏幕screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #对于这个窗口的命名为Alien Invasionship=Ship(ai_settings,screen) #创建飞船bullets=Group()aliens=Group()gf.creat_fleet(ai_settings,screen,ship,aliens)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)run_game()
运行程序,看看验证结果:
生成新的外星人:
当射击的外星人都没有了,就要产生新的外星人,首先,我们要去确定外星人都被杀死,就要检查aliens编组是否为空,如果为空,就要调用creat_fleet().我们要在update_bullets()里执行检查,因为外星人在这里被击杀,
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
#游戏的功能模块,包括响应键盘鼠标事件,移动飞船等import sys
import pygame
from bullet import Bullet
from alien import Aliendef 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=Trueelif event.key==pygame.K_SPACE: #响应按空格键fire_bullet(ai_settings,screen,ship,bullets)def fire_bullet(ai_settings,screen,ship,bullets): #发射子弹if len(bullets)<ai_settings.bullets_allowed: new_bullet=Bullet(ai_settings,screen,ship)bullets.add(new_bullet)def check_keyup_events(event,ship): #响应按键松开if event.key==pygame.K_RIGHT:ship.moving_right=Falseelif event.key==pygame.K_LEFT:ship.moving_left=Falsedef 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 update_screen(ai_settings,screen,ship,aliens,bullets): # 更新屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites():bullet.draw_bullet()ship.blitme()aliens.draw(screen)pygame.display.flip()def update_bullets(ai_settings,screen,ship,aliens,bullets): #更新子弹的位置,并删除已消失的子弹bullets.update()for bullet in bullets.copy():if bullet.rect.bottom<=0:bullets.remove(bullet)#检查是否两者碰撞,是的话,删除相应的子弹与外星人collisions=pygame.sprite.groupcollide(bullets,aliens,True,True) if len(aliens)==0:bullets.empty() #删除现有的子弹并新建新的外星人群creat_fleet(ai_settings,screen,ship,aliens)#创建外星人群
def get_number_aliens_x(ai_settings,alien_width): #计算每行可以放入多少外星人available_space_x=ai_settings.screen_width-2*alien_widthnumber_aliens_x=int(available_space_x/(2*alien_width))return number_aliens_x def creat_alien(ai_settings,screen,aliens,alien_number,row_number):alien=Alien(ai_settings,screen) #创建一个外星人,放入当前行alien_width=alien.rect.widthalien.x=alien_width+2*alien_width*alien_numberalien.rect.x=alien.xalien.rect.y=alien.rect.height+2*alien.rect.height*row_numberaliens.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_rowsdef creat_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):creat_alien(ai_settings,screen,aliens,alien_number,row_number)#更新外星人的位置
def update_aliens(ai_settings,aliens):check_fleet_edges(ai_settings,aliens)aliens.update()#对于外星人到达边缘采取的措施:
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_settings,aliens):for alien in aliens.sprites():alien.rect.y+=ai_settings.fleet_drop_speedai_settings.fleet_direction*=-1
主程序:
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
import pygamefrom setting import Setting
from ship import Ship
import game_functions as gf
from pygame.sprite import Groupdef run_game():pygame.init() #初始化,创建屏幕对象ai_settings=Setting() #创建一个800*800的屏幕screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #对于这个窗口的命名为Alien Invasionship=Ship(ai_settings,screen) #创建飞船bullets=Group()aliens=Group()gf.creat_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)run_game()
运行程序,验证结果:
当我射杀完外星人后,就会出现新的外星人群。
重构功能模块里的update_bullets():
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
#游戏的功能模块,包括响应键盘鼠标事件,移动飞船等import sys
import pygame
from bullet import Bullet
from alien import Aliendef 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=Trueelif event.key==pygame.K_SPACE: #响应按空格键fire_bullet(ai_settings,screen,ship,bullets)def fire_bullet(ai_settings,screen,ship,bullets): #发射子弹if len(bullets)<ai_settings.bullets_allowed: new_bullet=Bullet(ai_settings,screen,ship)bullets.add(new_bullet)def check_keyup_events(event,ship): #响应按键松开if event.key==pygame.K_RIGHT:ship.moving_right=Falseelif event.key==pygame.K_LEFT:ship.moving_left=Falsedef 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 update_screen(ai_settings,screen,ship,aliens,bullets): # 更新屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites():bullet.draw_bullet()ship.blitme()aliens.draw(screen)pygame.display.flip()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 check_bullet_alien_collisions(ai_settings,screen,ship,aliens,bullets):#检查是否两者碰撞,是的话,删除相应的子弹与外星人collisions=pygame.sprite.groupcollide(bullets,aliens,True,True) if len(aliens)==0:bullets.empty() #删除现有的子弹并新建新的外星人群creat_fleet(ai_settings,screen,ship,aliens)#创建外星人群
def get_number_aliens_x(ai_settings,alien_width): #计算每行可以放入多少外星人available_space_x=ai_settings.screen_width-2*alien_widthnumber_aliens_x=int(available_space_x/(2*alien_width))return number_aliens_x def creat_alien(ai_settings,screen,aliens,alien_number,row_number):alien=Alien(ai_settings,screen) #创建一个外星人,放入当前行alien_width=alien.rect.widthalien.x=alien_width+2*alien_width*alien_numberalien.rect.x=alien.xalien.rect.y=alien.rect.height+2*alien.rect.height*row_numberaliens.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_rowsdef creat_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):creat_alien(ai_settings,screen,aliens,alien_number,row_number)#更新外星人的位置
def update_aliens(ai_settings,aliens):check_fleet_edges(ai_settings,aliens)aliens.update()#对于外星人到达边缘采取的措施:
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_settings,aliens):for alien in aliens.sprites():alien.rect.y+=ai_settings.fleet_drop_speedai_settings.fleet_direction*=-1
验证结果:没有问题
现在看来整个游戏开发的大体框架都已经完成了,现在可以实现移动飞船,发射子弹,子弹射杀外星人,外星人会重新补全等大概的功能,但是这个游戏会一直继续下去,除非你点击退出,但一个没有输赢的游戏大概会很无聊,所以接下来就来设置如何结束游戏,结束游戏有以下几种情况,1.不想玩了,直接点击退出键就结束游戏。2.如果玩家在限制的时间内未射杀完外星人,或者外星人撞到飞船以及外星人到达屏幕底端,飞船会被摧毁,最多可提供三架飞船,飞船摧毁完游戏自动结束。
1.监测外星人和飞船相撞的情况,就像子弹和外星人的相撞一样,在更新外星人的位置后就检测有无相撞。现在就是简单检查有没有撞到,对于后续的行为先不设置。
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
#游戏的功能模块,包括响应键盘鼠标事件,移动飞船等import sys
import pygame
from bullet import Bullet
from alien import Aliendef 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=Trueelif event.key==pygame.K_SPACE: #响应按空格键fire_bullet(ai_settings,screen,ship,bullets)def fire_bullet(ai_settings,screen,ship,bullets): #发射子弹if len(bullets)<ai_settings.bullets_allowed: new_bullet=Bullet(ai_settings,screen,ship)bullets.add(new_bullet)def check_keyup_events(event,ship): #响应按键松开if event.key==pygame.K_RIGHT:ship.moving_right=Falseelif event.key==pygame.K_LEFT:ship.moving_left=Falsedef 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 update_screen(ai_settings,screen,ship,aliens,bullets): # 更新屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites():bullet.draw_bullet()ship.blitme()aliens.draw(screen)pygame.display.flip()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 check_bullet_alien_collisions(ai_settings,screen,ship,aliens,bullets):#检查是否两者碰撞,是的话,删除相应的子弹与外星人collisions=pygame.sprite.groupcollide(bullets,aliens,True,True) if len(aliens)==0:bullets.empty() #删除现有的子弹并新建新的外星人群creat_fleet(ai_settings,screen,ship,aliens)#创建外星人群
def get_number_aliens_x(ai_settings,alien_width): #计算每行可以放入多少外星人available_space_x=ai_settings.screen_width-2*alien_widthnumber_aliens_x=int(available_space_x/(2*alien_width))return number_aliens_x def creat_alien(ai_settings,screen,aliens,alien_number,row_number):alien=Alien(ai_settings,screen) #创建一个外星人,放入当前行alien_width=alien.rect.widthalien.x=alien_width+2*alien_width*alien_numberalien.rect.x=alien.xalien.rect.y=alien.rect.height+2*alien.rect.height*row_numberaliens.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_rowsdef creat_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):creat_alien(ai_settings,screen,aliens,alien_number,row_number)#更新外星人的位置
def update_aliens(ai_settings,ship,aliens):check_fleet_edges(ai_settings,aliens)aliens.update()#监测外星人和飞船的相撞if pygame.sprite.spritecollideany(ship,aliens):print("ship hit!!!")#对于外星人到达边缘采取的措施:
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_settings,aliens):for alien in aliens.sprites():alien.rect.y+=ai_settings.fleet_drop_speedai_settings.fleet_direction*=-1
方法sprite.spritecollideany()接受两个实参,一个精灵和一个编组,它检查编组是否有成员与精灵发生了碰撞,找到与精灵发生碰撞的成员后就停止遍历编组。如果没有发生碰撞,返回none。
主程序:
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
import pygamefrom setting import Setting
from ship import Ship
import game_functions as gf
from pygame.sprite import Groupdef run_game():pygame.init() #初始化,创建屏幕对象ai_settings=Setting() #创建一个800*800的屏幕screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #对于这个窗口的命名为Alien Invasionship=Ship(ai_settings,screen) #创建飞船bullets=Group()aliens=Group()gf.creat_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,ship,aliens)gf.update_screen(ai_settings,screen,ship,aliens,bullets)run_game()
运行程序。看看验证结果:
按上面的代码现在已经检测到相撞了,现在就在来响应下相撞后该有什么行为;现在创建一个新的飞船实例 ,记录游戏飞船被撞毁几次
创建一个用于记录跟踪游戏信息的新类Gamestats
#跟踪游戏统计信息的类
class GameStats():def __init__(self,ai_settings):self.ai_settings=ai_settingsself.reset_stats()self.game_active=True #游戏活动标志def reset_stats(self): #初始化在游戏里可能会变化的统计信息self.ships_left=self.ai_settings.ship_limit
创建一个GameStats的实例,每当开始新游戏的时候,重置设置一些统计信息,当前只有一项统计信息ships_left。
修改设置类;
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
#存储外星人游戏开发的设置
class Setting():def __init__(self):self.screen_width=800 #设置屏幕高度宽度,背景颜色self.screen_height=600self.bg_color=(230,230,230)#飞船设置self.ship_speed_factor=1.5 #设置飞船移动self.ship_limit=3 #设置飞船数量#子弹设置self.bullet_speed_factor=1self.bullet_width=3self.bullet_height=15self.bullet_color=(0,0,255)self.bullets_allowed=3#外星人设置self.alien_speed_factor=1self.fleet_drop_speed=5self.fleet_direction=1 #fleet_direction 为1表示右移,为-1表示左移
修改功能模块:当外星人撞到飞船,将飞船的数量减一,创建一群新的外星人,并将飞船放置到初始位置。
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
#游戏的功能模块,包括响应键盘鼠标事件,移动飞船等import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleepdef 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=Trueelif event.key==pygame.K_SPACE: #响应按空格键fire_bullet(ai_settings,screen,ship,bullets)def fire_bullet(ai_settings,screen,ship,bullets): #发射子弹if len(bullets)<ai_settings.bullets_allowed: new_bullet=Bullet(ai_settings,screen,ship)bullets.add(new_bullet)def check_keyup_events(event,ship): #响应按键松开if event.key==pygame.K_RIGHT:ship.moving_right=Falseelif event.key==pygame.K_LEFT:ship.moving_left=Falsedef 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 update_screen(ai_settings,screen,ship,aliens,bullets): # 更新屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites():bullet.draw_bullet()ship.blitme()aliens.draw(screen)pygame.display.flip()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 check_bullet_alien_collisions(ai_settings,screen,ship,aliens,bullets):#检查是否两者碰撞,是的话,删除相应的子弹与外星人collisions=pygame.sprite.groupcollide(bullets,aliens,True,True) if len(aliens)==0:bullets.empty() #删除现有的子弹并新建新的外星人群creat_fleet(ai_settings,screen,ship,aliens)#创建外星人群
def get_number_aliens_x(ai_settings,alien_width): #计算每行可以放入多少外星人available_space_x=ai_settings.screen_width-2*alien_widthnumber_aliens_x=int(available_space_x/(2*alien_width))return number_aliens_x def creat_alien(ai_settings,screen,aliens,alien_number,row_number):alien=Alien(ai_settings,screen) #创建一个外星人,放入当前行alien_width=alien.rect.widthalien.x=alien_width+2*alien_width*alien_numberalien.rect.x=alien.xalien.rect.y=alien.rect.height+2*alien.rect.height*row_numberaliens.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_rowsdef creat_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):creat_alien(ai_settings,screen,aliens,alien_number,row_number)#更新外星人的位置
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)#响应被外星人撞到的飞船
def ship_hit(ai_settings,stats,screen,ship,aliens,bullets):stats.ships_left-=1aliens.empty() #清空外星人列表bullets.empty() #清空子弹列表#创建新的外星人,飞船放入中间creat_fleet(ai_settings,screen,ship,aliens)ship.center_ship()sleep(0.5) #暂停#对于外星人到达边缘采取的措施:
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_settings,aliens):for alien in aliens.sprites():alien.rect.y+=ai_settings.fleet_drop_speedai_settings.fleet_direction*=-1
从模块time导入sleep,用于让游戏暂停;
修改ship类:
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
#创建飞船类
import pygameclass Ship(): def __init__(self,ai_settings,screen):self.screen=screenself.ai_settings=ai_settings#图片存在images文件夹下,名字是ship.bmp self.image=pygame.image.load('images/ship.bmp') self.rect=self.image.get_rect()self.screen_rect=screen.get_rect()self.rect.centerx=self.screen_rect.centerxself.rect.bottom=self.screen_rect.bottomself.center=float(self.rect.centerx) #因为rect的centerx只能储存整数值,在飞船的center储存小数值self.moving_right=False #设置移动标志self.moving_left=Falsedef update(self):if self.moving_right and self.rect.right <self.screen_rect.right: #根据移动标志,来调整位置self.center+=self.ai_settings.ship_speed_factor #更新飞船的center的值,不是rectif self.moving_left and self.rect.left>0:self.center-=self.ai_settings.ship_speed_factorself.rect.centerx=self.center #来更新rect对象def blitme(self):self.screen.blit(self.image,self.rect) def center_ship(self):self.center=self.screen_rect.centerx
修改主程序:
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
import pygamefrom setting import Setting
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from game_stats import GameStatsdef run_game():pygame.init() #初始化,创建屏幕对象ai_settings=Setting() #创建一个800*800的屏幕screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #对于这个窗口的命名为Alien Invasionstats=GameStats(ai_settings) #创建一个用于存储统计信息的实例ship=Ship(ai_settings,screen) #创建飞船bullets=Group()aliens=Group()gf.creat_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,stats,screen,ship,aliens,bullets)gf.update_screen(ai_settings,screen,ship,aliens,bullets)run_game()
运行程序,验证结果如下:
当相撞后,飞船与外星人重新出现,飞船在初始位置
2.有外星人到达屏幕底端:
上面已经处理相撞的情况,现在来处理到达底端的时候,
修改功能模块,添加一个检查函数,来检查是否到达底部
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
#游戏的功能模块,包括响应键盘鼠标事件,移动飞船等import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleepdef 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=Trueelif event.key==pygame.K_SPACE: #响应按空格键fire_bullet(ai_settings,screen,ship,bullets)def fire_bullet(ai_settings,screen,ship,bullets): #发射子弹if len(bullets)<ai_settings.bullets_allowed: new_bullet=Bullet(ai_settings,screen,ship)bullets.add(new_bullet)def check_keyup_events(event,ship): #响应按键松开if event.key==pygame.K_RIGHT:ship.moving_right=Falseelif event.key==pygame.K_LEFT:ship.moving_left=Falsedef 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 update_screen(ai_settings,screen,ship,aliens,bullets): # 更新屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites():bullet.draw_bullet()ship.blitme()aliens.draw(screen)pygame.display.flip()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 check_bullet_alien_collisions(ai_settings,screen,ship,aliens,bullets):#检查是否两者碰撞,是的话,删除相应的子弹与外星人collisions=pygame.sprite.groupcollide(bullets,aliens,True,True) if len(aliens)==0:bullets.empty() #删除现有的子弹并新建新的外星人群creat_fleet(ai_settings,screen,ship,aliens)#创建外星人群
def get_number_aliens_x(ai_settings,alien_width): #计算每行可以放入多少外星人available_space_x=ai_settings.screen_width-2*alien_widthnumber_aliens_x=int(available_space_x/(2*alien_width))return number_aliens_x def creat_alien(ai_settings,screen,aliens,alien_number,row_number):alien=Alien(ai_settings,screen) #创建一个外星人,放入当前行alien_width=alien.rect.widthalien.x=alien_width+2*alien_width*alien_numberalien.rect.x=alien.xalien.rect.y=alien.rect.height+2*alien.rect.height*row_numberaliens.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_rowsdef creat_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):creat_alien(ai_settings,screen,aliens,alien_number,row_number)#更新外星人的位置
def update_aliens(ai_settings,stats,screen,ship,aliens,bullets):check_fleet_edges(ai_settings,aliens)aliens.update()check_aliens_bottom(ai_settings,stats,screen,ship,aliens,bullets)#监测外星人和飞船的相撞if pygame.sprite.spritecollideany(ship,aliens):ship_hit(ai_settings,stats,screen,ship,aliens,bullets)#响应被外星人撞到的飞船
def ship_hit(ai_settings,stats,screen,ship,aliens,bullets):if stats.ships_left>0:stats.ships_left-=1aliens.empty() #清空外星人列表bullets.empty() #清空子弹列表#创建新的外星人,飞船放入中间creat_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#对于外星人到达左右边缘采取的措施:
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_settings,aliens):for alien in aliens.sprites():alien.rect.y+=ai_settings.fleet_drop_speedai_settings.fleet_direction*=-1
主程序如下:
#-*-coding:GBK-*-
#-*-coding:utf-8-*-
import pygamefrom setting import Setting
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from game_stats import GameStatsdef run_game():pygame.init() #初始化,创建屏幕对象ai_settings=Setting() #创建一个800*800的屏幕screen=pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") #对于这个窗口的命名为Alien Invasionstats=GameStats(ai_settings) #创建一个用于存储统计信息的实例ship=Ship(ai_settings,screen) #创建飞船bullets=Group()aliens=Group()gf.creat_fleet(ai_settings,screen,ship,aliens)while True:gf.check_events(ai_settings,screen,ship,bullets)if stats.game_active:ship.update()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()
当把飞船次数用完后,屏幕到停止不动了: