Another option to run pygame in a browser is to use pygbag. Install pygbag with pip install pygbag
pip install pygbag
Put the code in a file named main.py and adapt your pygame code like this:
import pygame
import asyncio
pygame.init()
# initializations: pygame.display.set_mode, ...
# [...]
def main():
run = True
while run:
# application loop: pygame.event.get(), pygame.display.flip(), ...
# [...]
await asyncio.sleep(0)
asyncio.run(main())
Build the project with the command:
pygbag .
Minimal example:
Live demo
import pygame
import asyncio
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5
async def main():
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
print(pygame.key.name(event.key))
keys = pygame.key.get_pressed()
rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel
rect.centerx = rect.centerx % window.get_width()
rect.centery = rect.centery % window.get_height()
window.fill(0)
pygame.draw.rect(window, "red", rect)
pygame.display.flip()
await asyncio.sleep(0)
pygame.quit()
exit()
asyncio.run(main())