Как отобразить текст шрифтом и цветом с помощью pygame?
Есть ли способ отобразить текст в окне pygame с помощью python?
Мне нужно отобразить кучу оперативной информации, которая обновляется, и я предпочел бы не создавать изображение для каждого нужного мне символа.
Могу ли я вывести текст на экран?
Переведено автоматически
Ответ 1
ДА. В pygame можно рисовать текст:
# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' errormyfont = pygame.font.SysFont("monospace", 15)# render textlabel = myfont.render("Some text!", 1, (255,255,0))screen.blit(label, (100, 100))
Ответ 2
Вы можете использовать свои собственные шрифты, задав путь к шрифту с помощью pygame.font.Шрифт
pygame.font.Font(filename, size): return Font
пример:
pygame.font.init()font_path = "./fonts/newfont.ttf"font_size = 32fontObj = pygame.font.Font(font_path, font_size)
Затем отобразите шрифт с помощью fontObj.render и перенесите на поверхность, как в ответе вейсета выше. :)
Ответ 3
В моей игре есть некоторый код, который отображает текущий результат. Это функция для быстрого доступа.
def texts(score): font=pygame.font.Font(None,30) scoretext=font.render("Score:"+str(score), 1,(255,255,255)) screen.blit(scoretext, (500, 457))
и я вызываю его, используя это в моем цикле while:
texts(score)
Ответ 4
Есть 2 возможности. В любом случае PyGame должен быть инициализирован с помощью pygame.init.
pygame.init
import pygamepygame.init()
Используйте или pygame.font модуль и создайте pygame.font.SysFont или pygame.font.Font объект. render() a pygame.Surface с текстом и blit поверхностью на экране:
pygame.font
pygame.font.SysFont
pygame.font.Font
render()
pygame.Surface
blit
my_font = pygame.font.SysFont(None, 50)text_surface = myfont.render("Hello world!", True, (255, 0, 0))screen.blit(text_surface, (10, 10))
Или используйте pygame.freetype модуль. Создайте объект pygame.freetype.SysFont() or pygame.freetype.Font. render() a pygame.Surface с текстом или непосредственно render_to() вывод текста на экран:
pygame.freetype
pygame.freetype.SysFont()
pygame.freetype.Font
render_to()
my_ft_font = pygame.freetype.SysFont('Times New Roman', 50)my_ft_font.render_to(screen, (10, 10), "Hello world!", (255, 0, 0))
Смотрите также текст и шрифт
Минимальный pygame.font пример: repl.it/@Rabbid76/PyGame-Text
import pygamepygame.init()window = pygame.display.set_mode((500, 150))clock = pygame.time.Clock()font = pygame.font.SysFont(None, 100)text = font.render('Hello World', True, (255, 0, 0))background = pygame.Surface(window.get_size())ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]for rect, color in tiles: pygame.draw.rect(background, color, rect)run = Truewhile run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False window.blit(background, (0, 0)) window.blit(text, text.get_rect(center = window.get_rect().center)) pygame.display.flip()pygame.quit()exit()
Минимальный pygame.freetype пример: repl.it/@Rabbid76/PyGame-FreeTypeText
import pygameimport pygame.freetypepygame.init()window = pygame.display.set_mode((500, 150))clock = pygame.time.Clock()ft_font = pygame.freetype.SysFont('Times New Roman', 80)background = pygame.Surface(window.get_size())ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]for rect, color in tiles: pygame.draw.rect(background, color, rect)run = Truewhile run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False window.blit(background, (0, 0)) text_rect = ft_font.get_rect('Hello World') text_rect.center = window.get_rect().center ft_font.render_to(window, text_rect.topleft, 'Hello World', (255, 0, 0)) pygame.display.flip()pygame.quit()exit()