跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像AI 生图工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
Python算法

Python 游戏编程入门:使用 Pygame 实现图形绘制与动画

Pygame 是 Python 的游戏开发库,支持图形绘制、用户输入及动画控制。 Pygame 的初始化流程、屏幕设置、事件循环机制以及常用绘图函数(如圆、矩形、线条、弧形)。通过移动矩形和 Pie 游戏的示例代码,展示了如何结合数学计算与逻辑判断实现交互效果。内容涵盖环境配置、核心 API 用法及常见错误修正,适合初学者掌握游戏编程基础。

CodeArtist发布于 2025/2/6更新于 2026/7/2441 浏览
Python 游戏编程入门:使用 Pygame 实现图形绘制与动画

前言

Pygame 是一个跨平台的 Python 模块,使得以下功能成为可能:绘制图形、获取用户输入、执行动画以及使用定时器让游戏按照稳定的帧速率运行。通过 Pygame 库,开发者可以以一定字体打印文本,使用循环来重复动作,并绘制圆、矩形、线条和弧形等基础几何形状。

本文旨在介绍 Pygame 的基础用法,包括环境配置、初始化流程、事件循环机制以及常用绘图 API,并通过示例代码展示如何实现简单的交互效果。

1. 环境准备

从 Pygame 官网下载并安装库。推荐使用 Python 3.x 版本配合最新稳定版 Pygame。

import pygame
from pygame.locals import *
pygame.init()

2. 屏幕设置与显示

创建一个指定大小的屏幕表面(Surface),并存储引用以便后续操作。

screen = pygame.display.set_mode((600, 500))
# screen 变量现在代表一个 Surface 对象

背景填充:在每一帧刷新前,通常需要先清除上一帧的内容。

screen.fill((0, 0, 0))  # (R, G, B) 颜色值,此处为黑色

刷新显示:将缓冲区内容更新到屏幕上。

pygame.display.update()

3. 文本渲染

使用 pygame.font 模块可以在屏幕上显示文字。

  1. 创建字体对象:None 表示使用默认字体,第二个参数为字号。
    myfont = pygame.font.Font(None, 60)
    
  2. 生成图像:render 方法返回一个 Surface,包含渲染后的文字。
    textimage = myfont.render("Hello Python", True, (255, 255, 255))
    # 参数说明:字符串,是否抗锯齿,颜色 (RGB)
    
  3. 绘制到屏幕:使用 blit 方法将文字 Surface 绘制到屏幕 Surface 上。
    screen.blit(textimage, (100, 100))
    

4. 事件循环

游戏的核心是持续运行的循环,用于处理用户输入和刷新画面。

while True:
    for event in pygame.event.get():
        if event.type == QUIT or event.type == KEYDOWN:
            import sys
            sys.exit()
    
    # 在此处更新游戏状态和绘制画面
    pygame.display.update()

注意:原代码中常见的错误如 event.typeQUIT 应修正为 event.type == QUIT;screen.display.update() 应修正为 pygame.display.update()。

5. 绘图函数详解

5.1 绘制圆形
# pygame.draw.circle(screen, color, position, radius, width)
pygame.draw.circle(screen, (255, 0, 0), (300, 250), 50, 2)
  • color: 颜色元组
  • position: 圆心坐标 (x, y)
  • radius: 半径
  • width: 线条宽度,0 表示填充
5.2 绘制矩形
# pygame.draw.rect(screen, color, rect, width)
# rect: (x, y, width, height)
pos = (100, 100, 100, 100)
pygame.draw.rect(screen, (0, 255, 0), pos, 0)
5.3 绘制线条
# pygame.draw.line(screen, color, start_pos, end_pos, width)
pygame.draw.line(screen, (0, 0, 255), (0, 0), (100, 100), 2)
5.4 绘制弧形
import math
# pygame.draw.arc(screen, color, rect, start_angle, end_angle, width)
# position: (x, y, w, h) 定义外接矩形
start_angle = math.radians(0)
end_angle = math.radians(90)
pygame.draw.arc(screen, (255, 255, 0), (200, 200, 100, 100), start_angle, end_angle, 2)

角度从正右侧开始逆时针旋转,0 到 360 度。

6. 示例一:移动矩形

此示例演示了如何在循环中更新位置、检测边界碰撞并改变颜色。

import sys
import random
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("Drawing Rectangles")

pos_x = 300
pos_y = 250
vel_x = 2
vel_y = 1
rand1, rand2, rand3 = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
color = (rand1, rand2, rand3)

while True:
    for event in pygame.event.get():
        if event.type in (QUIT, KEYDOWN):
            sys.exit()

    screen.fill((0, 0, 200))
    
    pos_x += vel_x
    pos_y += vel_y
    
    # 水平边界检测
    if pos_x > 500 or pos_x < 0:
        vel_x = -vel_x
        rand1, rand2, rand3 = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
        color = (rand1, rand2, rand3)
    
    # 垂直边界检测
    if pos_y > 400 or pos_y < 0:
        vel_y = -vel_y
        rand1, rand2, rand3 = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
        color = (rand1, rand2, rand3)
    
    width = 0
    pos = (pos_x, pos_y, 100, 100)
    pygame.draw.rect(screen, color, pos, width)
    
    pygame.display.update()

7. 示例二:Pie 游戏

此示例演示了如何根据按键状态绘制不同的扇形区域。

import sys
import math
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("The Pie Game")
myfont = pygame.font.Font(None, 60)

color = (200, 80, 60)
width = 4
x, y = 300, 250
radius = 200
position = (x - radius, y - radius, radius * 2, radius * 2)

piece1 = piece2 = piece3 = piece4 = False

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == KEYUP:
            if event.key == pygame.K_ESCAPE:
                sys.exit()
            elif event.key == pygame.K_1:
                piece1 = True
            elif event.key == pygame.K_2:
                piece2 = True
            elif event.key == pygame.K_3:
                piece3 = True
            elif event.key == pygame.K_4:
                piece4 = True

    screen.fill((0, 0, 200))
    
    # 绘制数字提示
    textimage1 = myfont.render("1", True, color)
    screen.blit(textimage1, (x + radius / 2 - 20, y - radius / 2))
    textimage2 = myfont.render("2", True, color)
    screen.blit(textimage2, (x - radius / 2, y - radius / 2))
    textimage3 = myfont.render("3", True, color)
    screen.blit(textimage3, (x - radius / 2, y + radius / 2 - 20))
    textimage4 = myfont.render("4", True, color)
    screen.blit(textimage4, (x + radius / 2 - 20, y + radius / 2 - 20))
    
    # 根据状态绘制扇形
    if piece1:
        pygame.draw.arc(screen, color, position, math.radians(0), math.radians(90), width)
        pygame.draw.line(screen, color, (x, y), (x + radius, y), width)
        pygame.draw.line(screen, color, (x, y), (x, y - radius), width)
    
    if piece2:
        pygame.draw.arc(screen, color, position, math.radians(90), math.radians(180), width)
        pygame.draw.line(screen, color, (x, y), (x, y - radius), width)
        pygame.draw.line(screen, color, (x, y), (x - radius, y), width)
    
    if piece3:
        pygame.draw.arc(screen, color, position, math.radians(180), math.radians(270), width)
        pygame.draw.line(screen, color, (x, y), (x - radius, y), width)
        pygame.draw.line(screen, color, (x, y), (x, y + radius), width)
    
    if piece4:
        pygame.draw.arc(screen, color, position, math.radians(270), math.radians(360), width)
        pygame.draw.line(screen, color, (x, y), (x, y + radius), width)
        pygame.draw.line(screen, color, (x, y), (x + radius, y), width)
      
    # 全部完成时变绿
    if piece1 and piece2 and piece3 and piece4:
        color = (0, 255, 0)
    
    pygame.display.update()

8. 挑战练习

8.1 绘制椭圆

使用 pygame.draw.ellipse 函数,其参数结构与 rect 类似,接受 (x, y, width, height) 定义的矩形区域。

8.2 随机绘制线条

在循环外绘制一次图形,则图形保持不变;在 while True 循环内绘制,则每帧都会重绘。这有助于理解渲染循环的机制。

import random
import sys
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((800, 600))

for i in range(1000):
    x1, y1 = random.randint(0, 800), random.randint(0, 600)
    x2, y2 = random.randint(0, 800), random.randint(0, 600)
    pygame.draw.line(screen, (100, 255, 200), (x1, y1), (x2, y2), 2)

while True:
    for event in pygame.event.get():
        if event.type in (QUIT, KEYDOWN):
            sys.exit()
    pygame.display.update()

总结

Pygame 提供了丰富的接口来处理图形界面和游戏逻辑。掌握初始化、事件循环、绘图 API 以及数学计算(如弧度转换)是入门的关键。建议初学者多尝试修改示例中的参数,观察变化,逐步构建自己的小游戏项目。

目录

  1. 前言
  2. 1. 环境准备
  3. 2. 屏幕设置与显示
  4. screen 变量现在代表一个 Surface 对象
  5. 3. 文本渲染
  6. 4. 事件循环
  7. 5. 绘图函数详解
  8. 5.1 绘制圆形
  9. pygame.draw.circle(screen, color, position, radius, width)
  10. 5.2 绘制矩形
  11. pygame.draw.rect(screen, color, rect, width)
  12. rect: (x, y, width, height)
  13. 5.3 绘制线条
  14. pygame.draw.line(screen, color, startpos, endpos, width)
  15. 5.4 绘制弧形
  16. pygame.draw.arc(screen, color, rect, startangle, endangle, width)
  17. position: (x, y, w, h) 定义外接矩形
  18. 6. 示例一:移动矩形
  19. 7. 示例二:Pie 游戏
  20. 8. 挑战练习
  21. 8.1 绘制椭圆
  22. 8.2 随机绘制线条
  23. 总结
  • 免费图片AI生成工具免费生成了解详情
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 免费图片视频在线生成30秒,将你的创意变成现实开始设计
  • X/Twitter免费视频下载器免登陆无限额度免费视频解析下载了解详情
  • 100+免费在线小游戏爽一把
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • .NET 微服务架构:从 WebAPI 到 Docker 实战
  • AIRI:开源的 AI 多模态数字桌面伴侣
  • 快速幂算法详解:高效计算 x 的 n 次幂
  • 通义万相 2.1:多模态 AI 生成的架构突破与应用前景
  • 前端请求后端返回 404/405/500 状态码排查与解决指南
  • JDK + Maven + IDEA 安装配置指南
  • 10 分钟部署大模型:本地知识库搭建指南(Ollama + Dify + Docker)
  • macOS 彻底卸载 Python 的完整指南
  • 编译型与解释型语言:核心原理、区别与应用场景
  • Windows 安装 Neo4j 图数据库详细教程
  • 绿豆 UI9 源码支持 Python 线路与弹幕解析功能介绍
  • 10 款主流网络爬虫工具对比评测:从 Scrapy 到 Bright Data 选型指南
  • 飞算 JavaAI:Java 开发的智能助推引擎
  • SM4 国密算法原理与 C++跨平台实现详解
  • Spring Data JPA 原理与实战:Repository 接口深度解析
  • GitHub 学生开发者认证指南与配置流程
  • AI 交互上下文溢出解决方案:会话压缩技术实现解析
  • 大模型基于 llama.cpp 量化详解
  • 算法面试:C++ 数组去重与位运算核心解析
  • Git 分布式版本控制:安装、配置与实战

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • curl 转代码

    解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online