Pygame Web IDE
Loading Environment...
Download
Pop Out
Clear Console
Stop
Run Code
main.py
import asyncio import pygame # 1. Initialize Pygame pygame.init() # 2. Set up the display screen = pygame.display.set_mode((400, 400)) pygame.display.set_caption("Web Pygame") # Colors BLACK = (20, 20, 25) BLUE = (50, 150, 255) async def main(): """ In the browser, we MUST use an async main function and await asyncio.sleep(0) inside the loop. """ clock = pygame.time.Clock() x, y = 200, 200 speed = 5 running = True print("Game Loop Started! Click on the canvas and use Arrow Keys.") while running: # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Movement logic keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: x -= speed if keys[pygame.K_RIGHT]: x += speed if keys[pygame.K_UP]: y -= speed if keys[pygame.K_DOWN]: y += speed # Keep circle inside bounds x = max(20, min(380, x)) y = max(20, min(380, y)) # Rendering screen.fill(BLACK) pygame.draw.circle(screen, BLUE, (x, y), 20) # Update display pygame.display.flip() # 3. CRITICAL: Yield control to the browser! await asyncio.sleep(0) # Cap frame rate clock.tick(60) pygame.quit() # 4. Start the async loop asyncio.ensure_future(main())
Console Output