Python外星人入侵完整程式碼和註釋(八)
阿新 • • 發佈:2019-01-09
八、計分,建立一個scoreboard.py的檔案
1、顯示分數,在螢幕上顯示最高分,等級和剩餘的飛船數,
在正上方顯示最高分,右上方顯示分數
2、建立記分牌,用於計算得到的分數
3、顯示等級。在外星人消滅後,提高等級
程式碼如下
import pygame.font from pygame.sprite import Group from ship import Ship class Scoreboard(): #顯示得分資訊的類 def __init__(self,ai_settings,screen,stats): #初始化顯示得分涉及的屬性 self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats #顯示得分資訊時使用的字型設定 self.text_color = (30,30,30) self.font = pygame.font.SysFont(None,48) #準備初始得分影象包含最高得分 self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def prep_score(self): #將得分轉化為一幅渲染的圖片 #round的第二個實參是將stats.score值整到10的整數倍 rounded_score = int(round(self.stats.score,-1)) #一個字串格式設定指令,在數值中插入逗號 score_str = "{:,}".format(rounded_score) #將字串傳遞給建立影象的render() 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.right -20 #上邊緣與螢幕相距20畫素 self.score_rect.top = 20 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.score_rect.top 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 def prep_ships(self): #顯示還剩餘多少艘飛船 self.ships = Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings,self.screen) ship .rect.x = 10 + ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship) 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) #繪製飛船 self.ships.draw(self.screen)