1.将文本渲染到屏幕上 P258
import pygame.font
class Button():
def __init__(self, ai_settings, screen, msg):
--snip--
# Set the dimensions and properties of the button.
--snip--
#渲染文本到屏幕上。实参None让Pygame使用默认字体,48为字体号。
self.font = pygame.font.SysFont(None, 48)
#创建按钮对象
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.rect.center = self.screen_rect.center
# The button message only needs to be prepped once.
self.prep_msg(msg)
def prep_msg(self, msg):
"""将msg渲染为图像,并使其在按钮上居中"""
#将存储在msg中的文本转换为图像,然后将该图像存储在msg_image中。布尔实参指定是否开启反锯齿功能
self.msg_image = self.font.render(msg, True, self.text_color,
self.button_color)
#让文本图像在按钮上居中
self.msg_image_rect = self.msg_image.get_rect()
self.msg_image_rect.center = self.rect.center
2.开始游戏 P261
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()
--snip--
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)
def check_play_button(ai_settings, screen, stats, sb, play_button, ship,
aliens, bullets, mouse_x, mouse_y):
"""在玩家单击Play按钮时开始新游戏"""
button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) #检测单击鼠标时,其位置是否在Play按钮处。如果是button_clicked为True.
3.隐藏光标 P263
pygame.mouse.set_visible(False)
4.将得分圆整 P272
round(score,-1)
函数round()通常让小数精确到小数点后多少位,其中小数位数是由第二个实参指定的。然而,如果将第二个实参指定为负数,round()将圆整到最近的10、100、1000等整数倍。