问题描述
如果您按住鼠标按钮,则表示您仍在点击。我想修复它,以便当您点击一次时,它会计数一次。
import pygame,sys,time
from pygame.locals import *
pygame.init()
ev = pygame.event.get()
clock = pygame.time.Clock()
w = 800
h = 600
Screendisplay = pygame.display.set_mode((w,h))
pygame.display.set_caption('Tap Simulator')
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
clock.tick(30)
handled = False
if pygame.mouse.get_pressed()[0] and not handled:
print("click!")
handled = pygame.mouse.get_pressed()[0]
pygame.display.flip()
解决方法
您必须使用 MOUSEBUTTONDOWN
事件而不是 pygame.mouse.get_pressed()
:
run = True
while run: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
run = False
if event.type == MOUSEBUTTONDOWN:
if event.button == 1: # 1 == left button
print("click!")
pygame.display.flip()
clock.tick(30)
pygame.quit()
sys.exit()
pygame.mouse.get_pressed()
返回一个布尔值列表,代表所有鼠标按钮的状态(True
或 False
)。只要按钮被按住,按钮的状态就是 True
。
MOUSEBUTTONDOWN
事件在您单击鼠标按钮时发生一次,而 MOUSEBUTTONUP
事件在鼠标按钮被释放时发生一次。pygame.event.Event()
对象有两个提供鼠标事件信息的属性。 pos
是一个存储被点击位置的元组。 button
存储被点击的按钮。每个鼠标按钮都关联一个值。例如,鼠标左键、鼠标中键、鼠标右键、鼠标滚轮向上和鼠标滚轮向下的属性值为1、2、3、4、5。当按下多个键时,会发生多个鼠标按钮事件。进一步的解释可以在模块 pygame.event
的文档中找到。
您无法明确检查鼠标点击,但可以检查鼠标按钮是否被按下 (event.type == pygame.MOUSEBUTTONDOWN
) 或释放 (event.type == pygame.MOUSEBUTTONUP
)。
click_count = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
click_count += 1
由于 event.type == pygame.MOUSEBUTTONUP
仅在释放鼠标按钮时计算为 True
,因此按住鼠标按钮不会增加 click_count
。