Continuously capture mouse events with pygame
I'm using pygame to build a simple game and have the following main loop,
where mouse() is a function to capture and process mouse events and
keyboard() for keyboard events:
def mainLoop():
pygame.event.pump()
keyboard(pygame.key.get_pressed())
events = pygame.event.get()
mouse(events)
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
return False
return True
When a player clicks on a tile I have the following function called by
mouse():
def objReach(obj, pos):
try:
path = obj.reach(pos, move=False) # A* (path-finding algorithm)
for step in path:
sleep(1.0/obj.speed)
objMove(obj, step)
except Exception as e:
sendMsg(str(e))
The problem is, while the object is walking the path (while the for loop
is running) mouse events don't get captured, so if the player clicks on
another tile in the middle of the way, nothing happens. I want the player
to be able to change paths.
I tried using mainLoop inside the for loop, but it was only partially
effective - it only captures the MOUSEBUTTONUP event, not both UP and DOWN
events, which are necessary to determine if the player is merely clicking
or dragging and dropping. Here's the mouse() function to clarify:
def mouse(events):
global clickPos
global releasePos
for event in events:
if event.type == MOUSEBUTTONDOWN:
clickPos = getPos(pygame.mouse.get_pos())
# getPos() transforms screen coordinates in game coordinates
elif event.type == MOUSEBUTTONUP:
releasePos = getPos(pygame.mouse.get_pos())
if event.button == MAIN_BUTTON:
# Simple click
if clickPos == releasePos:
if player.privilege > 1:
objMove(player, getPos(pygame.mouse.get_pos()))
else:
objReach(player, getPos(pygame.mouse.get_pos()))
# Drag and drop
else:
obj = player.place.matrix[clickPos[0]][clickPos[1]][-1]
objThrow(obj, clickPos, releasePos)
elif event.button == SECONDARY_BUTTON:
pass # TODO: ...
I'm not familiar with multithreading and I don't think it's supposed to be
used with pygame, but it was the only thing I could think of. Any ideas?
No comments:
Post a Comment