Issue
I am making a button in pygame where if I press down, something happens. This works, but only after I click the mouse about 5-10 times. It may be because I'm using the mouse on my computer and not an external mouse. Does anyone know how to fix this?
def button(x, y, width, height, ic, ac, action=None):
mouse = pygame.mouse.get_pos()
# print(mouse)
if x + width > mouse[0] > x and y + height > mouse[1] > y:
pygame.draw.rect(screen, ac, (x, y, width, height), 0)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and action is not None:
if action == 'play':
game_loop()
elif action == 'quit':
pygame.quit()
quit()
else:
pygame.draw.rect(screen, ic, (x, y, width, height), 0)
Solution
pygame.event.get()
gets all the messages from the event queue and remove them from the queue.
If you don't want to miss any message, then it is important to call pygame.event.get()
only once in the application loop.
Get the events in the main loop and pass the list of events to button()
, to solve the issue:
def button(events, x, y, width, height, ic, ac, action=None):
mouse = pygame.mouse.get_pos()
# print(mouse)
if x + width > mouse[0] > x and y + height > mouse[1] > y:
pygame.draw.rect(screen, ac, (x, y, width, height), 0)
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and action is not None:
if action == 'play':
game_loop()
elif action == 'quit':
pygame.quit()
quit()
else:
pygame.draw.rect(screen, ic, (x, y, width, height), 0)
while True:
events = pygame.event.get()
# [...]
button(events, .....)
# [...]
pygame.quit()
Answered By - Rabbid76
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.