Menu
CoddyTech

Skoru Tut

Coddy'nin Pygame Journey'sinin Oyun Döngüsü bölümünün bir parçası. Ders 27 / 32.

pygame'de metin, sözcüklerin bir görüntüsüdür. Bir pygame.font.Font, bir dizgeyi yüzeye dönüştürür ve bu yüzeyi screen.blit ile çizersin.

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'in yerleşik yazı tipidir ve yüksekliği 32 pikseldir. Döngüden önce, bir kez oluştur. render(text, True, color) sözcükleri çizer; True kenarlarını yumuşatır. blit(surface, (x, y)), görüntüyü sol üst köşesi (x, y) konumunda olacak şekilde ekrana kopyalar.

Metni döngünün içinde, dolgudan sonra oluştur. Skor değişir ve bir kez oluşturulan görüntü eski sayıyı göstermeye devam eder.

challenge icon

Görev

Kolay
  1. Döngüden önce font = pygame.font.Font(None, 32) ve score = 0 oluştur.
  2. Sepet bir bloğu yakaladığında score değerini 1 artır.
  3. Bloğu çizdikten sonra f"Score: {score}" ifadesini (240, 240, 240) renginde oluştur ve (10, 10) konumuna blit et.

Kendin dene

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

Oyun Döngüsü bölümündeki tüm dersler

Kendi başına pratik yap: Pygame playground