브라우저에서 Pygame

Pygame 온라인

Pygame으로 게임을 만들고 브라우저에서 바로 플레이하세요. 진짜 pygame-ce라서 게임 창이 이 페이지에 열리고 키보드, 마우스, 소리가 모두 동작합니다. 평소 쓰던 while 루프와 clock.tick(60)도 asyncio 없이 그대로 돌아갑니다. 예제를 골라 실행하고 창을 클릭해서 플레이하세요.

Pygame 코드 온라인 실행

Ctrl+Enter로 프로그램을 실행합니다. 설명과 수정은 계정 없이 무료로 써 볼 수 있고, 더 쓰려면 로그인하세요.

재생 버튼이나 이 코드 실행을 누르면 여기서 게임이 열립니다. 키보드를 쓰려면 창을 클릭하세요.

고급 편집기에서 열까요?

고급 편집기(전체 Python 컴파일러)는 화면이 넓고, 파일을 저장하며, 이 코드를 바로 실행합니다. 아니면 여기서 전체 화면으로 계속하세요.

Pygame 게임 루프

Pygame 프로그램은 pygame.display.set_mode로 창을 연 뒤 같은 루프를 1초에 여러 번 반복합니다. 이벤트를 읽고, 게임을 갱신하고, 화면을 그려 pygame.display.flip()으로 보여 준 다음, clock.tick(60)으로 기다려서 게임이 초당 60프레임으로 돌아가게 합니다.

pygame.key.get_pressed()는 지금 눌려 있는 키를 알려 주므로 부드러운 움직임에 필요합니다. 여기서 True는 1로 계산되므로 keys[K_RIGHT] - keys[K_LEFT]는 1, -1, 0 중 하나가 됩니다.

move.py
이 코드 실행 →
move.py
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()

마우스와 소리를 쓰는 작은 게임

바구니는 MOUSEMOTION 이벤트를 따라 움직이고, 별은 pygame.Rect이며, colliderect가 잡았는지 판정합니다. "딩" 소리는 NumPy로 만들어 pygame.sndarray.make_sound로 소리로 바꾸기 때문에 파일이 필요 없습니다. 브라우저는 클릭한 뒤에만 소리를 내므로 먼저 창을 클릭하세요.

catch_the_stars.py
이 코드 실행 →
catch_the_stars.py
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()

50줄짜리 스네이크

뱀은 칸의 리스트입니다. 한 걸음마다 현재 방향으로 새 머리를 붙이고, 먹이를 먹은 때가 아니면 꼬리를 뗍니다. KEYDOWN 이벤트로 방향을 바꾸고(바로 뒤로는 못 돌아갑니다) clock.tick(10)으로 속도를 정합니다.

snake.py
이 코드 실행 →
snake.py
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)

Pygame에서 자주 하는 실수

1. 이벤트, flip(), tick()이 없는 루프

pygame.event.get()이 없으면 창이 응답하지 않고, pygame.display.flip()이 없으면 그린 것이 보이지 않으며, clock.tick()이 없으면 루프가 컴퓨터가 허락하는 만큼 빠르게 돕니다. 이 프로그램은 done, x = 360을 출력하지만 사각형은 한 번도 보여 주지 않습니다.

wrong.py
이 코드 실행 →
wrong.py
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)

세 단계를 모두 넣으면 사각형이 약 3초 동안 창을 가로질러 움직입니다.

right.py
이 코드 실행 →
right.py
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. 이미지와 소리 파일을 찾지 못함

pygame.image.load("player.png")는 프로그램 옆에서 파일을 찾습니다. Python 편집기에서는 먼저 파일을 작업 공간의 프로그램과 같은 폴더에 업로드하세요.

3. pygame.init() 전에 pygame.font로 글자 쓰기

pygame.font.SysFont를 pygame.init()보다 먼저 부르면 "font not initialized"로 실패합니다. 프로그램 맨 처음에 pygame.init()을 호출하세요.

Pygame이 브라우저에서 실행되는 방식

Python은 WebAssembly로 여러분의 기기에서 실행되고, pygame-ce는 canvas에 그림을 그리며 이 페이지는 그 canvas를 게임 창으로 보여 줍니다. 키보드와 마우스 이벤트는 Pygame으로 돌아가고, pygame.mixer는 브라우저를 통해 소리를 냅니다. Chrome, Edge, Firefox, Safari에서 동작합니다. 처음에는 Python과 Pygame을 다운로드하고, 그 뒤로는 캐시에서 불러옵니다.

파일, 이미지, 소리가 많은 큰 프로젝트는 Python 편집기를 쓰세요. 작업 공간이 저장되고 Pygame 게임도 그곳에서 창을 엽니다. turtle로 그림을 그리나요? Python turtle 온라인도 써 보세요.

자주 묻는 질문

Pygame을 온라인에서 어떻게 실행하나요?

이 페이지의 편집기에 Pygame 코드를 쓰거나 붙여넣고 실행하세요. 게임 창이 페이지에 열리면 클릭하고 키보드와 마우스로 플레이하면 됩니다. 설치할 것은 없습니다.

진짜 Pygame인가요?

네. pygame-ce(계속 관리되는 Pygame)를 브라우저용으로 빌드한 것이라서 그리기, 글꼴, Surface, Rect, 스프라이트, transform, 이미지 함수가 컴퓨터에서와 똑같이 동작합니다.

소리가 나나요?

네. pygame.mixer.Sound, Channel, pygame.mixer.music으로 WAV, OGG, MP3 파일과 pygame.sndarray로 만든 소리를 재생합니다. 브라우저는 클릭이나 키 입력 뒤에만 소리를 켜므로 먼저 실행 버튼이나 게임 창을 클릭하세요.

게임 루프를 바꿔야 하나요?

아니요. pygame.event.get(), pygame.display.flip(), clock.tick(60)을 쓰는 평범한 while 루프가 그대로 돌아갑니다. asyncio는 필요 없습니다.

어떤 브라우저에서 되나요?

Chrome, Edge, Firefox, Safari입니다. 모든 브라우저에서 키와 클릭이 게임에 전달되며, Chrome과 Edge가 가장 빠릅니다.

이미지와 글꼴을 쓸 수 있나요?

네. Python 편집기에서 이미지와 소리를 작업 공간에 업로드하고 이름으로 불러오세요. pygame.font.SysFont는 시스템 글꼴을 쓰므로 Arial, Segoe UI, 한국어, 중국어, 일본어 글꼴도 제대로 표시됩니다.