Как сделать функцию активированной, когда над областью, оставаться активным за пределами области ограничения - PullRequest
0 голосов
/ 18 февраля 2019

Я пишу код для приложения рисования и хочу иметь несколько кистей.Единственная проблема сейчас заключается в том, что с этим кодом кисть работает нормально, но работает только тогда, когда курсор находится над реальной иконкой.Вот код:

def paintScreen():
    intro = True
    gameDisplay.fill(cyan)
    message_to_screen('Welcome to PyPaint', black, -300, 'large')
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        pygame.draw.rect(gameDisplay, white, (50, 120, displayWidth - 100, displayHeight - 240))

        button('X', 20, 20, 50, 50, red, lightRed, action = 'quit')
        icon(airbrushIcon, white, 50, displayHeight - 101, 51, 51, white, grey, 'airbrush')
        pygame.display.update()

def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, action = None):
        cur = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()
        if x + width > cur[0] > x and y + height > cur[1] > y:#if the cursor is over the button
            pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))
            gameDisplay.blit(icon, (x, y))
            if click[0] == 1 and action != None:
                if action == 'quit':
                    pygame.quit()
                    quit()
                if action == 'pencil':
                    pencil()
                if action == 'airbrush':
                    airbrush()
                if action == 'calligraphy':
                    calligraphy()
                if action == 'erase':
                    pencil()
        else:
            pygame.draw.rect(gameDisplay, inactiveColour, (x, y, width, height))
            gameDisplay.blit(icon, (x, y))

def airbrush(brushSize = 3):
    airbrush = True
    cur = pygame.mouse.get_pos() #cur[0] is x location, cur[1] is y location
    click = pygame.mouse.get_pressed()
    if click[0] == True:
        if cur[0] > 50 < displayWidth - 50 and cur[1] > 120 < displayHeight - 120:
            #the area of the canvas is x(50, width-50) y(120, width-120)
            pygame.draw.circle(gameDisplay, black, (cur[0] + random.randrange(brushSize), cur[1] + random.randrange(brushSize)), random.randrange(1, 5))
        clock.tick(60)

Я понимаю, что проблема в том, что функция вызывается только тогда, когда курсор находится над значком, но я не знаю, куда перемещать операторы действия или какизмени их.

1 Ответ

0 голосов
/ 18 февраля 2019

Вы хотите сделать так, чтобы, когда пользователь нажимает на иконку с краской, устанавливалась переменная.Поэтому вместо:

def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, action = None):
        cur = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()
        if x + width > cur[0] > x and y + height > cur[1] > y:#if the cursor is over the button
            pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))
            gameDisplay.blit(icon, (x, y))
            if click[0] == 1 and action != None:
                if action == 'quit':
                    pygame.quit()
                    quit()
                if action == 'pencil':
                    pencil()
                if action == 'airbrush':
                    airbrush()
                if action == 'calligraphy':
                    calligraphy()
                if action == 'erase':
                    pencil()
        else:
            pygame.draw.rect(gameDisplay, inactiveColour, (x, y, width, height))
            gameDisplay.blit(icon, (x, y))

Вы можете изменить этот код так, чтобы просто включать и выключать рисование для:

def icon(icon, colour, x, y, width, height, inactiveColour, activeColour, paint_on, action = None):
        cur = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()
        if x + width > cur[0] > x and y + height > cur[1] > y and click[0] == 1: # if the cursor is over the button and they clicked
            if paint_on == True:
                paint_on = False
            else:
                paint_on = True
            return paint_on

Очевидно, что в вашем случае, поскольку у вас есть несколько инструментов, вам придется создатьразличные переключатели для каждого инструмента внутри этой функции, но я пытаюсь сделать его простым и показать пример только для одного инструмента рисования.

Теперь, когда у вас есть переключатель, который изменит переменную "paint_on" нащелкнув по значку, вы можете проверить обычный щелчок мыши

def regular_click(colour, x, y, width, height, inactiveColour, activeColour, action = None):
    cur = pygame.mouse.get_pos()
    click = pygame.get_pressed()
    if cur[1] > y and click[0] == 1 and paint_on == True: # if cursor is beneath the tool bar (I'm assuming your tool bar is at the top)
        pygame.draw.rect(gameDisplay, activeColour, (x, y, width, height))

Затем добавьте эту функцию в свой основной цикл while True:

def paintScreen():
    intro = True
    gameDisplay.fill(cyan)
    message_to_screen('Welcome to PyPaint', black, -300, 'large')
    paint_on = False
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        pygame.draw.rect(gameDisplay, white, (50, 120, displayWidth - 100, displayHeight - 240))

        button('X', 20, 20, 50, 50, red, lightRed, action = 'quit')
        paint_on = icon(airbrushIcon, white, 50, displayHeight - 101, 51, 51, white, grey, paint_on, 'airbrush')
        regular_click(paint_on)
        pygame.display.update()

Так что весь этот код работает какследует:

После того, как пользователь щелкнет по значку, он изменит переменную «paint_on» на противоположную (так, если она выключена или выключена, если включен), затем, когда они щелкают в любом месте, проверяет, включена ли эта переменная, иесли курсор не находится на панели инструментов, и если оба они выполнены, то он рисует.

Вот как вы это сделаете.Я не могу гарантировать, что этот код работает так, как я сам никогда не использовал pygame, но я знаю, что это лучший способ сделать это, если только нет встроенной функции.

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