Как добавить текстовую речь в Pygame - PullRequest
2 голосов
/ 02 апреля 2020

Итак, у меня есть эта функция, которая перетаскивает текст на экран:

def text_speech(font : str ,size : int,text : str,color,x,y, bold : bool):
    SCREEN = width, height = 900, 600
    font = pygame.font.Font(font,size)
    font.set_bold(bold)
    text = font.render(text, True, color)
    textRect = text.get_rect()
    textRect.center = (x,y)
    screen.blit(text,textRect)

Если у меня есть

screen.fill((0,0,0))
text_speech('arialnarrow.ttf', 30, 'Hello', (255,255,255),  
            width/2, height/2, False)

Она печатает «Hello» на черном экране с белым текстом. Если игрок наводит курсор на этот текст, как я могу создать текстовый пузырь, который выглядит следующим образом:

this

Я просто хочу, чтобы текст имел зеленый фон с надписью «Нажмите, чтобы подтвердить». Кто-нибудь знает, как это сделать. Прошу прощения, я немного новичок в Pygame.

1 Ответ

4 голосов
/ 02 апреля 2020

4-й параметр font.render - это необязательный цвет фона текста:

color = (255, 255, 255)
background = (0, 255, 0)
text = font.render(text, True, color, background)

Другой вариант - визуализация текста на поверхности и преобразование формата поверхности в формат альфа-формат пикселя (convert_alpha):

textSurf = font.render(text, True, color).convert_alpha()
textSize = textSurf.get_size()

Создайте новую поверхность с двойным размером:

bubbleSurf = pygame.Surface((textSize[0]*2., textSize[1]*2))
bubbleRect = bubbleSurf.get_rect()

Заполните поверхность цветом фона пузыря:

bubbleSurf.fill(background)

Перетаскивание текста на поверхность пузыря:

bubbleSurf.blit(textSurf, textSurf.get_rect(center = bubbleRect.center))

Переливание поверхности пузыря на screen:

bubbleRect.center = (x,y)
screen.blit(bubbleSurf, bubbleRect)

Полная функция text_speech:

def text_speech(font : str ,size : int,text : str,color,background,x,y, bold : bool):
    SCREEN = width, height = 900, 600
    font = pygame.font.Font(font,size)
    font.set_bold(bold)
    textSurf = font.render(text, True, color).convert_alpha()
    textSize = textSurf.get_size()   
    bubbleSurf = pygame.Surface((textSize[0]*2., textSize[1]*2))
    bubbleRect = bubbleSurf.get_rect()
    bubbleSurf.fill(background)
    bubbleSurf.blit(textSurf, textSurf.get_rect(center = bubbleRect.center))
    bubbleRect.center = (x,y)
    screen.blit(bubbleSurf, bubbleRect)
text_speech('arialnarrow.ttf', 30, 'Hello', (255,255,255), (0,128,0), 
            width/2, height/2, False)

См. Пример:

import pygame
import pygame.font

pygame.init()

width, height = 400, 300
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
textRect = pygame.Rect(0, 0, 0, 0)

def text_speech(font : str, size : int, text : str,color,background,x,y, bold : bool, bubble: bool):
    global textRect
    font = pygame.font.SysFont(None, 40) 
    #font = pygame.font.Font(font,size)
    font.set_bold(bold)
    textSurf = font.render(text, True, color).convert_alpha()
    if bubble:
        textSize = textSurf.get_size()   
        bubbleSurf = pygame.Surface((textSize[0]*2., textSize[1]*2))
        textRect = bubbleSurf.get_rect()
        bubbleSurf.fill(background)
        bubbleSurf.blit(textSurf, textSurf.get_rect(center = textRect.center))
        textRect.center = (x,y)
        screen.blit(bubbleSurf, textRect)
    else:
        textRect = textSurf.get_rect()
        textRect.center = (x,y)
        screen.blit(textSurf, textRect)


run = True
while run:
    clock.tick(60)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    hover = textRect.collidepoint(pygame.mouse.get_pos())

    screen.fill((0,0,0))
    text_speech('arialnarrow.ttf', 30, 'Hello', (255,255,255), (0, 128, 0), 
        (width/2), (height/2), False, hover)
    pygame.display.flip()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...