За основу взял пост, в котором загружал шрифт, и сделал так, чтобы каждая нажатая буква появлялась внизу окна и поднималась вверх.
Рендеринг букв не стал выносить в метод класса, а оставил внутри main
, но для хранения данных о букве сделал датакласс Letter
.
import pygame as pg
from dataclasses import dataclass
from pygame import QUIT, KEYDOWN, K_ESCAPE
from pygame.font import Font
from pygame.math import Vector2
from pygame.surface import Surface
from pygame.time import Clock
from random import randint
WINDOW_SIZE = (800, 450)
BG_COLOR = (200, 200, 200)
SPEED = Vector2(0, -3)
FPS = 60
@dataclass()
class Letter:
position: Vector2
surface: Surface
def next_position(surf):
return Vector2(
randint(0, WINDOW_SIZE[0] - surf.get_width()),
WINDOW_SIZE[1] + surf.get_height()
)
def main():
pg.init()
surface = pg.display.set_mode(WINDOW_SIZE)
font = Font('Boxy-Bold.ttf', 24)
items = []
clock = Clock()
working = True
while working:
# Handle events
for e in pg.event.get():
if e.type == QUIT:
working = False
continue
if e.type != KEYDOWN:
continue
if e.key == K_ESCAPE:
working = False
char = e.unicode.strip()
if char:
surf = font.render(char, False, (50, 50, 50))
items.append(Letter(next_position(surf), surf))
# Update
for i in items:
i.position += SPEED
items = [i for i in items if i.position.y > -i.surface.get_height()]
# Render
surface.fill(BG_COLOR)
for i in items:
surface.blit(i.surface, i.position)
pg.display.update()
clock.tick(FPS)
pg.quit()
if __name__ == "__main__":
main()