《Python编程从入门到实践》(第14章.记分)

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等整数倍。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值