Pygame Online Compiler

Write, Run & Share Pygame code online using OneCompiler's Pygame online compiler for free. It's one of the robust, feature-rich online compilers for the Pygame library, running on Python 3.12. The game window your code creates is streamed live into the browser — no Python install, no SDL setup, no display server to configure. The editor shows sample boilerplate code when you choose language as Pygame and start coding.

About Pygame

Pygame is a Python wrapper around SDL (Simple DirectMedia Layer), the same C library that powers a huge swath of indie games, emulators, and 2D engines. It's been around since 2000 and is the most popular way for Python programmers to write games — and, just as often, the gentlest possible introduction to writing a game loop, handling input, drawing sprites, and playing sounds. If you've ever written a "for event in pygame.event.get()" loop, you know Pygame.

Adding dependencies

Pygame is pre-installed. To add anything else (numpy for procedural graphics, pillow for image processing…), open requirements.txt in the file tree and add one package per line — the first run installs them, subsequent runs are cached.

pygame
numpy
pillow

Syntax help

The game loop

Every Pygame program follows the same skeleton: initialise, create a window, then loop forever reading events, updating state, and redrawing the frame. clock.tick(60) caps the loop to 60 frames per second.

import pygame

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((30, 30, 40))      # clear the frame
    # … draw things here …
    pygame.display.flip()          # push the frame to the screen
    clock.tick(60)                 # cap to 60 fps

pygame.quit()

Drawing shapes

pygame.draw exposes primitives for rectangles, circles, lines, and polygons. Colours are (r, g, b) tuples with each channel 0–255.

import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))

WHITE = (255, 255, 255)
RED   = (220, 50, 50)
BLUE  = (50, 100, 220)

screen.fill(WHITE)
pygame.draw.rect(screen, RED, (50, 50, 120, 80))                # x, y, w, h
pygame.draw.circle(screen, BLUE, (250, 90), 40)                 # centre, radius
pygame.draw.line(screen, (0, 0, 0), (50, 200), (350, 200), 3)
pygame.draw.polygon(screen, (40, 180, 90), [(200, 220), (160, 280), (240, 280)])

pygame.display.flip()
pygame.time.wait(2000)
pygame.quit()

Movement and animation

Update positions each frame, redraw, flip. Use clock.tick(60) so motion is smooth and consistent.

import pygame
pygame.init()
W, H = 600, 400
screen = pygame.display.set_mode((W, H))
clock = pygame.time.Clock()

x, y, dx, dy, r = W // 2, H // 2, 4, 3, 24
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    x += dx
    y += dy
    if x - r < 0 or x + r > W: dx = -dx
    if y - r < 0 or y + r > H: dy = -dy

    screen.fill((20, 24, 40))
    pygame.draw.circle(screen, (233, 30, 99), (x, y), r)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Keyboard input

pygame.key.get_pressed() returns the current state of every key — perfect for movement, where you want continuous motion while a key is held. Use the event loop for one-shot actions like jumping or shooting.

import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()

x, y, speed = 300, 200, 5
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            print("Jump!")

    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

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, (0, 200, 0), (x, y, 40, 40))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Mouse input

Two patterns: poll pygame.mouse.get_pos() / get_pressed() every frame, or react to MOUSEBUTTONDOWN / MOUSEBUTTONUP / MOUSEMOTION events.

import pygame
pygame.init()
screen = pygame.display.set_mode((600, 400))
clock = pygame.time.Clock()

dots = []
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            dots.append(event.pos)

    screen.fill((255, 255, 255))
    for p in dots:
        pygame.draw.circle(screen, (255, 0, 0), p, 8)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Rendering text

Pygame has no built-in text widget — you render a string to a Surface with a Font, then blit that surface onto the screen.

import pygame
pygame.init()
screen = pygame.display.set_mode((400, 200))
font = pygame.font.SysFont("Arial", 36, bold=True)

text = font.render("Hello, Pygame!", True, (50, 50, 200))
rect = text.get_rect(center=(200, 100))

screen.fill((255, 255, 255))
screen.blit(text, rect)
pygame.display.flip()
pygame.time.wait(2000)
pygame.quit()

Sprites and groups

For anything bigger than a demo, structure objects as Sprite subclasses and put them in a Group. group.update() and group.draw(screen) handle the loop boilerplate for you.

import pygame
pygame.init()
W, H = 600, 400
screen = pygame.display.set_mode((W, H))
clock = pygame.time.Clock()

class Ball(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
        pygame.draw.circle(self.image, (255, 200, 0), (10, 10), 10)
        self.rect = self.image.get_rect(center=(x, y))
        self.dx, self.dy = 3, 2

    def update(self):
        self.rect.x += self.dx
        self.rect.y += self.dy
        if self.rect.left < 0 or self.rect.right  > W: self.dx = -self.dx
        if self.rect.top  < 0 or self.rect.bottom > H: self.dy = -self.dy

balls = pygame.sprite.Group(Ball(100, 100), Ball(300, 200), Ball(500, 80))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    balls.update()
    screen.fill((20, 20, 30))
    balls.draw(screen)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Collision detection

Rect collision is the simplest — most 2D games never need anything fancier. pygame.sprite.spritecollide does the same thing for sprite groups.

player = pygame.Rect(100, 100, 40, 40)
wall   = pygame.Rect(200, 100, 40, 40)

if player.colliderect(wall):
    print("Hit!")

# Sprite-vs-group collisions
# hit_list = pygame.sprite.spritecollide(player_sprite, enemy_group, dokill=True)