How to center a text with Pygame

This is how you can center a text in pygame, the library to create games with python.

import pygame

pygame.init()
WIDTH = HEIGHT = 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
font = pygame.font.SysFont("Arial", 14)


def write(text, x, y, color="Coral",):
    text = font.render(text, 1, pygame.Color(color))
    text_rect = text.get_rect(center=(WIDTH//2, y))
    return text, text_rect

text, text_rect = write("Hello", 10, 10) # this will be centered anyhow, but at 10 height
loop = 1
while loop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            loop = 0
    screen.blit(text, text_rect)
    pygame.display.update()

pygame.quit()

Another example: Hello World

import pygame


pygame.init()

# THE MAIN SCREEN (surface)
WIDTH = HEIGHT = 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
font = pygame.font.SysFont("Arial", 128)
clock = pygame.time.Clock()

def write(text, x, y, color="Coral",):
    "returns a text on a surface with the position in a rect"
    text = font.render(text, 1, pygame.Color(color))
    text_rect = text.get_rect(center=(WIDTH//2, y))
    return text, text_rect

text, text_rect = write("Hello", 10, 70)
text2, text_rect2 = write("World", 10, 180)

loop = 1
while loop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            loop = 0
    screen.blit(text, text_rect)
    screen.blit(text2, text_rect2)
    pygame.display.update()
    clock.tick(60)

pygame.quit()

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.