Gustavo
Gustavo

Reputation: 23

How to display text?

Hey I want to have Pygame print out text on the screen, I did try to make it but I have some weird bugs with it and I cant figure out what's wrong. Here is my code

    def write(text):
        for j in range(h):

            for j in range(w):

                for char in text:

                    if char.lower() == "a":

                        screen.blit(a, (k, l))
                    self.k += 10

                self.l += 11
    write("aaaaaaaa")

I would appreciate if anyone could point out my mistakes and/or suggest the proper way to do this.

Upvotes: 2

Views: 8888

Answers (2)

Franck Dernoncourt
Franck Dernoncourt

Reputation: 83177

Here is one way:

import pygame, pygame.font, pygame.event, pygame.draw, string
from pygame.locals import *

def display_box(screen, message):
    fontobject=pygame.font.SysFont('Arial', 18)
    if len(message) != 0:
        screen.blit(fontobject.render(message, 1, (255, 255, 255)),
                ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10))
    pygame.display.flip()

def get_key():
    while True:
        event = pygame.event.poll()
        if event.type == KEYDOWN:
            return event.key

if __name__ == "__main__":
    # Graphics initialization
    full_screen = False    
    window_size = (1024, 768)
    pygame.init()      
    if full_screen:
        surf = pygame.display.set_mode(window_size, HWSURFACE | FULLSCREEN | DOUBLEBUF)
    else:
        surf = pygame.display.set_mode(window_size)

    # Create a display box
    while True:
        display_box(surf, "hello world")
        inkey = get_key()
        if inkey == K_RETURN or inkey == K_KP_ENTER:
            break
        pygame.display.flip()

Upvotes: 2

dani herrera
dani herrera

Reputation: 51665

Take a look to this sample at Very simple Pong game:

font = pygame.font.SysFont("calibri",40)
...
score1 = font.render(str(bar1_score), True,(255,255,255))
...
screen.blit(score1,(250.,210.))

Upvotes: 1

Related Questions