Skip to content

Instantly share code, notes, and snippets.

@pmp-p
Last active June 6, 2022 19:29
Show Gist options
  • Save pmp-p/fb25df0c8beb84d5c771c1875d7594bd to your computer and use it in GitHub Desktop.
Save pmp-p/fb25df0c8beb84d5c771c1875d7594bd to your computer and use it in GitHub Desktop.
use aio green thread for pygame.time.set_timer
import asyncio
import itertools
import pygame
import aio.gthread
from threading import Thread
def patch_set_timer(cust_event_no, millis, loops=0):
dlay = float(millis) / 1000
cevent = pygame.event.Event(cust_event_no)
async def fire_event():
while not aio.exit:
await asyncio.sleep( dlay )
pygame.event.post(cevent)
Thread(target=fire_event).start()
pygame.time.set_timer = patch_set_timer
WIDTH, HEIGHT = 500, 400
FPS = 60
COLOR_CHANGE_EVENT = pygame.event.custom_type()
COLOR_CYCLE = itertools.cycle(pygame.color.THECOLORS.keys())
async def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
pygame.time.set_timer(COLOR_CHANGE_EVENT, 500, 0)
bg_color = next(COLOR_CYCLE)
running = True
while running:
clock.tick(FPS)
screen.fill(bg_color)
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
running = False
if event.type == COLOR_CHANGE_EVENT:
bg_color = next(COLOR_CYCLE)
pygame.display.flip()
await asyncio.sleep(0)
def run():
asyncio.run(main())
if __name__ == "__main__":
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment