Пигмея поменять местами текст с другим текстом - PullRequest
1 голос
/ 31 марта 2020

Итак, у меня есть этот кусок кода:

import pygame

def colors():
    import random
    clock = pygame.time.Clock()
    pygame.init()
    pygame.font.init
    pygame.display.set_caption('Colors')
    SCREEN = width, height = 900,600
    screen = pygame.display.set_mode(SCREEN,0,32)
    particles = []
    running = True
    click = False
    while running:
        screen.fill((0,0,0))
        button_1 = pygame.Rect(width/2, (height/10), width/4, 60)
        button_1.centerx = width/2
        color = (255,255,255)
        pygame.draw.rect(screen, (135, 206, 235), button_1)
        text_speech('pixel.ttf', 30, 'Particle:', (255,255,255), (100), (300), False)
        color_t = 'White'
        font = pygame.font.Font('pixel.ttf', 30)



        text = font.render(color_t, True, color) 

        textRect = text.get_rect()  

        textRect.center = ((180), (300))


        screen.blit(text, textRect)
        text_speech('pixel.ttf', 50, 'Colors', (255,255,255), (button_1.centerx), (button_1.centery), False)
        particles.append([[150,200],[random.randint(0,20) / 10 - 1, 1], random.randint(4,6)])
        for particle in particles:
            particle[0][0] += particle[1][0]
            particle[0][1] += particle[1][1]
            particle[2] -= 0.1
            particle[1][1] += 0.03
            pygame.draw.circle(screen, color, [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
            if particle[2] <= 0:
                particles.remove(particle)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    running = False
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    click = True
        mx, my = pygame.mouse.get_pos()

        if textRect.collidepoint((mx,my)):
            if click:
                color_t = 'Red'
                color = (255,0,0)
                text_speech('pixel.ttf', 30, color_t, color, (180), (300), False)
        pygame.display.update()
        clock.tick(60)

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)
colors()

, и он производит это
[

Если Я нажимаю на текст, слово «красный» просто перекрывает слово «белый», а цвет круга не меняется. Мне было интересно, как сделать так, чтобы, если пользователь нажимает на текст, он заменяет предыдущее слово (в данном случае белое) новым словом (красным), а также меняет цвет круга

1 Ответ

0 голосов
/ 31 марта 2020

Создание функции, которая отображает текст, но не blit выводит его на поверхность окна:

def render_text_speech(fontname, size, text, color, x, y, bold):
    SCREEN = width, height = 900, 600
    font = pygame.font.Font(fontname, size)
    font.set_bold(bold)
    text = font.render(text, True, color)
    textRect = text.get_rect()
    textRect.center = (x,y)
    return text, textRect

Отображает текст перед основным приложением l oop и blit Текстовые поверхности непрерывно совпадают с поверхностью окна в l oop:

def colors():
    # [...]

    button_1 = pygame.Rect(width/2, (height/10), width/4, 60)
    button_1.centerx = width/2
    color = (255,255,255)
    color_t = 'White'
    text_particle = render_text_speech('pixel.ttf', 30, 'Particle:', (255,255,255), 100, 300, False)
    text_colors = render_text_speech('pixel.ttf', 50, 'Colors', (255,255,255), button_1.centerx, button_1.centery, False)
    text_color = render_text_speech('pixel.ttf', 30, color_t, color, 180, 300, False)

    # [...]
    while running:
        # [...]

        screen.blit(*text_particle)
        screen.blit(*text_colors)
        screen.blit(*text_color)

. При повторном нажатии текстовой мыши достаточно перерисовать текстовую поверхность:

def colors():
    # [...]

    while running:
        # [...]

        for event in pygame.event.get():
            # [...]

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and textRect.collidepoint(event.pos):
                    color_t = 'Red'
                    color = (255,0,0)
                    text_color = render_text_speech('pixel.ttf', 30, color_t, color, 180, 300, False)

См. Пример:

import pygame
import random

pygame.init()
pygame.font.init()
pygame.display.set_caption('Colors')
SCREEN = width, height = 900,600
screen = pygame.display.set_mode(SCREEN,0,32)

def render_text_speech(fontname, size, text, color, x, y, bold):
    SCREEN = width, height = 900, 600
    font = pygame.font.SysFont(None, size)
    #font = pygame.font.Font(fontname, size)
    font.set_bold(bold)
    text = font.render(text, True, color)
    textRect = text.get_rect()
    textRect.center = (x,y)
    return text, textRect

def colors():
    clock = pygame.time.Clock()

    button_1 = pygame.Rect(width/2, (height/10), width/4, 60)
    button_1.centerx = width/2
    colors = [("White", (255, 255, 255)), ("Red", (255, 0, 0)), ("Green", (0, 255, 0)), ("Blue", (0, 0, 255))]
    current_color = 0
    color_t, color = colors[current_color]
    text_particle = render_text_speech('pixel.ttf', 30, 'Particle:', (255,255,255), 100, 300, False)
    text_colors = render_text_speech('pixel.ttf', 50, 'Colors', (255,255,255), button_1.centerx, button_1.centery, False)
    text_color = render_text_speech('pixel.ttf', 30, color_t, color, 180, 300, False)

    particles = []
    running = True
    while running:
        screen.fill((0,0,0))

        pygame.draw.rect(screen, (135, 206, 235), button_1)
        screen.blit(*text_particle)
        screen.blit(*text_colors)
        screen.blit(*text_color)
        textRect = text_color[1]

        particles.append([[150,200],[random.randint(0,20) / 10 - 1, 1], random.randint(4,6)])
        for particle in particles:
            particle[0][0] += particle[1][0]
            particle[0][1] += particle[1][1]
            particle[2] -= 0.1
            particle[1][1] += 0.03
            pygame.draw.circle(screen, color, [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
            if particle[2] <= 0:
                particles.remove(particle)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and textRect.collidepoint(event.pos):
                    current_color += 1
                    if current_color >= len(colors):
                        current_color = 0
                    color_t, color = colors[current_color]
                    text_color = render_text_speech('pixel.ttf', 30, color_t, color, 180, 300, False)

        pygame.display.update()
        clock.tick(60)

colors()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...