Una fuente desde un archivo
Parte de la sección Reglas del juego del Journey de Pygame de Coddy. Lección 6 de 29.
pygame.font.Font(None, 32) usa la fuente integrada de pygame. Se lee bien, pero todos los juegos de pygame que la usan tienen el mismo aspecto. Un archivo de fuente le da letras propias a tu juego.
El paquete de recursos incluye cuatro en assets/fonts/. Pasa la ruta del archivo en lugar de None:
font = pygame.font.Font("assets/fonts/pixel.ttf", 24)
big_font = pygame.font.Font("assets/fonts/pixel.ttf", 48)El número es el tamaño en píxeles. Cada objeto Font tiene un solo tamaño, así que necesitas dos objetos para mostrar un título y una puntuación con tamaños diferentes. Créelos una sola vez, antes del bucle: cargar una fuente implica leer el archivo, lo que es demasiado lento para hacerlo en cada fotograma.
La ruta es relativa a la carpeta de main.py. Una ruta incorrecta detiene el programa con FileNotFoundError e indica el archivo que buscaba.
Cada fuente dibuja con su propio tamaño: pixel.ttf en tamaño 24 tiene aproximadamente la misma altura que la fuente integrada en tamaño 32, así que compara a ojo y ajusta.
Desafío
Fácil- Haz que
fontsea el archivoassets/fonts/pixel.ttfcon tamaño 24. - Añade
big_font, el mismo archivo con tamaño 48. - Dibuja
Meteor DodgeyGame overconbig_font.
Pruébalo tú mismo
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Meteor Dodge")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
WHITE = (240, 240, 240)
def reset():
global player, rock, score
player = pygame.Rect(220, 300, 40, 40)
rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
score = 0
def draw_menu():
screen.fill((30, 30, 46))
title = font.render("Meteor Dodge", True, WHITE)
screen.blit(title, title.get_rect(center=(240, 140)))
hint = font.render("Press Enter to play", True, WHITE)
screen.blit(hint, hint.get_rect(center=(240, 200)))
def draw_game():
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (255, 196, 0), player)
pygame.draw.rect(screen, (235, 80, 80), rock)
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
def play_frame():
global score, state
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= 6
if keys[pygame.K_RIGHT]:
player.x += 6
player.clamp_ip(screen.get_rect())
rock.y += 4
if rock.top > 360:
rock.y = -24
rock.x = random.randint(0, 456)
score += 1
if rock.colliderect(player):
state = "over"
draw_game()
def draw_over():
draw_game()
message = font.render("Game over", True, WHITE)
screen.blit(message, message.get_rect(center=(240, 160)))
hint = font.render("Press R to play again", True, WHITE)
screen.blit(hint, hint.get_rect(center=(240, 200)))
reset()
state = "menu"
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN and state == "menu":
state = "play"
elif event.key == pygame.K_r and state == "over":
reset()
state = "play"
if state == "menu":
draw_menu()
elif state == "play":
play_frame()
else:
draw_over()
pygame.display.flip()
clock.tick(60)
pygame.quit()
Todas las lecciones de Reglas del juego
Practica por tu cuenta: Playground de Pygame