#Python# Alien Invasion项目(九)
- 实现余下飞船数的显示
- 总结
实现余下飞船数的显示
我们希望在窗口的左上角通过显示飞船图像来提示玩家剩余的飞船数量,其本质是在窗口右上角创建并显示与飞船剩余数量相同的飞船图像。
首先更新Ship类,使其继承Sprite类,以便于在之后显示飞船数量时同意对编组进行操作。
ship.py
import pygame
from pygame.sprite import Spriteclass Ship(Sprite):'''表示飞船的类'''def __init__(self,ai_settings,screen):'''初始化飞船并设置初始位置'''super().__init__()self.screen = screen self.ai_settings = ai_settings# 加载飞船图像并获取其外接矩形self.image = pygame.image.load(r'D:/Python学习/Alien Invasion/images/ship.bmp') # 设置飞船的图像 # 使用相对文件地址出错?self.rect = self.image.get_rect() # 获取飞船图像的外接矩形self.screen_rect = screen.get_rect() # 获取界面的外接矩形# 将每艘飞船放在屏幕底部中央self.rect.centerx = self.screen_rect.centerx # 将screen_rect的中心点的x坐标赋值给rect的中心点的x坐标self.rect.bottom = self.screen_rect.bottom # 将screen_rect的底部的y坐标赋给rect的底部的y坐标# 在飞船的属性center中存储小数值,centerx中只能存储整数值self.center = float(self.rect.centerx)# 移动标志self.moving_right = False # 移动默认为Falseself.moving_left = False def update(self):'''根据移动标志调整飞船的位置'''# 更新飞船的center值,而不是rectif self.moving_right and self.rect.right < self.screen_rect.right:self.center += self.ai_settings.ship_speed_factorif self.moving_left and self.rect.left > 0:self.center -= self.ai_settings.ship_speed_factor# 根据self.center更新rect对象self.rect.centerx = self.center # 取center值的整数部分保存,但对于显示来说区别不大def center_ship(self):'''让飞船在屏幕上居中'''self.center = self.screen_rect.centerxdef blitme(self):'''在制定位置绘制飞船'''self.screen.blit(self.image, self.rect) #
然后更新scoreboard模块,加入准备剩余飞船图像的函数
scoreboard.py
import pygame.font
from pygame.sprite import Group
from ship import Shipclass 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()self.perp_high_score()self.prep_level()self.prep_ships()def prep_ships(self):'''显示还余下多少艘飞船'''self.ships = Group() # 创建飞船编组for ship_number in range(self.stats.ship_left):ship = Ship(self.ai_settings,self.screen)ship.rect.x = 10 + ship_number * ship.rect.widthship.rect.y = 10self.ships.add(ship) # 将飞船加入编组def prep_level(self):'''将难度登记转化为渲染的图像'''self.level_image = self.font.render(str(self.stats.level),True,self.text_color,self.ai_settings.bg_color)# 将等级放在当前得分显示下方self.level_rect = self.level_image.get_rect()self.level_rect.right = self.screen_rect.rightself.level_rect.top = self.score_rect.bottom + 10def perp_high_score(self):'''将最高得分转化为渲染的图像'''high_score = int(round(self.stats.high_score,-1)) high_score_str = "{:,}".format(high_score)self.high_score_iamge = self.font.render(high_score_str,True,self.text_color,self.ai_settings.bg_color)# 将最高得分放在屏幕顶部中央self.high_score_rect = self.high_score_iamge.get_rect()self.high_score_rect.centerx = self.screen_rect.centerxself.score_rect.top = 20def 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)self.screen.blit(self.high_score_iamge,self.high_score_rect)self.screen.blit(self.level_image,self.level_rect)self.ships.draw(self.screen)
更新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_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,sb,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,sb,play_button,ship,aliens,bullets,mouse_x,mouse_y)def check_play_buttom(ai_settings,screen,stats,sb,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 # 激活游戏# 重置记分牌图表sb.prep_score()sb.perp_high_score()sb.prep_level()sb.prep_ships# 清空外星人编组与子弹编组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_high_score(stats,sb):'''检查是否产生新的最高得分'''if stats.score > stats.high_score:stats.high_score = stats.scoresb.perp_high_score()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() # 渲染新的得分图像check_high_score(stats,sb) # 检查是否产生新最高分# 如果外星人全被击落,则删除现有子弹并新建外星人群if len(aliens) == 0:bullets.empty()ai_settings.increase_speed() # 游戏加速stats.level += 1 # 提升难度等级sb.prep_level() # 更新难度等级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,sb,ship,aliens,bullets):'''更新所有外星人位置,并检测是否与飞船碰撞'''check_fleet_edges(ai_settings,aliens)aliens.update()# 检测外星人与飞船碰撞,并响应if pygame.sprite.spritecollideany(ship,aliens):ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets)# 检查外星人到达屏幕底部,并响应check_aliens_bottom(ai_settings,stats,screen,sb,ship,aliens,bullets)def ship_hit(ai_settings,stats,screen,sb,ship,aliens,bullets):'''响应外星人与飞船碰撞'''# 检测飞船剩余个数,判断游戏是否激活if stats.ship_left > 0:# 将ship_left减1stats.ship_left -= 1# 更新记分牌sb.prep_ships()# 清空外星人编组与子弹编组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,sb,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,sb,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() #
最后在主函数中更新相关函数
alien_invasion.py
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,sb,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,sb,ship,aliens,bullets)# 更新屏幕gf.update_screen(ai_settings,screen,stats,sb,ship,aliens,bullets,play_button)run_game()
总结
《Python编程——从入门到实践》中关于本项目的正文内容到此结束。通过本项目主要学习了pygame库的一系列应用,对于创建窗口,按钮的方法的学习,整个程序的分块,函数的重构以及对于类编组的学习尤为重要。后续会缓慢更新一些基于目前代码的新功能,如Help按钮的实现,通过文件保存最高分等