ZetCode

Pygame 入门

最后修改于 2025 年 2 月 25 日

Pygame 是一个流行的 Python 库,用于创建 2D 游戏和多媒体应用程序。它提供了处理图形、声音和用户输入的工具,使其成为游戏开发初学者的绝佳选择。本教程涵盖了设置 Pygame 窗口和处理事件的基础知识。

Pygame 构建在 SDL(Simple DirectMedia Layer)库之上,该库提供对音频、键盘、鼠标和显示硬件的底层访问。借助 Pygame,您可以轻松创建游戏和交互式应用程序。

安装 Pygame

在使用 Pygame 之前,您需要安装它。您可以使用 pip 安装 Pygame

install_pygame.sh
pip install pygame

安装完成后,您就可以开始使用 Pygame 创建游戏了。

设置 Pygame 窗口

本示例演示了如何创建一个基本的 Pygame 窗口。

basic_window.py
import pygame

# Initialize Pygame
pygame.init()

# Set up the display
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Pygame Window")

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

    # Fill the screen with a color
    screen.fill((0, 0, 0))

    # Update the display
    pygame.display.flip()


pygame.quit()

pygame.init 函数初始化所有 Pygame 模块。pygame.display.set_mode 函数创建一个指定大小的窗口。主循环处理事件并更新显示。

处理事件

本示例演示了如何在 Pygame 中处理键盘和鼠标事件。

event_handling.py
import pygame

# Initialize Pygame
pygame.init()

# Set up the display
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Event Handling")

# Main loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            print(f"Key pressed: {pygame.key.name(event.key)}")
        elif event.type == pygame.MOUSEBUTTONDOWN:
            print(f"Mouse button pressed at: {event.pos}")

    # Fill the screen with a color
    screen.fill((0, 0, 0))

    # Update the display
    pygame.display.flip()


pygame.quit()

pygame.event.get 函数从事件队列中检索所有事件。使用 pygame.KEYDOWNpygame.MOUSEBUTTONDOWN 来处理键盘和鼠标事件。

绘制图形

本示例演示了如何在屏幕上绘制图形。

drawing_shapes.py
import pygame

# Initialize Pygame
pygame.init()

# Set up the display
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Drawing Shapes")

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

    # Fill the screen with a color
    screen.fill((255, 255, 255))

    # Draw a rectangle
    pygame.draw.rect(screen, (255, 0, 0), (100, 100, 200, 150))

    # Draw a circle
    pygame.draw.circle(screen, (0, 255, 0), (400, 300), 75)

    # Draw a line
    pygame.draw.line(screen, (0, 0, 255), (700, 100), (700, 500), 5)

    # Update the display
    pygame.display.flip()


pygame.quit()

pygame.draw.rectpygame.draw.circlepygame.draw.line 函数用于在屏幕上绘制图形。

弹跳球

在下一个示例中,我们将创建一个弹跳球动画。

anim_ball.py
import pygame

# Initialize Pygame
pygame.init()

# Set up the display
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Bouncing Ball")

# Ball properties
ball_color = (255, 255, 255)
ball_radius = 20
ball_x = 400
ball_y = 300
ball_x_speed = 5

clock = pygame.time.Clock()

ball_y_speed = 5

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

    # Ball movement
    ball_x += ball_x_speed
    ball_y += ball_y_speed

    # Bounce off the walls
    if ball_x + ball_radius > 800 or ball_x - ball_radius < 0:
        ball_x_speed *= -1
    if ball_y + ball_radius > 600 or ball_y - ball_radius < 0:
        ball_y_speed *= -1

    # Fill the screen with a color
    screen.fill((0, 0, 0))

    # Draw the ball
    pygame.draw.circle(screen, ball_color, (int(ball_x), int(ball_y)), ball_radius)

    clock.tick(60)
    
    # Update the display
    pygame.display.flip()


pygame.quit()

定义了球的属性,包括颜色、半径、初始位置和速度。程序的主循环在 running 变量为 True 时运行。在该循环中,它会检查事件(如退出程序)并根据球的速度更新其位置。如果球碰到窗口边缘,它会通过反转速度来反弹。

然后,屏幕被填充为黑色,并使用 pygame.draw.circle 在更新后的位置绘制球。程序使用 clock.tick(60) 确保显示以每秒 60 帧的速度更新,最后,使用 pygame.display.flip 更新显示。主循环结束后,使用 pygame.quit 退出 Pygame。

Pygame 最佳实践

来源

Pygame 文档

在本文中,我们探讨了 Pygame 的基础知识,包括设置窗口、处理事件、绘制图形和移动球。

作者

我叫 Jan Bodnar,是一名热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 Python 教程