-
-
Save pmp-p/fb25df0c8beb84d5c771c1875d7594bd to your computer and use it in GitHub Desktop.
use aio green thread for pygame.time.set_timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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