#Python# Alien Invasion项目(八)
- 在Play按钮的基础上,重置游戏
- 提高游戏难度
- 实现计分系统
- 总结
在Play按钮的基础上,重置游戏
希望于Play按钮不仅仅作为游戏开始的按钮,也可以作为游戏结束后重新开始时的按钮,即将游戏重新激活。所以首先更新game_functions模块中响应Play的函数,并加入隐藏光标的功能
game_functions.py
import sys
from time import sleep
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 = Trueelif 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: # 按Q退出游戏sys.exit(0)def check_keyup_evets(event,ship):'''响应松开按键'''if event.key == pygame.K_RIGHT:ship.moving_right = Falseelif event.key == pygame.K_LEFT:ship.moving_left = False def check_events(ai_settings,screen,stats,play_button,ship,bullets):'''响应按键和鼠标事件'''for event in pygame.event.get():if event.type == pygame.QUIT: # 检测游戏窗口关闭按钮是否被点击sys.exit(0) # 退出游戏 不抛出异常退出elif event.type == pygame.KEYDOWN: # 按下按键check_keydown_events(event,ai_settings,screen,ship,bullets)elif event.type == pygame.KEYUP: # 松开按键check_keyup_evets(event,ship)elif event.type == pygame.MOUSEBUTTONDOWN: # 按下鼠标mouse_x,mouse_y = pygame.mouse.get_pos()check_play_buttom(stats,play_buttom,mouse_x,mouse_y)def check_play_buttom(ai_settings,screen,stats,play_button,ship,aliens,bullets,mouse_x,mouse_y):'''响应鼠标按下Play按钮'''button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y) # 检查鼠标按下位置是否与Play按钮的rect重合if button_clicked and not stats.game_active: # 仅在按下Play按钮且游戏未激活时重置游戏# 隐藏光标pygame.mouse.set_visible(False)# 重置游戏信息stats.reset_stats()stats.game_active = True # 激活游戏# 清空外星人编组与子弹编组aliens.empty()bullets.empty()# 创建新的外星人群,将飞船居中create_fleet(ai_settings,screen,ship,aliens)ship.center_ship()def fire_bullet(ai_settings,screen,ship,bullets):'''发射子弹'''if len(bullets) < ai_settings.bullet_allowed:new_bullet = Bullet(ai_settings,screen,ship) # 创建一颗新子弹bullets.add(new_bullet) # 将新子弹存入编组bulllets中def update_bullets(ai_settings,screen,ship,aliens,bullets):'''更新子弹位置,并删除超出屏幕上边界的子弹'''# 更新子弹位置bullets.update()# 响应子弹与外星人的碰撞check_bullet_alien_collisions(ai_settings,screen,ship,aliens,bullets)# 删除超出屏幕上边界的子弹for bullet in bullets.copy():if bullet.rect.bottom <= 0:bullets.remove(bullet)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 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_xdef 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 create_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 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 check_fleet_edges(ai_settings,aliens):'''有外星人到达边缘时做出反应'''for alien in aliens.sprites():if alien.check_edges():change_fleet_direction(ai_settings,aliens) # 改变外星人横向移动方向breakdef change_fleet_direction(ai_settings,aliens):'''将外星人群下移,并改变横向移动方向'''for alien in aliens.sprites():alien.rect.y += ai_settings.fleet_drop_speedai_settings.fleet_direction *= -1def 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.ship_left > 0:# 将ship_left减1stats.ship_left -= 1# 清空外星人编组与子弹编组aliens.empty()bullets.empty()# 创建新的外星人群,并创建新的飞船放置在屏幕底部中央create_fleet(ai_settings,screen,ship,aliens)ship.center_ship()# 暂停sleep(0.5)else:stats.game_active = Falsedef 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)breakdef update_screen(ai_settings,screen,stats,ship,aliens,bullets,play_buttom):'''更新屏幕上的图像,并切换到新屏幕'''# 使用背景色填充屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites(): # 重绘所有子弹bullet.draw_bullet()ship.blitme() # 在背景上绘上飞船aliens.draw(screen) # 在背景上绘制所有外星人# 如果游戏处于非激活状态,则绘制Play按钮if not stats.game_active:play_buttom.draw_buttom()# 让最近绘制的屏幕可见pygame.display.flip() #
然后在主程序中更新相关函数
alien_invasion.py
import sys
import pygame
from settings import Settings
from game_stats import GameStats
from button import Button
from ship import Ship
from pygame.sprite import Group
import game_functions as gfdef run_game(): # 初始化游戏并创建一个屏幕对象pygame.init() # 初始化背景设置ai_settings = Settings()screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) #创建名为screen的显示窗口pygame.display.set_caption("Alien Invasion") # 创建一个用于储存游戏统计信息的实例stats = GameStats(ai_settings)#创建Play按钮play_button = Button(ai_settings,screen,"Play")# 创建一艘飞船ship = Ship(ai_settings,screen)# 创建一个子弹编组bullets = Group()# 创建一个外星人编组,并添加外星人aliens = Group()gf.create_fleet(ai_settings,screen,ship,aliens)# 开始游戏的主循环while True:# 监视键盘和鼠标事件gf.check_events(ai_settings,screen,stats,play_button,ship,aliens,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,stats,ship,aliens,bullets,play_buttom)run_game()
提高游戏难度
随着游戏的进程逐步提高游戏,具体体现为消灭外星人群后,逐步提高飞船,子弹,外星人的移动速度,而且保证每次重置游戏时,这些速度值也同时重置。首先修改设置类中的相关设置,加入移动速度的变化值。
settings.py
class Settings:'''存储所有设置'''def __init__(self):'''初始化游戏设置'''# 屏幕设置self.screen_width = 1200 # 窗口宽度为1200像素self.screen_height = 800 # 窗口高度为800像素self.bg_color = (230,230,230) # 创建名为bu_color的背景色 以RGB值为参数指定# 飞船设置self.ship_limit = 3 # 飞船个数限制# 子弹设置self.bullet_width = 3 # 子弹大小self.bullet_height = 15self.bullet_color = 60,60,60 # 子弹颜色self.bullet_allowed = 3 # 同屏最大子弹数# 外星人设置self.fleet_drop_speed = 10 # 外星人群向下移动速度self.speedup_scale = 1.1 # 加快游戏速度# 随游戏变化的设置self.initialize_dynamic_settings()def initialize_dynamic_settings(self):'''初始化随游戏进行而变化的设置'''self.ship_speed_factor = 1.5 # 飞船速度初始设置self.bullet_speed_factor = 3 # 子弹速度初始设置self.alien_speed_factor = 1 # 外星人速度初始设置self.fleet_direction = 1 # 外星人横向移动方向,1表示向右移,-1表示向左移def increase_speed(self):'''提高速度及外星人点数'''self.ship_speed_factor *= self.speedup_scaleself.bullet_speed_factor *= self.speedup_scaleself.alien_speed_factor *= self.speedup_scale
然后在game_functions方法中对检测击中外星人的函数进行更新
game_functions.py
import sys
from time import sleep
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 = Trueelif 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: # 按Q退出游戏sys.exit(0)def check_keyup_evets(event,ship):'''响应松开按键'''if event.key == pygame.K_RIGHT:ship.moving_right = Falseelif event.key == pygame.K_LEFT:ship.moving_left = False def check_events(ai_settings,screen,stats,play_button,ship,bullets):'''响应按键和鼠标事件'''for event in pygame.event.get():if event.type == pygame.QUIT: # 检测游戏窗口关闭按钮是否被点击sys.exit(0) # 退出游戏 不抛出异常退出elif event.type == pygame.KEYDOWN: # 按下按键check_keydown_events(event,ai_settings,screen,ship,bullets)elif event.type == pygame.KEYUP: # 松开按键check_keyup_evets(event,ship)elif event.type == pygame.MOUSEBUTTONDOWN: # 按下鼠标mouse_x,mouse_y = pygame.mouse.get_pos()check_play_buttom(stats,play_buttom,mouse_x,mouse_y)def check_play_buttom(stats,play_button,mouse_x,mouse_y):'''响应鼠标按下Play按钮'''if play_buttom.rect.collidepoint(mouse_x,mouse_y): # 检查鼠标按下位置是否与Play按钮的rect重合stats.game_active = Truedef fire_bullet(ai_settings,screen,ship,bullets):'''发射子弹'''if len(bullets) < ai_settings.bullet_allowed:new_bullet = Bullet(ai_settings,screen,ship) # 创建一颗新子弹bullets.add(new_bullet) # 将新子弹存入编组bulllets中def update_bullets(ai_settings,screen,ship,aliens,bullets):'''更新子弹位置,并删除超出屏幕上边界的子弹'''# 更新子弹位置bullets.update()# 响应子弹与外星人的碰撞check_bullet_alien_collisions(ai_settings,screen,ship,aliens,bullets)# 删除超出屏幕上边界的子弹for bullet in bullets.copy():if bullet.rect.bottom <= 0:bullets.remove(bullet)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()ai_settings.increase_speed() # 游戏加速create_fleet(ai_settings,screen,ship,aliens)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_xdef 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 create_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 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 check_fleet_edges(ai_settings,aliens):'''有外星人到达边缘时做出反应'''for alien in aliens.sprites():if alien.check_edges():change_fleet_direction(ai_settings,aliens) # 改变外星人横向移动方向breakdef change_fleet_direction(ai_settings,aliens):'''将外星人群下移,并改变横向移动方向'''for alien in aliens.sprites():alien.rect.y += ai_settings.fleet_drop_speedai_settings.fleet_direction *= -1def 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.ship_left > 0:# 将ship_left减1stats.ship_left -= 1# 清空外星人编组与子弹编组aliens.empty()bullets.empty()# 创建新的外星人群,并创建新的飞船放置在屏幕底部中央create_fleet(ai_settings,screen,ship,aliens)ship.center_ship()# 暂停sleep(0.5)else:stats.game_active = Falsedef 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)breakdef update_screen(ai_settings,screen,stats,ship,aliens,bullets,play_buttom):'''更新屏幕上的图像,并切换到新屏幕'''# 使用背景色填充屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites(): # 重绘所有子弹bullet.draw_bullet()ship.blitme() # 在背景上绘上飞船aliens.draw(screen) # 在背景上绘制所有外星人# 如果游戏处于非激活状态,则绘制Play按钮if not stats.game_active:play_buttom.draw_buttom()# 让最近绘制的屏幕可见pygame.display.flip() #
实现计分系统
希望于实现一个计分系统,实时跟踪玩家的得分,并在游戏窗口中显示。首先在game_stats模块中添加计分属性
game_stats.py
class GameStats():'''跟踪游戏的统计信息'''def __init__(self,ai_settings):'''初始化统计信息'''self.ai_settings = ai_settingsself.reset_stats()# 游戏启动时处于非激活状态self.game_active = Falsedef reset_stats(self):'''初始化游戏运行期间可能变化的统计信息'''self.ship_left = self.ai_settings.ship_limit # 飞船剩余数量self.score = 0 # 得分
创建一个ScoreBoard类用于储存关于得分板的信息与方法
import pygame.fontclass ScoreBoard():'''显示得分信息的类'''def __init__(self,ai_settings,screen,stats):'''初始化显示得分涉及的属性'''self.screen = screenself.screen_rect = screen.get_rect()self.ai_settings = ai_settingsself.stats = stats# 显示得分信息时使用的字体self.text_color = (30,30,30)self.font = pygame.font.SysFont(None,48)# 准备初始得分图像self.prep_score()def prep_score(self):'''将得分转化为渲染的图像'''rounded_score = int(round(self.stats.score,-1)) # 使显示的得分圆整score_str = "{:,}".format(rounded_score)self.score_image = self.font.render(score_str,True,self.text_color,self.ai_settings.bg_color)# 将得分放在屏幕右上角self.score_rect = self.score_image.get_rect()self.score_rect.right = self.screen_rect.rightself.score_rect.top = 20def show_score(self):'''在屏幕上显示得分'''self.screen.blit(self.score_image,self.score_rect)
在settings类中加入击中单个外星人得分,以及随着游戏难度增加,关于得分改变的值的函数
import sys
from time import sleep
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 = Trueelif 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: # 按Q退出游戏sys.exit(0)def check_keyup_events(event,ship):'''响应松开按键'''if event.key == pygame.K_RIGHT:ship.moving_right = Falseelif event.key == pygame.K_LEFT:ship.moving_left = False def check_events(ai_settings,screen,stats,play_button,ship,aliens,bullets):'''响应按键和鼠标事件'''for event in pygame.event.get():if event.type == pygame.QUIT: # 检测游戏窗口关闭按钮是否被点击sys.exit(0) # 退出游戏 不抛出异常退出elif event.type == pygame.KEYDOWN: # 按下按键check_keydown_events(event,ai_settings,screen,ship,bullets)elif event.type == pygame.KEYUP: # 松开按键check_keyup_events(event,ship)elif event.type == pygame.MOUSEBUTTONDOWN: # 按下鼠标mouse_x,mouse_y = pygame.mouse.get_pos()check_play_buttom(ai_settings,screen,stats,play_button,ship,aliens,bullets,mouse_x,mouse_y)def check_play_buttom(ai_settings,screen,stats,play_button,ship,aliens,bullets,mouse_x,mouse_y):'''响应鼠标按下Play按钮'''button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y) # 检查鼠标按下位置是否与Play按钮的rect重合if button_clicked and not stats.game_active: # 仅在按下Play按钮且游戏未激活时重置游戏# 隐藏光标pygame.mouse.set_visible(False)# 重置游戏信息stats.reset_stats()stats.game_active = True # 激活游戏# 清空外星人编组与子弹编组aliens.empty()bullets.empty()# 创建新的外星人群,将飞船居中create_fleet(ai_settings,screen,ship,aliens)ship.center_ship()def fire_bullet(ai_settings,screen,ship,bullets):'''发射子弹'''if len(bullets) < ai_settings.bullet_allowed:new_bullet = Bullet(ai_settings,screen,ship) # 创建一颗新子弹bullets.add(new_bullet) # 将新子弹存入编组bulllets中def update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets):'''更新子弹位置,并删除超出屏幕上边界的子弹'''# 更新子弹位置bullets.update()# 响应子弹与外星人的碰撞check_bullet_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,bullets)# 删除超出屏幕上边界的子弹for bullet in bullets.copy():if bullet.rect.bottom <= 0:bullets.remove(bullet)def check_bullet_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,bullets):'''响应子弹与外星人的碰撞'''# 检查是否有子弹击中外星人,并删除相应的子弹与外星人collisions = pygame.sprite.groupcollide(bullets,aliens,True, True)if collisions:for aliens in collisions.values(): # 确保击中每个外星人都得分stats.score += ai_settings.alien_points * len(aliens) # 加分sb.prep_score() # 渲染新的得分图像# 如果外星人全被击落,则删除现有子弹并新建外星人群if len(aliens) == 0:bullets.empty()ai_settings.increase_speed() # 游戏加速create_fleet(ai_settings,screen,ship,aliens)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_xdef 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 create_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 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 check_fleet_edges(ai_settings,aliens):'''有外星人到达边缘时做出反应'''for alien in aliens.sprites():if alien.check_edges():change_fleet_direction(ai_settings,aliens) # 改变外星人横向移动方向breakdef change_fleet_direction(ai_settings,aliens):'''将外星人群下移,并改变横向移动方向'''for alien in aliens.sprites():alien.rect.y += ai_settings.fleet_drop_speedai_settings.fleet_direction *= -1def 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.ship_left > 0:# 将ship_left减1stats.ship_left -= 1# 清空外星人编组与子弹编组aliens.empty()bullets.empty()# 创建新的外星人群,并创建新的飞船放置在屏幕底部中央create_fleet(ai_settings,screen,ship,aliens)ship.center_ship()# 暂停sleep(0.5)else:stats.game_active = Falsepygame.mouse.set_visible(True) # 显示光标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)breakdef update_screen(ai_settings,screen,stats,sb,ship,aliens,bullets,play_buttom):'''更新屏幕上的图像,并切换到新屏幕'''# 使用背景色填充屏幕screen.fill(ai_settings.bg_color)for bullet in bullets.sprites(): # 重绘所有子弹bullet.draw_bullet()ship.blitme() # 在背景上绘上飞船aliens.draw(screen) # 在背景上绘制所有外星人# 显示得分sb.show_score()# 如果游戏处于非激活状态,则绘制Play按钮if not stats.game_active:play_buttom.draw_buttom()# 让最近绘制的屏幕可见pygame.display.flip() #
最后在主程序中加入创建计分板的函数,并更新相关的函数
import sys
import pygame
from settings import Settings
from game_stats import GameStats
from scoreboard import ScoreBoard
from button import Button
from ship import Ship
from pygame.sprite import Group
import game_functions as gfdef run_game(): # 初始化游戏并创建一个屏幕对象pygame.init() # 初始化背景设置ai_settings = Settings()screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) #创建名为screen的显示窗口pygame.display.set_caption("Alien Invasion") # 创建一个用于储存游戏统计信息的实例stats = GameStats(ai_settings)# 创建Play按钮play_button = Button(ai_settings,screen,"Play")# 创建一个得分牌sb = ScoreBoard(ai_settings,screen,stats)# 创建一艘飞船ship = Ship(ai_settings,screen)# 创建一个子弹编组bullets = Group()# 创建一个外星人编组,并添加外星人aliens = Group()gf.create_fleet(ai_settings,screen,ship,aliens)# 开始游戏的主循环while True:# 监视键盘和鼠标事件gf.check_events(ai_settings,screen,stats,play_button,ship,aliens,bullets)if stats.game_active: # 游戏处于激活状态# 飞船更新位置(移动)ship.update()# 子弹更新位置,并删除超出屏幕上边界的子弹gf.update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets)# 更新外星人位置 gf.update_aliens(ai_settings,stats,screen,ship,aliens,bullets)# 更新屏幕gf.update_screen(ai_settings,screen,stats,sb,ship,aliens,bullets,play_button)run_game()
总结
pygame.mouse.set_visible(False)
set_visible(bool) -> bool
通过设置布尔值参数bool,函数将显示(True)或者隐藏(False)鼠标光标,并返回光标先前的显示状态
collisions = pygame.sprite.groupcollide(bullets,aliens,True,True)
for aliens in collisions.values():
groupcollide(group1, group2, dokill1, dokill2, collided = None) -> Sprite_dict
由之前关于groupcollide()函数的解析可知(可以看我之前的博客“#Python# Alien Invasion项目(五)”https://blog.csdn.net/weixin_45797443/article/details/107305440.),函数groupcollide()将返回一个由Sprite元素组成的字典,而参数group1中的Sprite元素将作为字典的key值,每个key值的value值是一个由于key值有重合部分的group2中的Sprite元素所组成的列表。而函数value()在Python3将返回一个迭代器,其中包含的元素分别是每个key值下的value值,在此处即为一个列表,所以使用变量values来作为遍历的变量,以提醒我们value并不是一个单个值,而是一个列表。这样的好处是可以防止出现一发子弹击中多个外星人后,程序仅计算一次得分的情况
rounded_score = int(round(self.stats.score,-1))
round(number[, ndigits])
函数round()将参数number进行四舍五入的化简圆整,参数ndigits设置化简的精度(小数点后位数),默认为0,当其值为负值时,将圆整到最近的10,100,1000等整数倍。需注意的是,因为float型变量在计算机内部存储的精度,以及函数在不同版本的调整的问题,有时函数给出的结果不一定是数学意义上的四舍五入结果,所以在对变量精度有特别要求的时候应避免使用该函数
score_str = "{:,}".format(rounded_score)
此处使用了一个字符串格式设置指令,将int型变量转化为str型时,在以千分位的方法插入‘,’分割符,使输出结果更便于阅读