八、計分,創建一個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)
點擊鏈接 https://blog.csdn.net/Ljt101222/article/details/81253914 進入 Python外星人入侵完整代碼和註釋(九)