Pygame 入门与功能演示

224 阅读13分钟

Pygame 入门与功能演示

在这里插入图片描述

此外,我的纱窗也是绿的,极浅极浅的绿,被太阳一照,当真就像古美人的.纱裙一样飘缈。你们想,我在这样一个染满绿意的早晨和你们写信,我的心里又焉能不充溢着生气勃勃的绿呢?

1. Pygame 初始化与主循环

代码:

import pygame

pygame.init()  # 初始化 Pygame 所有模块
screen = pygame.display.set_mode((800, 600))  # 创建宽800像素,高600像素的窗口
pygame.display.set_caption('Pygame Basic Example')  # 设置窗口标题

running = True  # 控制主循环是否继续
while running:  # 游戏主循环
    for event in pygame.event.get():  # 遍历当前的所有事件
        if event.type == pygame.QUIT:  # 如果用户关闭窗口
            running = False  # 结束主循环
pygame.quit()  # 退出 Pygame,清理资源

详细解释:

  1. 初始化 Pygame:
pygame.init()
- `pygame.init()` 用于初始化 Pygame 的所有模块(如声音、图像、事件等)。每个 Pygame 程序都需要调用它一次。

2. 设置窗口大小:

screen = pygame.display.set_mode((800, 600))
- `pygame.display.set_mode((800, 600))` 设置窗口的大小,这里指定窗口宽度为 800 像素,高度为 600 像素。返回的 `screen` 对象用于后续绘制图像。

3. 设置窗口标题:

pygame.display.set_caption('Pygame Basic Example')
- `pygame.display.set_caption()` 设置窗口标题为 "Pygame Basic Example"

4. 主循环:

running = True
while running:
- `while running:` 是游戏的主循环,游戏程序通常在这个循环里运行,直到用户关闭窗口。

5. 事件处理:

for event in pygame.event.get():
- `pygame.event.get()` 获取当前所有的事件,比如键盘按下、鼠标点击等。通过遍历事件,可以处理用户的操作。

6. 退出事件:

if event.type == pygame.QUIT:
- `pygame.QUIT` 是用户关闭窗口的事件类型,如果检测到该事件,程序会退出主循环。

7. 退出 Pygame:

pygame.quit()
- `pygame.quit()` 退出 Pygame,清理所有初始化的模块。

2. 绘制图形(矩形)

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Draw Rectangle Example')

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

    screen.fill((255, 255, 255))  # 用白色填充屏幕

    pygame.draw.rect(screen, (255, 0, 0), (50, 50, 100, 100))  # 绘制红色矩形

    pygame.display.flip()  # 更新屏幕显示

pygame.quit()

详细解释:

  1. 屏幕填充:
screen.fill((255, 255, 255))
- `screen.fill((255, 255, 255))` 用白色填充整个屏幕,每一帧开始时,通常要清除上一次的绘制内容。RGB `(255, 255, 255)` 是白色。

2. 绘制矩形:

pygame.draw.rect(screen, (255, 0, 0), (50, 50, 100, 100))
- `pygame.draw.rect()` 绘制一个矩形。
- 参数解释:
    * `screen`: 要绘制的目标表面,这里是窗口。
    * `(255, 0, 0)`: 矩形的颜色,RGB 值,红色。
    * `(50, 50, 100, 100)`: 矩形的位置和大小。前两个数 `50, 50` 表示矩形的左上角坐标,后两个数 `100, 100` 是矩形的宽度和高度。

3. 刷新屏幕:

pygame.display.flip()
- `pygame.display.flip()` 用于刷新整个窗口的内容,确保所有的绘制操作更新到屏幕上。

3. 加载并显示图像

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Image Example')

# 加载图像
image = pygame.image.load('example.png')  # 加载图像文件

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

    screen.fill((255, 255, 255))  # 清空屏幕

    screen.blit(image, (100, 50))  # 将图像绘制到屏幕上

    pygame.display.flip()  # 刷新显示

pygame.quit()

详细解释:

  1. 加载图像:
image = pygame.image.load('example.png')
- `pygame.image.load()` 从文件中加载图像,并返回一个 `Surface` 对象,可以通过它进行绘制操作。
- `'example.png'` 是图像文件的路径。确保图像文件与代码位于相同目录下,或指定正确的文件路径。

2. 绘制图像:

screen.blit(image, (100, 50))
- `screen.blit()``Pygame` 用来绘制图像的常用方法。
- 参数 `(image, (100, 50))``image` 是需要绘制的图像,`(100, 50)` 是图像在窗口上的左上角位置。

4. 处理键盘输入

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Keyboard Input Example')

x, y = 200, 150  # 圆形的初始位置
running = True

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

    keys = pygame.key.get_pressed()  # 检查键盘上哪些键被按下
    if keys[pygame.K_LEFT]:  # 如果按下左键
        x -= 5  # 向左移动
    if keys[pygame.K_RIGHT]:  # 如果按下右键
        x += 5  # 向右移动
    if keys[pygame.K_UP]:  # 如果按下上键
        y -= 5  # 向上移动
    if keys[pygame.K_DOWN]:  # 如果按下下键
        y += 5  # 向下移动

    screen.fill((255, 255, 255))  # 清屏
    pygame.draw.circle(screen, (0, 0, 255), (x, y), 20)  # 绘制蓝色圆形

    pygame.display.flip()  # 更新显示

pygame.quit()

详细解释:

  1. 获取键盘状态:
keys = pygame.key.get_pressed()
- `pygame.key.get_pressed()` 返回一个包含所有键状态的列表,每个键对应一个布尔值。如果某个键被按下,对应的值为 `True`,否则为 `False`

2. 检查方向键:

if keys[pygame.K_LEFT]:
    x -= 5
- `pygame.K_LEFT` 表示左箭头键。当用户按下左键时,将 `x` 坐标减少 5,表示向左移动圆形。同理,可以检测其他方向的按键。

3. 绘制圆形:

pygame.draw.circle(screen, (0, 0, 255), (x, y), 20)
- `pygame.draw.circle()` 用来绘制圆形。
- 参数 `(screen, (0, 0, 255), (x, y), 20)``screen` 是目标表面,`(0, 0, 255)` 是颜色(蓝色),`(x, y)` 是圆心坐标,`20` 是圆的半径。

好的,下面我将继续为学生展示 Pygame 的更多功能,并详细解释每一行代码,力求清晰易懂。以下是更多的示例,涵盖音频、文本渲染、动画等功能。


5. 处理鼠标输入

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Mouse Input Example')

running = True

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

    screen.fill((255, 255, 255))  # 清空屏幕

    mouse_pos = pygame.mouse.get_pos()  # 获取鼠标位置
    pygame.draw.circle(screen, (0, 255, 0), mouse_pos, 15)  # 在鼠标位置绘制一个绿色圆

    pygame.display.flip()  # 更新显示

pygame.quit()

详细解释:

  1. 获取鼠标位置:
mouse_pos = pygame.mouse.get_pos()
- `pygame.mouse.get_pos()` 返回鼠标当前在窗口中的位置,结果是一个包含 `(x, y)` 坐标的元组。

2. 根据鼠标位置绘制圆形:

pygame.draw.circle(screen, (0, 255, 0), mouse_pos, 15)
- `pygame.draw.circle()` 使用鼠标位置作为圆心,绘制一个半径为 15 的绿色圆。

6. 文本渲染与显示

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Text Rendering Example')

# 定义字体对象
font = pygame.font.SysFont(None, 55)

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

    screen.fill((255, 255, 255))  # 清空屏幕

    # 渲染文本
    text = font.render('Hello, Pygame!', True, (0, 128, 0))  # 创建绿色文本
    screen.blit(text, (50, 100))  # 在屏幕上的位置 (50, 100) 显示文本

    pygame.display.flip()  # 更新显示

pygame.quit()

详细解释:

  1. 定义字体:
font = pygame.font.SysFont(None, 55)
- `pygame.font.SysFont()` 创建一个字体对象。
- 参数 `None` 表示使用系统默认字体,`55` 是字体大小。

2. 渲染文本:

text = font.render('Hello, Pygame!', True, (0, 128, 0))
- `font.render()` 将文本转换为可绘制的 `Surface` 对象。
- 参数 `'Hello, Pygame!'` 是要显示的文本,`True` 表示启用抗锯齿,`(0, 128, 0)` 是文本颜色,绿色。

3. 显示文本:

screen.blit(text, (50, 100))
- 使用 `screen.blit()` 将文本显示在屏幕的 (50, 100) 位置。

7. 播放声音

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Sound Example')

# 加载声音文件
sound = pygame.mixer.Sound('example.wav')  # 加载音频文件

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:  # 当按键按下时播放声音
            sound.play()

    screen.fill((255, 255, 255))  # 清空屏幕
    pygame.display.flip()

pygame.quit()

详细解释:

  1. 加载声音文件:
sound = pygame.mixer.Sound('example.wav')
- `pygame.mixer.Sound()` 用于加载音频文件,这里我们加载了一个 `.wav` 文件。Pygame 支持多种音频格式。

2. 播放声音:

sound.play()
- `sound.play()` 播放加载的音频文件。该函数可以在按键事件中调用,实现按下键盘时播放音效。

8. 绘制多边形

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Polygon Example')

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

    screen.fill((255, 255, 255))  # 清空屏幕

    # 定义多边形的顶点
    points = [(100, 100), (150, 50), (200, 100), (150, 150)]

    # 绘制多边形
    pygame.draw.polygon(screen, (0, 0, 255), points)

    pygame.display.flip()  # 更新显示

pygame.quit()

详细解释:

  1. 定义多边形的顶点:
points = [(100, 100), (150, 50), (200, 100), (150, 150)]
- `points` 是一个包含多边形各个顶点坐标的列表,表示一个四边形。

2. 绘制多边形:

pygame.draw.polygon(screen, (0, 0, 255), points)
- `pygame.draw.polygon()` 用来绘制多边形。
- 参数 `(screen, (0, 0, 255), points)`,第一个参数是绘制的目标窗口,第二个是颜色(蓝色),第三个是多边形的顶点列表。

9. 渐变背景

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Gradient Background Example')

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

    # 通过每个像素列来创建渐变效果
    for x in range(400):
        color = (x % 255, 128, 255 - x % 255)  # 生成渐变颜色
        pygame.draw.line(screen, color, (x, 0), (x, 300))  # 绘制从顶到底的线条

    pygame.display.flip()  # 更新显示

pygame.quit()

详细解释:

  1. 创建渐变颜色:
color = (x % 255, 128, 255 - x % 255)
- 我们根据 `x` 的值生成颜色,使得颜色从左到右渐变。`x % 255``255 - x % 255` 会产生一个从 0 到 255 循环变化的颜色值。

2. 绘制垂直线条:

pygame.draw.line(screen, color, (x, 0), (x, 300))
- `pygame.draw.line()` 用来绘制从 `(x, 0)``(x, 300)` 的线条,即屏幕上每一列都画一条线,从而形成渐变效果。

10. 动画效果(移动的矩形)

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Moving Rectangle Example')

x = 0  # 矩形初始x坐标
speed = 5  # 矩形的移动速度

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

    screen.fill((255, 255, 255))  # 清空屏幕

    # 移动矩形
    pygame.draw.rect(screen, (255, 0, 0), (x, 100, 50, 50))  # 绘制矩形
    x += speed  # 增加x坐标实现移动

    if x > 350 or x < 0:  # 碰到边界时反向
        speed = -speed

    pygame.display.flip()  # 更新显示
    pygame.time.delay(30)  # 增加延迟实现动画效果

pygame.quit()

详细解释:

  1. 控制矩形的移动:
x += speed
- 每帧增加矩形的 `x` 坐标,使矩形在屏幕上向右移动。

2. 检测边界碰撞并反向:

if x > 350 or x < 0:
    speed = -speed
- 当矩

形碰到屏幕边缘时,反转移动方向。

  1. 延迟实现平滑动画:
pygame.time.delay(30)

11. 使用计时器

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Timer Example')

# 设置一个事件定时器,每 1000 毫秒触发一次
TIMER_EVENT = pygame.USEREVENT + 1
pygame.time.set_timer(TIMER_EVENT, 1000)

counter = 10  # 计数器初始值
font = pygame.font.SysFont(None, 55)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == TIMER_EVENT:  # 每次定时器事件触发时减少计数器
            counter -= 1
            if counter <= 0:
                running = False

    screen.fill((255, 255, 255))  # 清空屏幕

    # 显示计时器
    text = font.render(str(counter), True, (255, 0, 0))
    screen.blit(text, (180, 130))

    pygame.display.flip()

pygame.quit()

详细解释:

  1. 设置定时器:

    pygame.time.set_timer(TIMER_EVENT, 1000)
    
    • pygame.time.set_timer() 每隔指定时间(这里是 1000 毫秒,即 1 秒)生成一个定时器事件。
    • TIMER_EVENT 是自定义的事件类型。
  2. 处理定时器事件:

    if event.type == TIMER_EVENT:
        counter -= 1
    
    • 每次定时器事件触发时,计数器减 1,当计数器为 0 时,退出游戏循环。

12. 加载和显示图片

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Image Example')

# 加载图片
image = pygame.image.load('example.png')

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

    screen.fill((255, 255, 255))  # 清空屏幕
    screen.blit(image, (50, 50))  # 在屏幕上 (50, 50) 位置显示图片

    pygame.display.flip()

pygame.quit()

详细解释:

  1. 加载图片:

    image = pygame.image.load('example.png')
    
    • pygame.image.load() 用于加载图片文件,支持多种格式(如 .png.jpg 等)。
  2. 显示图片:

    screen.blit(image, (50, 50))
    
    • screen.blit() 将图片绘制在屏幕的指定位置,这里是 (50, 50)

13. 处理键盘输入

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Keyboard Input Example')

x = 200
y = 150
speed = 5

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

    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((255, 255, 255))  # 清空屏幕
    pygame.draw.rect(screen, (0, 0, 255), (x, y, 50, 50))  # 在新位置绘制矩形

    pygame.display.flip()

pygame.quit()

详细解释:

  1. 获取键盘按键状态:

    keys = pygame.key.get_pressed()
    
    • pygame.key.get_pressed() 返回当前所有按键的状态,按键被按下时对应的位置为 True
  2. 处理按键输入:

    if keys[pygame.K_LEFT]:
        x -= speed
    
    • 如果左方向键(K_LEFT)被按下,矩形在屏幕上向左移动。其他方向键类似。

14. 播放背景音乐

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Background Music Example')

# 加载并播放背景音乐
pygame.mixer.music.load('background.mp3')
pygame.mixer.music.play(-1)  # 无限循环播放音乐

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

    screen.fill((255, 255, 255))  # 清空屏幕
    pygame.display.flip()

pygame.quit()
pygame.mixer.music.stop()  # 结束时停止音乐

详细解释:

  1. 加载背景音乐:

    pygame.mixer.music.load('background.mp3')
    
    • pygame.mixer.music.load() 用于加载背景音乐文件。
  2. 播放音乐:

    pygame.mixer.music.play(-1)
    
    • pygame.mixer.music.play() 播放背景音乐。参数 -1 表示无限循环播放。
  3. 停止音乐:

    pygame.mixer.music.stop()
    
    • 程序结束时使用 stop() 方法停止播放音乐。

15. 透明图片

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Transparent Image Example')

# 加载带透明通道的图片
image = pygame.image.load('example.png').convert_alpha()

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

    screen.fill((255, 255, 255))  # 清空屏幕
    screen.blit(image, (100, 100))  # 在屏幕上 (100, 100) 位置显示透明图片

    pygame.display.flip()

pygame.quit()

详细解释:

  1. 加载透明图片:

    image = pygame.image.load('example.png').convert_alpha()
    
    • 使用 convert_alpha() 方法加载带有透明通道的图片(如 PNG 格式)。

16. 鼠标点击检测

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Mouse Click Example')

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:  # 检测鼠标点击
            print('Mouse clicked at', event.pos)  # 打印点击位置

    screen.fill((255, 255, 255))  # 清空屏幕
    pygame.display.flip()

pygame.quit()

详细解释:

  1. 检测鼠标点击:

    elif event.type == pygame.MOUSEBUTTONDOWN:
        print('Mouse clicked at', event.pos)
    
    • pygame.MOUSEBUTTONDOWN 事件触发时,表示鼠标被按下,此时 event.pos 是鼠标点击的坐标。

17. 处理窗口缩放

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300), pygame.RESIZABLE)
pygame.display.set_caption('Resizable Window Example')

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.VIDEORESIZE:  # 检测窗口大小变化
            screen = pygame.display.set_mode(event.size, pygame.RESIZABLE)

    screen.fill((255, 255, 255))  # 清空屏幕
    pygame.draw.rect(screen, (0, 0, 255), (50, 50, 100, 100))  # 绘制矩形

    pygame.display.flip()

pygame.quit()

详细解释:

  1. 设置可缩放窗口:

    screen = pygame.display.set_mode((400, 300), pygame.RESIZABLE)
    
    • pygame.RESIZABLE 标志允许窗口大小调整。
  2. 处理窗口大小变化:

    if event.type == pygame.VIDEORESIZE:
        screen = pygame.display.set_mode(event.size, pygame.RESIZABLE)
    
    • 当窗口大小变化时,重新设置窗口大小。

18. 创建简单按钮

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Button Example')

font = pygame.font.SysFont(None, 55)
button_color = (0, 255

, 0)
button_rect = pygame.Rect(100, 100, 200, 50)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if button_rect.collidepoint(event.pos):  # 检测按钮点击
                print('Button clicked!')

    screen.fill((255, 255, 255))  # 清空屏幕
    pygame.draw.rect(screen, button_color, button_rect)  # 绘制按钮
    text = font.render('Click Me', True, (255, 255, 255))
    screen.blit(text, (button_rect.x + 40, button_rect.y + 10))

    pygame.display.flip()

pygame.quit()

详细解释:

  1. 创建按钮矩形:

    button_rect = pygame.Rect(100, 100, 200, 50)
    
    • pygame.Rect() 定义按钮区域。
  2. 检测按钮点击:

    if button_rect.collidepoint(event.pos):
        print('Button clicked!')
    
    • 使用 collidepoint() 检测鼠标点击是否在按钮区域内。

19. 控制帧率

代码:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Frame Rate Control Example')

clock = pygame.time.Clock()  # 创建一个 Clock 对象用于控制帧率
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255, 255, 255))  # 清空屏幕
    pygame.draw.circle(screen, (0, 0, 255), (200, 150), 50)  # 绘制蓝色圆形

    pygame.display.flip()
    clock.tick(30)  # 设置帧率为 30

pygame.quit()

详细解释:

  1. 控制帧率:

    clock.tick(30)
    
    • clock.tick(30) 控制游戏循环每秒运行 30 帧。