Menu
CoddyTech

记录分数

本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 30 课,共 35 课。

在 pygame 中,文本是一张由文字组成的图片。pygame.font.Font 会把字符串转换为一个表面,然后用 screen.blit 绘制这个表面。

font = pygame.font.Font(None, 32)

text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(text, (10, 10))

Font(None, 32) 是 pygame 内置的字体,高 32 像素。在循环开始前创建一次。render(text, True, color) 会绘制文字;True 会平滑文字边缘。blit(surface, (x, y)) 会把图片复制到屏幕上,并将图片左上角放在 (x, y) 处。

在循环内填充屏幕后再渲染文本。分数会变化,如果只创建一次图片,它就会一直显示旧的数字。

challenge icon

挑战

简单

统计屏幕上接住方块的次数。

  1. 在循环之前,创建 font = pygame.font.Font(None, 32) 和 score = 0。
  2. 当篮子接住方块时,将 score 加 1。
  3. 绘制方块后,将 f"Score: {score}" 渲染为 (240, 240, 240),并将其绘制在 (10, 10) 处。

按“运行”并接住一个方块:会显示 Score: 1。然后按“检查”。

亲手试试

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()

basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        basket.x -= 8
    if keys[pygame.K_RIGHT]:
        basket.x += 8
    basket.clamp_ip(screen.get_rect())

    block.y += 3
    if block.top > 360:
        block.y = -20
        block.x = random.randint(0, 460)
    if block.colliderect(basket):
        block.y = -20
        block.x = random.randint(0, 460)

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), basket)
    pygame.draw.rect(screen, (235, 80, 80), block)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

游戏循环中的所有课

自己练习: Pygame 在线编辑器