首页 > 解决方案 > 为什么我的点击不能在 pygame 中立即生效?

问题描述

我正在重建我的扫地机。

我的代码遍历 800 x 600 显示器上的每个正方形,每个正方形是 50 x 50,所以有 192 个正方形。我检查点击是否在每个方块中,并根据它是什么画一个炸弹或一个开放空间。

def check_for_click(x_click,  y_click, x_square, y_square, x_circle, y_circle, a_round, a_count):
    if x_click < x_square and y_click < y_square and x_click > (x_square - 50) and y_click > (y_square - 50):
        if grid[(a_round - 1)][(a_count)] == 1:
            bomb.play()
            choose = random.randint(0, 6)
            the_color = random.choice(light_colors[choose])
            make_square(the_color, (x_square - 50), (y_square - 50))
            the_color = random.choice(dark_colors[choose])
            make_circle(the_color, x_circle, y_circle)
            pygame.display.update()
        if grid[(a_round - 1)][(a_count)] == 0:
            the_grass.play()
            make_square(light_brown, (x_square - 50), (y_square - 50))
            pygame.display.update()
            grid[(a_round - 1)][(a_count)] = 2

上面的函数检查点击是否在某个正方形

word = True
while word:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            word = False
    
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            click = pygame.mouse.get_pos()
            check = True
            while check == True:
                round = 1
                count = 0
                the_x = 50
                the_y = 50
                cir_x = 25
                cir_y = 25
                x = click[0]
                y = click[1]
                for i in range(12):
                    for i in range(16):
                        check_for_click(x, y, the_x, the_y, cir_x, cir_y, round, count)
                        the_x = the_x + 50
                        cir_x = cir_x + 50
                        count = count + 1
                    the_y = the_y + 50
                    cir_y = cir_y + 50
                    the_x = 50
                    cir_x = 25
                    count = 0
                    round = round + 1
                check = False

上面是游戏循环,然后每次单击时它都会进入一个while循环并检查每个正方形位置以查看单击是否在其中

    update_score()
    draw_numbers()
    pygame.display.update()

pygame.quit()

以上是我编写的更多功能,但为简洁起见未包括在内。

标签: pythonpygamegame-development

解决方案


pygame.event.get()获取所有消息并将它们从队列中删除。请参阅文档:

这将获取所有消息并将它们从队列中删除。[...]

如果pygame.event.get()在多个事件循环中调用,则只有一个循环接收事件,但绝不会所有循环都接收所有事件。结果,似乎错过了一些事件。

只需调用pygame.event.get()一次:

word = True
    while word:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                word = False

        # for event in pygame.event.get(): <--- DELETE
        
            if event.type == pygame.MOUSEBUTTONDOWN:
                click = event.pos

                # [...]

推荐阅读