记录分数
Coddy 用 Pygame 制作游戏 课程的第 13 课,共 41 课。
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)。
在循环内、填充屏幕后渲染文本。分数会变化,而只创建一次的图片会一直显示旧数字。
挑战
简单在屏幕上统计接住方块的次数。
- 在循环之前,创建
font = pygame.font.Font(None, 32)和score = 0。 - 篮子接住方块时,将
score加 1。 - 绘制方块后,将
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 制作游戏中的所有课
自己练习: Pygame 在线编辑器