当鼠标悬停在圆圈上时,圆圈不会改变颜色

时间:2020-04-09 05:34:45

标签: python math pygame

我正在尝试使用math.hypo(x1-x2)(y1-y2)检测鼠标坐标是否在圆上。在对一般问题进行了一些调试之后,我无法弄清楚它出了什么问题。我认为这是相关的代码。除了在codeacademy上花了几个小时的webdev之外,我对此还是全新的。对于任何奇怪的编码,我们深表歉意。

    # bubble and mouse stuff
orange = (255, 165, 0)
dark_orange = (255, 140, 0)
bubble_x = 300
bubble_y = 400
bubble_pos = (bubble_x, bubble_y)
bubble_rad = 100


def mouse_pos():
    for event in pygame.event.get():
        if event.type == pygame.MOUSEMOTION:
            mouse_coords = pygame.mouse.get_pos()
            print(mouse_coords)
            mouse_x = pygame.mouse.get_pos()[0]
            mouse_y = pygame.mouse.get_pos()[1]




def bubble():
    if event.type == pygame.MOUSEMOTION:
        mouse_x = pygame.mouse.get_pos()[0]
        mouse_y = pygame.mouse.get_pos()[1]
    else:
        mouse_x = 0
        mouse_y = 0
    bubble_color = dark_orange
    pygame.draw.circle(screen, bubble_color, bubble_pos, bubble_rad)
    distance = math.hypot(bubble_x - mouse_x, bubble_y - mouse_y)
    if distance >= bubble_rad:
        bubble_color = orange


# Game Loop
running = True
while running:
    screen.fill((255, 255, 255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                Kill_counter += 1
    GraveImg = pygame.transform.scale(GraveImg, (150, 150))
    grave()
    show_counter(Kill_counterX, Kill_counterY)
    mouse_pos()
    bubble()
    pygame.display.update()



1 个答案:

答案 0 :(得分:1)

在绘制圆之前,您必须更改bubble_color。此外,我建议通过pygame.mouse.get_pos()

获取当前鼠标位置
def bubble():
    mouse_x, mouse_y = pygame.mouse.get_pos()

    # set the current color
    bubble_color = dark_orange
    distance = math.hypot(bubble_x - mouse_x, bubble_y - mouse_y)
    if distance >= bubble_rad:
        bubble_color = orange

    # draw the circle with the current color 
    pygame.draw.circle(screen, bubble_color, bubble_pos, bubble_rad)

我强烈建议仅使用一个事件循环。在主应用程序循环中处理事件。请注意,pygame.event.get()从队列中删除事件,因此第一个事件循环将获取事件,但是第二个循环将丢失它们。
删除函数mouse_pos,它没有执行您期望的功能。