Pygame Online
Write and play Pygame games in your browser. This is real pygame-ce: the game window opens on this page, and the keyboard, mouse and sound work. Your usual while loop with clock.tick(60) runs as it is, no asyncio needed. Pick an example, select Run this code, then click the window to play.
Run Pygame code online
Press play or Run this code: the game opens here. Click it to use the keyboard.
The Pygame game loop
A Pygame program opens a window with pygame.display.set_mode and then repeats the same loop many times a second: read the events, update the game, draw the frame, show it with pygame.display.flip() and wait with clock.tick(60) so the game runs at 60 frames per second.
pygame.key.get_pressed() tells you which keys are held down right now, which is what smooth movement needs. In this example True counts as 1, so keys[K_RIGHT] - keys[K_LEFT] is 1, -1 or 0.
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 320))
pygame.display.set_caption("Move the square")
clock = pygame.time.Clock()
font = pygame.font.SysFont("arial", 20)
x, y = 220, 140
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 5
y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 5
x = max(0, min(440, x))
y = max(0, min(280, y))
screen.fill((25, 28, 45))
pygame.draw.rect(screen, (255, 200, 0), (x, y, 40, 40), border_radius=6)
screen.blit(font.render("Click here, then use the arrow keys", True, (220, 220, 220)), (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
A small game with the mouse and sound
The basket follows MOUSEMOTION events, stars are pygame.Rect objects and colliderect detects a catch. The "ding" is generated with NumPy and turned into a sound with pygame.sndarray.make_sound, so the example needs no files. Browsers only play sound after a click, so click the window first.
import random
import numpy as np
import pygame
pygame.mixer.pre_init(44100, -16, 2)
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the stars")
clock = pygame.time.Clock()
font = pygame.font.SysFont("arial", 22, bold=True)
# a short "ding" made with NumPy, no sound file needed
t = np.linspace(0, 0.12, int(44100 * 0.12), False)
tone = (np.sin(880 * 2 * np.pi * t) * np.exp(-t * 30) * 20000).astype(np.int16)
ding = pygame.sndarray.make_sound(np.column_stack([tone, tone]))
basket = pygame.Rect(200, 330, 80, 14)
stars = []
score = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEMOTION:
basket.centerx = event.pos[0]
if random.random() < 0.04:
stars.append(pygame.Rect(random.randint(10, 460), -10, 12, 12))
for star in stars[:]:
star.y += 4
if star.colliderect(basket):
stars.remove(star)
score += 1
ding.play()
elif star.y > 360:
stars.remove(star)
screen.fill((10, 10, 30))
for star in stars:
pygame.draw.circle(screen, (255, 230, 90), star.center, 6)
pygame.draw.rect(screen, (90, 200, 255), basket, border_radius=4)
screen.blit(font.render(f"Score: {score}", True, (255, 255, 255)), (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
Snake in 50 lines
The snake is a list of grid cells. Each tick adds a new head in the current direction and removes the tail unless it ate the food. KEYDOWN events change the direction (never straight back), and clock.tick(10) sets the speed.
import random
import pygame
pygame.init()
CELL, COLS, ROWS = 20, 24, 16
screen = pygame.display.set_mode((CELL * COLS, CELL * ROWS))
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()
font = pygame.font.SysFont("arial", 20)
snake = [(5, 8), (4, 8), (3, 8)]
direction = (1, 0)
food = (15, 8)
alive = True
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
raise SystemExit
if event.type == pygame.KEYDOWN:
turns = {pygame.K_UP: (0, -1), pygame.K_DOWN: (0, 1), pygame.K_LEFT: (-1, 0), pygame.K_RIGHT: (1, 0)}
new = turns.get(event.key)
if new and (new[0] != -direction[0] or new[1] != -direction[1]):
direction = new
if event.key == pygame.K_SPACE and not alive:
snake, direction, alive = [(5, 8), (4, 8), (3, 8)], (1, 0), True
if alive:
head = ((snake[0][0] + direction[0]) % COLS, (snake[0][1] + direction[1]) % ROWS)
if head in snake:
alive = False
else:
snake.insert(0, head)
if head == food:
food = (random.randrange(COLS), random.randrange(ROWS))
else:
snake.pop()
screen.fill((20, 24, 20))
pygame.draw.rect(screen, (230, 70, 70), (food[0] * CELL, food[1] * CELL, CELL, CELL))
for x, y in snake:
pygame.draw.rect(screen, (90, 220, 110), (x * CELL + 1, y * CELL + 1, CELL - 2, CELL - 2))
text = f"Length {len(snake)}" if alive else "Game over - press Space"
screen.blit(font.render(text, True, (255, 255, 255)), (8, 6))
pygame.display.flip()
clock.tick(10)
Common Pygame mistakes
1. A loop without events, flip() and tick()
Without pygame.event.get() the window stops responding, without pygame.display.flip() nothing you draw is shown, and without clock.tick() the loop runs as fast as the computer allows. This program prints done, x = 360 without ever showing the square:
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 240))
x = 0
# Wrong: no pygame.event.get(), no flip(), no tick()
# The window never shows the square and the program runs as fast as it can.
while x < 360:
x += 1
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 255, 0), (x, 100, 40, 40))
print("done, x =", x)
With the three steps the square slides across the window in about three seconds:
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 240))
clock = pygame.time.Clock()
x = 0
while x < 360:
for event in pygame.event.get(): # 1. read events (and QUIT)
if event.type == pygame.QUIT:
x = 360
x += 2
screen.fill((0, 0, 0))
pygame.draw.rect(screen, (255, 255, 0), (x, 100, 40, 40))
pygame.display.flip() # 2. show the frame
clock.tick(60) # 3. 60 frames per second
print("done, x =", x)
pygame.quit()
2. Image and sound files not found
pygame.image.load("player.png") looks for the file next to your program. In the Python editor, upload the file to your workspace first, in the same folder as the program.
3. Drawing text with pygame.font before pygame.init()
pygame.font.SysFont fails with "font not initialized" when it runs before pygame.init(). Call pygame.init() first, at the top of the program.
How Pygame runs in the browser
Python runs on your device with WebAssembly, and pygame-ce draws into a canvas that this page shows as the game window. Keyboard and mouse events from the window go back to Pygame, and pygame.mixer plays through the browser's audio. It works in Chrome, Edge, Firefox and Safari. The first run downloads Python and Pygame; after that they are cached.
For bigger projects with several files, images and sounds, use the Python editor: your workspace is saved, and Pygame programs open their game window there too. Drawing in turtle? Try Python turtle online.
Frequently asked questions
How do I run Pygame online?
Write or paste your Pygame code in the editor on this page and select Run this code. The game window opens in the page; click it, then use the keyboard and mouse to play. Nothing to install.
Is it real Pygame?
Yes. It is pygame-ce (the maintained Pygame fork) compiled for the browser, so drawing, fonts, Surface, Rect, sprites, transform and image functions behave as on your computer.
Does sound work?
Yes. pygame.mixer.Sound, Channel and pygame.mixer.music play WAV, OGG and MP3 files, and sounds you build with pygame.sndarray. Browsers start sound only after a click or key press, so click Run or the game window first.
Do I need to change my game loop?
No. A normal while loop with pygame.event.get(), pygame.display.flip() and clock.tick(60) runs as it is. You do not need asyncio.
Which browsers work?
Chrome, Edge, Firefox and Safari. Keys and clicks reach the game in all of them; Chrome and Edge are the fastest.
Can I use images and fonts?
Yes. Upload images and sounds to your workspace in the Python editor and load them by file name. pygame.font.SysFont uses your system's fonts, so Arial, Segoe UI and Chinese, Japanese or Korean fonts show correctly.
Related tools
- Tkinter Online Compiler: Run Tkinter GUI Code OnlineRun Python Tkinter code online and use the window right in your browser: buttons, entries, ttk, Canvas, dialogs and Matplotlib charts. No install, free.
- Python Turtle Online: Run Turtle Graphics in Your BrowserWrite Python turtle code and see the drawing right away, no install. forward, left, circle, colors, fills and more, with examples and PNG download.
- Run Python in the Browser: Online IDE with No InstallRun real Python in your browser with WebAssembly (Pyodide): NumPy, pandas and SciPy included, code runs on your device. How it works and its limits.