Pygame ในเบราว์เซอร์

Pygame ออนไลน์

สร้างเกมด้วย Pygame แล้วเล่นในเบราว์เซอร์ได้เลย นี่คือ pygame-ce ตัวจริง หน้าต่างเกมเปิดในหน้านี้ และคีย์บอร์ด เมาส์ และเสียงใช้ได้ทั้งหมด ลูป while ปกติของคุณกับ clock.tick(60) รันได้ตามเดิมโดยไม่ต้องใช้ asyncio เลือกตัวอย่าง รัน แล้วคลิกในหน้าต่างเพื่อเล่น

รันโค้ด Pygame ออนไลน์

กด Ctrl+Enter เพื่อรันโปรแกรม ลองใช้ อธิบาย และ แก้โค้ด ได้ฟรีโดยไม่ต้องมีบัญชี เข้าสู่ระบบ เพื่อใช้ได้มากขึ้น

กดเล่นหรือ รันโค้ดนี้ แล้วเกมจะเปิดที่นี่ คลิกในหน้าต่างเพื่อใช้คีย์บอร์ด

เปิดในตัวแก้ไขขั้นสูงไหม?

ตัวแก้ไขขั้นสูง (คอมไพเลอร์ Python เต็มรูปแบบ) มีพื้นที่มากกว่า บันทึกไฟล์ของคุณ และรันโค้ดนี้ทันที หรือจะใช้ต่อที่นี่แบบเต็มจอก็ได้

ลูปเกมของ Pygame

โปรแกรม Pygame เปิดหน้าต่างด้วย pygame.display.set_mode แล้ววนลูปเดิมหลายครั้งต่อวินาที คืออ่านเหตุการณ์ อัปเดตเกม วาดเฟรม แสดงด้วย 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)

เมื่อมีครบทั้งสามขั้นตอน สี่เหลี่ยมจะเคลื่อนข้ามหน้าต่างในราวสามวินาที

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.font ก่อน pygame.init()

pygame.font.SysFont จะล้มเหลวด้วย "font not initialized" ถ้าเรียกก่อน pygame.init() ให้เรียก pygame.init() เป็นอย่างแรกตอนเริ่มโปรแกรม

Pygame ทำงานในเบราว์เซอร์อย่างไร

Python ทำงานบนอุปกรณ์ของคุณด้วย WebAssembly และ pygame-ce วาดลงใน 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 เบราว์เซอร์จะเปิดเสียงหลังจากคลิกหรือกดแป้นเท่านั้น ให้คลิกปุ่มรันหรือหน้าต่างเกมก่อน

ต้องแก้ลูปเกมไหม?

ไม่ต้อง ลูป while ปกติที่มี pygame.event.get(), pygame.display.flip() และ clock.tick(60) รันได้ตามเดิม ไม่ต้องใช้ asyncio

ใช้กับเบราว์เซอร์ไหนได้บ้าง?

Chrome, Edge, Firefox และ Safari ทุกเบราว์เซอร์ส่งการกดแป้นและการคลิกถึงเกมได้ Chrome และ Edge เร็วที่สุด

ใช้รูปภาพและฟอนต์ได้ไหม?

ได้ อัปโหลดรูปภาพและเสียงลงพื้นที่ทำงานในตัวแก้ไข Python แล้วโหลดด้วยชื่อไฟล์ pygame.font.SysFont ใช้ฟอนต์ของระบบ ฟอนต์ไทย Arial, Segoe UI และฟอนต์จีน ญี่ปุ่น เกาหลีจึงแสดงได้ถูกต้อง