Fight Aliens 显示飞船生命/分数/游戏结束

发布时间 2023-03-31 17:06:23作者: 以赛亚

游戏的基本功能搞定,现在来实现一下我们比较关注的游戏中的生命值、武力值等等信息吧

1. 飞船生命值显示

# 显示飞船的生命
def show_ship_life(screen, gc):
    """
        显示飞船的生命
    :param screen:  屏幕对象
    :param gc: GameConfig 配置对象
    :return:
    """
    for i in range(gc.ship_life):
        ship = Ship(screen, gc)
        ship.rect.x = ship.rect.width * i
        ship.rect.y = 0
        ship.blit_ship()

2. 击中外星人获得分数/关卡升级显示

# 显示攻击得到分数 关卡
def show_total_score(screen, gc):
    """
        显示攻击得到分数
    :param screen: 屏幕对象
    :param gc: GameConfig 配置对象
    :return:
    """
    # 创建字体的对象
    font_obj = pygame.font.SysFont(None, 30)
    font_level_obj = pygame.font.SysFont(None, 50)
    # pygame.font.get_fonts() --> 获取系统中的字体名字
    # 使用字体对象,创建字体的图层
    font_sur = font_obj.render(str(gc.total_core) + ' $', True, (0, 0, 0))
    font_level_sur = font_level_obj.render("pass " + str(gc.total_level), True, (0, 0, 0))
    # 获取字体的矩形
    font_rect = font_sur.get_rect()
    font_level_rect = font_sur.get_rect()
    # 调整分数矩形在屏幕中的位置 -- 右上角
    font_rect.x = 730
    font_level_rect.x = 530
    font_rect.y = gc.height / 20
    font_level_rect.y = 0
    # 将字体显示在屏幕中
    screen.blit(font_sur, font_rect)
    screen.blit(font_level_sur, font_level_rect)

3. 游戏结束显示

# 检查游戏是否结束
def check_game_over(screen, gc):
    """
        检查游戏是否结束
    :param screen: 屏幕对象
    :param gc: GameConfig 配置对象
    :return:
    """
    if gc.ship_life < 0:
        # pygame.font.SysFont(name, size, bold=False, italic=False, constructor=None) -> Font
        # font.render(text, antialias, color, background=None) -> Surface
        # 创建字体的对象
        font_obj = pygame.font.SysFont(None, 100)

        # 使用字体对象,创建字体的图层
        font_sur = font_obj.render('GAME OVER', True, (255, 0, 0), (230, 230, 230))

        # 获取字体的矩形
        font_rect = font_sur.get_rect()
        # 调整字体矩形在屏幕中的位置 -- 居中
        font_rect.centerx = screen.get_rect().centerx
        font_rect.centery = screen.get_rect().centery

        # 将字体显示在屏幕中
        screen.blit(font_sur, font_rect)

        # 刷新屏幕
        pygame.display.flip()

        # 游戏结束时停止 显示4秒
        time.sleep(4)
        # 程序退出
        sys.exit()

至此项目结束,源码地址: