Menu
CoddyTech

Keep Score

Part of the The Game Loop section of Coddy's Pygame journey. Lesson 27 of 32.

Text in pygame is a picture of the words. A pygame.font.Font turns a string into a surface, and you draw that surface with 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) is pygame's built-in font, 32 pixels high. Make it once, before the loop. render(text, True, color) draws the words; True smooths their edges. blit(surface, (x, y)) copies the picture onto the screen with its top left corner at (x, y).

Render the text inside the loop, after the fill. The score changes, and a picture made once keeps showing the old number.

challenge icon

Challenge

Easy
  1. Before the loop, make font = pygame.font.Font(None, 32) and score = 0.
  2. Add 1 to score when the basket catches a block.
  3. After drawing the block, render f"Score: {score}" in (240, 240, 240) and blit it at (10, 10).

Try it yourself

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()

All lessons in The Game Loop

Practice on your own: Pygame playground