微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的点击不能立即在 pygame 中工作?

如何解决为什么我的点击不能立即在 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,y_circle)
            pygame.display.update()
        if grid[(a_round - 1)][(a_count)] == 0:
            the_grass.play()
            make_square(light_brown,(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()

以上是我编写的更多函数,但为了简洁起见不包括在内。

解决方法

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

                # [...]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。