Skip to content

Instantly share code, notes, and snippets.

@guilledk
Created March 2, 2021 00:53
Show Gist options
  • Select an option

  • Save guilledk/7bfb3ac6cd64c6a933abccd548283508 to your computer and use it in GitHub Desktop.

Select an option

Save guilledk/7bfb3ac6cd64c6a933abccd548283508 to your computer and use it in GitHub Desktop.
Proof of concept for trio + pygame integration using trio guest mode
from queue import Queue, Empty
import trio
import pygame
from pygame import Rect
async def trio_main():
for x in range(4):
print('trio awake')
await trio.sleep(1)
def trio_done(outcome):
print(f'trio done {outcome}')
class AsyncPygame:
def __init__(
self,
async_main,
async_exit,
width,
height
):
pygame.init()
self.running = False
self.clock = pygame.time.Clock()
self.screen = pygame.display.set_mode((800, 600))
self._run_queue = Queue()
self.async_main = async_main
self.async_exit = async_exit
def schedule_fn(self, fn):
self._run_queue.put(fn)
def run(self):
trio.lowlevel.start_guest_run(
self.async_main,
run_sync_soon_threadsafe=self.schedule_fn,
done_callback=self.async_exit
)
x = 0
self.running = True
while self.running:
dt_ms = self.clock.tick()
dt = dt_ms / 1000.0
# run scheduled functions
while True:
try:
fn = self._run_queue.get(block=False)
fn()
except Empty:
break
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
self.screen.fill((0, 0, 0))
pygame.draw.rect(
self.screen,
(255,0,0),
Rect(x, 100, 10, 10)
)
x += 20 * dt
pygame.display.flip()
pygame.quit()
AsyncPygame(trio_main, trio_done, 800, 600).run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment