Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update set_timer patch #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 20 additions & 10 deletions platform_wasm/pygame/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,20 @@
THREADS = {}


def patch_set_timer(arg: Union[int, pygame.event.Event], millis: int, loops: int = 0):
"""Patches the pygame.time.set_timer function to use gthreads"""

def patch_set_timer(
event: Union[int, pygame.event.Event],
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated the args to match the pygame-ce api docs if that's okay with you @pmp-p 😄

millis: int,
loops: int = 0):
"""repeatedly create an event on the event queue

Patches the pygame.time.set_timer function to use gthreads
"""
dlay = float(millis) / 1000
if isinstance(arg, pygame.event.Event):
event = int(arg)
cevent = arg
if isinstance(event, pygame.event.Event):
event_type = event.type
cevent = event
else:
event = int(arg)
event_type = int(event)
cevent = pygame.event.Event(event)

event_loop = asyncio.get_event_loop()
Expand All @@ -81,7 +86,12 @@ async def fire_event(thread_uuid):
loop_counter = 0
while True:
await asyncio.sleep(dlay)
if event_loop.is_closed() or event not in THREADS or THREADS[event] != thread_uuid or (loops and loop_counter >= loops):
if (
event_loop.is_closed()
or event_type not in THREADS
or THREADS[event_type] != thread_uuid
or (loops and loop_counter >= loops)
):
break

pygame.event.post(cevent)
Expand All @@ -92,12 +102,12 @@ async def fire_event(thread_uuid):
# stale threads will be terminated
thread_uuid = uuid.uuid4()
Thread(target=fire_event, args=[thread_uuid]).start()
THREADS[event] = thread_uuid
THREADS[event_type] = thread_uuid

else:
# This cancels the timer for the event
if event in THREADS:
del THREADS[event]
del THREADS[event_type]


pygame.time.set_timer = patch_set_timer