Python Application Chapter Alien Invasion Project - Scoring (End)

foreword

  The last article introduced the implementation of some functions of the last function score in the "Alien Invasion" project; including displaying the score, creating a scoreboard, updating the score when the aliens are eliminated, and each alien that will be eliminated. The points are counted into the score and the final increase of points and rounding of the score, etc. This article introduces the implementation of other remaining functions of scoring. We first introduce the implementation of the highest scoring function.

1. Highest score

  Every player wants to beat the game's highest score record. Here's to track and display the top score, giving the player a target to beat. We store the highest score GameStatsin:

    def __init__(self, ai_settings):
        """初始化統計信息"""
        self.ai_settings = ai_settings
        self.reset_stats()
        # 遊戲剛啟動時處於非活動狀態
        self.game_active = False
        # 在任何情况下都不应该重置最高得分
        self.high_score = 0

  Given that the top score is never reset under any circumstances, we initialize __init__()in instead of in . Beginners should pay special attention to this.   Next modified to show the highest score. First let's modify the method :reset_stats()high_score
Scoreboard__init__()

    def __init__(self, ai_settings, screen, stats):
        """Initialize scorekeeping attributes."""
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.ai_settings = ai_settings
        self.stats = stats

        # Font settings for scoring information.
        self.text_color = (30, 30, 30)
        self.font = pygame.font.SysFont(None, 48)
        # 准备初始得分图像
        self.prep_score()
        self.prep_high_score()

  The highest score will be displayed separately from the current score, so we need to write a new method prep_high_score()that prepares the image containing the highest score. The code for the method prep_high_score()is as follows:

    def prep_high_score(self):
        """将最高得分转换为渲染的图像"""
        high_score = int(round(self.stats.high_score, -1))
        high_score_str = "{:,}".format(high_score)
        self.high_score_image = self.font.render(high_score_str, True,
                                                 self.text_color, self.ai_settings.bg_color)
        # 将最高分放在屏幕顶部中央
        self.high_score_rect = self.high_score_image.get_rect()
        self.high_score_rect.centerx = self.screen_rect.centerx
        self.high_score_rect.top = self.high_score_rect.top

  We rounded the highest score to the nearest multiple of 10 and added a comma-denoted thousandth separator. Then, we generate an image based on the highest score, center it horizontally, and set its top property to the top property of the current scoring image.
  Now, the method show_score()needs to display the current score in the upper right corner of the screen and the highest score in the top center of the screen:

    def show_score(self):
        """在屏幕上显示得分"""
        self.screen.blit(self.score_image, self.score_rect)
        self.screen.blit(self.high_score_image, self.high_score_rect)

  To check if a new top score has been created, we game_funcations.pyadd a new function to check_high_score():

def check_high_score(stats, sb):
    """检查元素是否诞生了新的最高得分"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        sb.prep_high_score()

  The function check_high_score()contains two formal parameters: statsand sb. It is used statsto compare the current score with the highest score, and sbto retouch the highest score image if necessary. We compare the current score with the highest score, update the value if the current score is higher, high_scoreand call prep_high_score()to update the image containing the highest score.
  in the function check_bullet_alien_collisions(). Whenever an alien is destroyed, it needs to be called after updating the score check_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
            sb.prep_score()
        check_high_score(stats, sb)
    if len(aliens) == 0:
        bullets.empty()
        ai_settings.increase_speed()
        create_fleet(ai_settings, screen, ship, aliens)

  When the dictionary collisionsexists, we update the score based on how many aliens have been eliminated, in the call check_high_score().
  When playing the game for the first time, the current score is the highest score, so both displays show the current score. But when you start the game again, the highest score appears in the center, and the current score appears on the right, as shown in the image below:

2. Display level

  In order to display the player's level in the game, you first need GameStatsto add an attribute that represents the current level in the game. To ensure the level is reset every time you start a new game reset_stats(), :

    def reset_stats(self):
        """初始化在遊戲運行期間可能變化的統計信息"""
        self.ships_left = self.ai_settings.ship_limit
        self.score = 0
        self.level = 1

  To Scoreboardbe able to display the current level below the score, we __init__()call a new method inprep_level()

    def __init__(self, ai_settings, screen, stats):
        """Initialize scorekeeping attributes."""
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.ai_settings = ai_settings
        self.stats = stats

        # Font settings for scoring information.
        self.text_color = (30, 30, 30)
        self.font = pygame.font.SysFont(None, 48)
        # 准备初始得分图像
        self.prep_score()
        self.prep_high_score()
        self.prep_level()

  The specific prep_level()implementation is as follows:

    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.score_rect.right
        self.level_rect.top = self.score_rect.bottom + 10

  method creates an image from the values prep_level()​​stored in and sets its properties to the properties of the score . Then, set the top property to be 10 pixels larger than the bottom property of the score image to allow some space between the score and the rank. We also need to update :stats.levelrightrightshow_score()

    def show_score(self):
        """在屏幕上显示得分"""
        self.screen.blit(self.score_image, self.score_rect)
        self.screen.blit(self.high_score_image, self.high_score_rect)
        self.screen.blit(self.level_image, self.level_rect)

  In this method, a line of code is added to display the grade image on the screen. We check_bullet_alien_collisions()raise the rank in and update the rank image:

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
            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)

  If the entire group of aliens is wiped out, we stats.levelincrement the value of 1 and call prep_level()to make sure the new level is displayed correctly and correctly.
  To ensure that the score and level images are updated when starting a new game, a reset is triggered when the button play is clicked:

def check_play_button(ai_settings, screen, stats, sb, play_button, ship,
                      aliens, bullets,  mouse_x, mouse_y):
    """在玩家单击play按钮时开始新游戏"""
    button_checked = play_button.rect.collidepoint(mouse_x, mouse_y)
    if button_checked and not stats.game_active:
        # 重置游戏设置
        ai_settings.initialize_dymaic_settings()
        # 隐藏光标
        pygame.mouse.set_visible(False)
        # 重置游戏统计信息
        stats.reset_stats()
        stats.game_active = True
        # 重置记分牌图像
        sb.prep_score()
        sb.prep_high_score()
        sb.prep_level()
        # 清空外星人列表和子弹列表
        aliens.empty()
        bullets.empty()
        # 创建一群新的外星人,并让飞船居中
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

  check_play_button()The definition of needs to contain the object sb. To reset the scoreboard image, we call prep_score(), prep_high_score()and , after resetting the relevant game settings prep_level().
  In check_events(), now you need to check_play_button()pass sb to give it access to the scorecard object:

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()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings, screen,stats, sb,
                              play_button, ship, aliens, bullets,
                              mouse_x, mouse_y)
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)

  check_events()The definition of needs to contain formal parameters sbso that check_play_buttom()when called, it can be sbpassed as an actual parameter.
  Finally, the code alien_invasion.pycalled in the update check_events(), also pass it sb:

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("Alian Invasion")
    # 创建play按钮
    play_button = Button(ai_settings, screen, "Play")
    # 創建一個用于存儲遊戲統計信息的實例
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # 创建一艘飞船、一个子弹编组和一个外星人编组
    ship = Ship(ai_settings, screen)
    # 创建一组一个用于存储子弹的编组
    bullets = Group()
    aliens = Group()
    # 创建外星人群
    # alien = Alien(ai_settings, screen)
    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, ship, aliens, bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens,
                         bullets, play_button)
run_game()

  Now we run the game, we can know how many levels we can upgrade, the specific effect is as follows:

  Here we need to pay attention to: in some classic games, the score is labeled, eg score、High Score和Level. We didn't show these tabs because once you start playing the game you will see at a glance what each number means. To include these tags, simply add them to the score string before Scoreboardcalling in .   Readers have read so much, the functions should be almost understood, and they should have a clear understanding of this game. Finally a homework for you:font.render()
Just ask the reader to realize显示余下的飞船数. The implementation of this function is similar to the previous one, except that you have to consider adding the spaceship to the spaceship group and add it to the group socreboard.py. Finally game_function.py, sb has to be added in the middle. Don't forget to add parameters to the alien_invasion.pylieutenant at the end . The last function of the whole project is left to everyone to realize. There are many answers on the Internet, but I still hope to realize it by myself. I have learned so much. I will test how I have learned in practice. Come on, everyone! ! ! !update_alien()sb

Summarize

  The last article introduced the implementation of some functions of the last function score in the "Alien Invasion" project; including displaying the score, creating a scoreboard, updating the score when the aliens are eliminated, and each alien that will be eliminated. The points are counted into the score and the final increase of points and rounding of the score, etc. This article introduces the implementation of other remaining functions of scoring, mainly including the highest score and display level. In the end, I left a small assignment for everyone, which is to let everyone realize the display of the remaining number of spaceships. This project is coming to an end here. Nearly a dozen articles will introduce you to the realization of each function of this project step by step. The next article will give a brief summary of the entire project of "Alien Invasion" and the complete code of the entire project, but I still hope that everyone can follow these articles step by step, so that you will be solid, and you will realize it step by step. It is very helpful for you to have a clear understanding of the framework of the entire project after understanding every function of the project. But if you simply paste the copied code, it won't help at all.
  In fact, this project is already very typical, the code is everywhere, but if you simply paste and copy, it will not have any value for your knowledge learning, you still have to follow it again, and then you need to know the meaning of each line of code or use When it comes to the knowledge point we introduced earlier, only in this way will this project play a different value. I hope everyone will study hard and solidify the basic knowledge. Python is a practical language, it is the simplest of many programming languages, and it is also the best to get started. When you have learned the language, it is relatively simple to learn java, go and C. Of course, Python is also a popular language, which is very helpful for the realization of artificial intelligence. Therefore, it is worth your time to learn. Life is endless and struggle is endless. We work hard every day, study hard, and constantly improve our ability. I believe that we will learn something. come on! ! !

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324131059&siteId=291194637