如何修复MOUSEMOTION和碰撞意外结果?

时间:2019-06-19 18:09:49

标签: python-3.x pygame

为了学习python和pygame,我正在做一个2D游戏。我制作了一个菜单,上面有2个按钮(PLAY和QUIT)。 PLAY按钮开始游戏,QUIT按钮退出游戏。

现在,我想在鼠标通过按钮时显示一个红色圆圈。我正在使用MOUSEMOTION和碰撞点。

代码正在运行,当我将鼠标移到按钮上时显示红色圆圈,但是当我将鼠标放在窗口的其他位置时,红色圆圈仍然保留。

def menu():

    global Font, Xplay, Xquit, Yplay, Yquit, X_rect_play, Y_rect_play, X_rect_quit, Y_rect_quit, done, QUIT1, pos_quit, BLACK, WHITE, RECT_QUIT, RECT_PLAY, pos_play
    pygame.font.init()

    circle_play = False
    circle_quit = False

    while not done:
        screen.fill(BLACK)      
        RECT_QUIT = pygame.draw.rect(screen, WHITE, (X_rect_quit,Y_rect_quit,250,50))
        RECT_PLAY = pygame.draw.rect(screen, WHITE, (X_rect_play, Y_rect_play,250,50))
        pos_play = (325,166)
        PLAY1 = Font.render("PLAY", True, BLACK)

        screen.blit(PLAY1,pos_play)
        screen.blit(QUIT1, pos_quit)

        if circle_play:
            pygame.draw.circle(screen, RED, (310,174), 13)
        if circle_quit:
            pygame.draw.circle(screen, RED, (310,274), 13)

        pygame.display.update()

        for event in pygame.event.get():

            if event.type == MOUSEMOTION:
                circle_play = RECT_PLAY.collidepoint(pygame.mouse.get_pos())
                circle_quit = RECT_QUIT.collidepoint(pygame.mouse.get_pos())

我希望在移动鼠标时会删除红色圆圈。

我该如何解决?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

只需移动在while循环内绘制按钮的代码,并确保每帧都清除屏幕即可。

要修复自动消失的圆,您需要创建一个变量来跟踪圆是否可见。

def menu():

    global Font, Xplay, Xquit, Yplay, Yquit, X_rect_play, Y_rect_play, X_rect_quit, Y_rect_quit, done, QUIT1, pos_quit
    circle_play = False  # will be true when circle on the play button will be visible
    circle_quit = False

    while not done:
        screen.fill(BLACK)
        RECT_PLAY = pygame.draw.rect(screen, WHITE, (X_rect_play, Y_rect_play,250,50))
        pos_play = (325,166)
        PLAY1 = Font.render("PLAY", True, BLACK)

        screen.blit(PLAY1,pos_play)
        screen.blit(QUIT1, pos_quit)

        if circle_play:
            pygame.draw.circle(screen, RED, (310,174), 13)
        if circle_quit:
            pygame.draw.circle(screen, RED, (310,274), 13)

        pygame.display.update()

        for event in pygame.event.get():

            if event.type == MOUSEMOTION:
                circle_play = RECT_PLAY.collidepoint(pygame.mouse.get_pos())
                circle_quit = RECT_QUIT.collidepoint(pygame.mouse.get_pos())
            ...