如何使pygame将鼠标单击识别为鼠标单击



问题是,当我在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()

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

最新更新