Today we are going to see how to display a text on the screen with pygame and how to animate it. We will also see:
- how to adapt the window to the screen size of the monitor with pygame.display.Info()
import pygame import time class Color: green = (0, 255, 0) class Font: ''' definition of type of fonts ''' pygame.font.init() little = pygame.font.SysFont("Arial", 48) big = pygame.font.SysFont("Arial", 192) class Text: ''' definition of text with rendering method ''' def text_render(font, text, color): text = font.render(text, 1, color) return text def show_text(enter=None): def animate(text, pos): width1 = text.get_size()[0] for n in range(width1): screen.fill(0) screen.blit(text, (-width1 + n, pos)) clock.tick(360) pygame.display.update() def pause(): for n in range(100): screen.blit(Text.hello, (0, 0)) screen.blit(Text.world, (0, 200)) pygame.display.update() if enter == None: screen.blit(Text.hello, (0, 0)) screen.blit(Text.world, (0, 200)) elif enter == "from_left": # width1 = Text.hello.get_size()[0] width2 = Text.world.get_size()[0] animate(Text.hello, 0) animate(Text.world, 200) pause() hello = text_render(Font.big, "Hello", Color.green) world = text_render(Font.little, "World", Color.green) def monitor_size(): ''' return width and height of the monitor screen ''' info = pygame.display.Info() return info.current_w, info.current_h def mainloop(): ''' main loop to show stuff on the screen ''' while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() Text.show_text(enter="from_left") # clock.tick(60) pygame.display.update() pygame.init() w, h = monitor_size() screen = pygame.display.set_mode((w - 100, h - 100), pygame.RESIZABLE) clock = pygame.time.Clock() mainloop()
Another example
import pygame def start_window(): pygame.init() GREEN = (0, 255, 0) # Text font = pygame.font.SysFont("Arial", 192) welcome = font.render("Pygame is great", 1, (GREEN)) tw, th = welcome.get_size() # size of the text surface # Screen info = pygame.display.Info() # width and height w, h = info.current_w, info.current_h print(w, h) screen = pygame.display.set_mode((tw, th)) clock = pygame.time.Clock() rx = 0 forward = 1 while True: screen.fill(0) for event in pygame.event.get(): if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() if rx < tw and forward == 1: rx += 10 screen.blit(welcome, (-tw + rx, 0)) if rx == tw -1: forward = 0 elif forward == 0: rx -= 10 screen.blit(welcome, (-tw + rx, 0)) if rx == 0: forward = 1 clock.tick(60) pygame.display.update() return screen start_window()