# GameStats类
class GameStats(): #用来设置游戏状态改变时的各属性
def __init__(self,ai_settings):
self.ai_settings=ai_settings #需要用到设置类对象
self.reset_stats()
self.game_active=False #设置标记False时游戏不能开始,True时可以开始游戏
self.high_score=0 #刚开始最高分为0
def reset_stats(self): #再点击play按钮后重设游戏各属性
self.ships_left=self.ai_settings.ship_limit #重设飞船数量为3艘
self.score=0 #重设分数为0
self.level=1 #重设游戏难度级别为1
# Scoreboard类设置分数,最高分,游戏级别,剩余飞船数量
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):
rounded_score=int(round(self.stats.score,-1)) #round()函数和第二个实参-1将分数设置成10的整数倍
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.right-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.screen_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.screen_rect.right
self.level_rect.top=self.screen_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) #编组中元素的绘制与其余图像的绘制不同
外星人入侵Gamestats类,Scoreboard类
最新推荐文章于 2023-04-09 22:14:27 发布