python-3.x 如何让pygame将一次鼠标点击识别为一次鼠标点击?

rsl1atfo  于 2023-01-14  发布在  Python
关注(0)|答案(1)|浏览(200)

问题是,当我在我的pygame游戏中点击箭头时,pygame将其识别为多次鼠标点击。
我尝试过的:
这样创建一个KeyDownListener类:

class KeyDownListener:
    def __init__(self):
        self.down = False
        self.is_up = False

    def update(self, key_pressed):
        if not key_pressed:
            self.is_up = True
            self.down = False
        else:
            if self.is_up:
                self.down = True
            else:
                self.down = False

            self.is_up = False

但那不起作用,因为当我点击箭头时什么也没发生。
我的Arrow类:

class Arrow(pygame.sprite.Sprite):
        default_imgresizer = pygame.transform.scale
        default_imgflipper = pygame.transform.flip

        def __init__(self, win, x, y, rotate=False):
            pygame.sprite.Sprite.__init__(self)

            self.win = win
            self.x = x
            self.y = y

            self.image = pygame.image.load("./arrow.png")
            self.image = self.default_imgresizer(self.image, [i // 4 for i in self.image.get_size()])

            if rotate:
                self.image = self.default_imgflipper(self.image, True, False)

            self.rect = self.image.get_rect(center=(self.x, self.y))

        def is_pressed(self):
            return pygame.mouse.get_pressed(3)[0] and self.rect.collidepoint(pygame.mouse.get_pos())

我的事件循环:

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

        screen.blit(computer_screen, (0, 0))

        current_profile.win.blit(current_profile.image, current_profile.rect)

        arrow_left.win.blit(arrow_left.image, arrow_left.rect)
        arrow_right.win.blit(arrow_right.image, arrow_right.rect)

        if arrow_right.is_pressed():
            with suppress(IndexError):
                current_profile_num += 1
                current_profile = profiles[current_profile_num]
        elif arrow_left.is_pressed():
            with suppress(IndexError):
                current_profile_num -= 1
                current_profile = profiles[current_profile_num]

        current_profile.increase_size()

        back_button.win.blit(back_button.image, back_button.rect)

        if back_button.is_pressed():
            return

        # boy.self_blit()

        pygame.display.update()
0vvn1miw

0vvn1miw1#

您必须使用MOUSEDOWN事件而不是pygame.mouse.get_pressed()。虽然pygame.mouse.get_pressed()返回按钮的当前状态,但MOUSEBUTTONDOWNMOUSEBUTTONUP仅在按下按钮时发生。

相关问题