1

So I have defined a function Meteor and set up the dimensions and where it will appear on the screen.

def Meteor(Meteorx, Meteory, Meteorw, Meteorh, colour):
    pygame.draw.rect(Screen, colour, [Meteorx,Meteory, Meteorw, Meteorh])

but I wanted to add text to it but I can't work out how to blit it onto a rectangle (note: I have tried to play around with font.render etc). Am I going the right way about this or is there a simpler way than putting it onto the rect surface.

Source code https://github.com/WamblyTK/Word-Blaster/blob/master/Full%20Draft%20%231

1 Answers1

2

First you'll need a pygame.font, which can be created by pygame.font.SysFont() or pygame.font.Font. e.g.:

import pygame.font

font = pygame.font.SysFont('Times New Roman', 30)

With the font object a text can be rendered by .render(). The result is a pygame.Surface object.
If you want you can scale the surface to a certain size, by pygame.transform.smoothscale.
Finally the text can be drawn to the surface by blit. e.g.:

def Meteor(Meteorx, Meteory, Meteorw, Meteorh, colour):
    text = font.render('test text', False, colour)
    text = pygame.transform.smoothscale(text.convert(), (Meteorw, Meteorh))
    Screen.blit(text, (Meteorx, Meteory))

As mentioned in the comment below it is easier to use pygame.freetype. e.g.:

import pygame.freetype

font = pygame.freetype.SysFont('Times New Roman', 30)
def Meteor(Meteorx, Meteory, Meteorw, Meteorh, colour):
    font.render_to(Screen, (Meteorx, Meteory), 'test text', colour, size=Meteorw)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    Note there's also the [`pygame.freetype` module](https://www.pygame.org/docs/ref/freetype.html), which is an improved replacement for the `pygame.font` module. – sloth Mar 08 '19 at 14:40
  • I provided both solutions, using [`pygame.font`](https://www.pygame.org/docs/ref/font.html) or [`pygame.freetype`](https://www.pygame.org/docs/ref/freetype.html) – Rabbid76 Apr 26 '19 at 04:55