Menu
CoddyTech

Catat Skor

Termasuk bagian Perulangan Game dalam perjalanan Pygame di Coddy. Pelajaran 27 dari 32.

Teks di pygame adalah gambar dari kata-kata. pygame.font.Font mengubah string menjadi surface, lalu kamu menggambar surface itu dengan 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) adalah font bawaan pygame, dengan tinggi 32 piksel. Buat font sekali, sebelum perulangan. render(text, True, color) menggambar kata-katanya; True menghaluskan tepinya. blit(surface, (x, y)) menyalin gambar ke layar dengan sudut kiri atasnya di (x, y).

Render teks di dalam perulangan, setelah pengisian. Skor berubah, dan gambar yang dibuat sekali akan terus menampilkan angka lama.

challenge icon

Tantangan

Mudah
  1. Sebelum perulangan, buat font = pygame.font.Font(None, 32) dan score = 0.
  2. Tambahkan 1 ke score saat keranjang menangkap blok.
  3. Setelah menggambar blok, render f"Score: {score}" dengan (240, 240, 240) dan blit di (10, 10).

Coba sendiri

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

Semua pelajaran di Perulangan Game

Latihan sendiri: Playground Pygame