Python Pygame 交互式演示

下面是一个使用 Pygame 创建的交互式演示程序,展示了 Pygame 的基本功能和特性。这个程序包含多个可视化元素,让您直观地了解 Pygame 的能力。

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

# 初始化 Pygame
pygame.init()

# 设置窗口尺寸
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Python Pygame 简介 - 交互式演示")

# 颜色定义
BACKGROUND = (25, 30, 45)
TEXT_COLOR = (220, 220, 255)
HIGHLIGHT = (0, 200, 255)
ACCENT = (255, 105, 180)
SHAPE_COLORS = [
    (72, 199, 116),   # 绿色
    (255, 179, 71),   # 橙色
    (77, 171, 247),   # 蓝色
    (255, 109, 106),  # 红色
    (173, 126, 255),  # 紫色
]

# 加载字体
title_font = pygame.font.SysFont("simhei", 48, bold=True)
heading_font = pygame.font.SysFont("simhei", 32, bold=True)
body_font = pygame.font.SysFont("simhei", 22)
small_font = pygame.font.SysFont("simhei", 18)

# 粒子类
class Particle:
    def __init__(self):
        self.reset()
        
    def reset(self):
        self.x = random.randint(0, WIDTH)
        self.y = random.randint(0, HEIGHT)
        self.size = random.randint(1, 3)
        self.speed = random.uniform(0.5, 2)
        self.color = random.choice(SHAPE_COLORS)
        self.color = (self.color[0], self.color[1], self.color[2], 150)
        self.angle = random.uniform(0, 2 * math.pi)
        
    def update(self):
        self.x += math.cos(self.angle) * self.speed
        self.y += math.sin(self.angle) * self.speed
        
        # 边界检查
        if self.x < 0 or self.x > WIDTH or self.y < 0 or self.y > HEIGHT:
            self.reset()

# 创建粒子
particles = [Particle() for _ in range(100)]

# 旋转形状类
class RotatingShape:
    def __init__(self, x, y, shape_type, color):
        self.x = x
        self.y = y
        self.shape_type = shape_type
        self.color = color
        self.angle = 0
        self.size = 40
        self.speed = random.uniform(0.01, 0.03)
        
    def update(self):
        self.angle += self.speed
        
    def draw(self, surface):
        points = []
        if self.shape_type == "triangle":
            for i in range(3):
                angle = self.angle + i * (2 * math.pi / 3)
                px = self.x + math.cos(angle) * self.size
                py = self.y + math.sin(angle) * self.size
                points.append((px, py))
            pygame.draw.polygon(surface, self.color, points)
            
        elif self.shape_type == "square":
            for i in range(4):
                angle = self.angle + i * (math.pi / 2)
                px = self.x + math.cos(angle) * self.size
                py = self.y + math.sin(angle) * self.size
                points.append((px, py))
            pygame.draw.polygon(surface, self.color, points)
            
        elif self.shape_type == "pentagon":
            for i in range(5):
                angle = self.angle + i * (2 * math.pi / 5)
                px = self.x + math.cos(angle) * self.size
                py = self.y + math.sin(angle) * self.size
                points.append((px, py))
            pygame.draw.polygon(surface, self.color, points)
            
        elif self.shape_type == "circle":
            pygame.draw.circle(surface, self.color, (int(self.x), int(self.y)), self.size)

# 创建旋转形状
rotating_shapes = []
for i in range(5):
    x = 150 + i * 150
    y = 450
    shape_type = ["triangle", "square", "pentagon", "circle", "square"][i]
    color = SHAPE_COLORS[i]
    rotating_shapes.append(RotatingShape(x, y, shape_type, color))

# 按钮类
class Button:
    def __init__(self, x, y, width, height, text):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.hover = False
        
    def draw(self, surface):
        color = HIGHLIGHT if self.hover else (70, 80, 110)
        pygame.draw.rect(surface, color, self.rect, border_radius=8)
        pygame.draw.rect(surface, (100, 200, 255), self.rect, 2, border_radius=8)
        
        text_surf = body_font.render(self.text, True, TEXT_COLOR)
        text_rect = text_surf.get_rect(center=self.rect.center)
        surface.blit(text_surf, text_rect)
        
    def check_hover(self, pos):
        self.hover = self.rect.collidepoint(pos)
        
    def is_clicked(self, pos, event):
        if event.type == MOUSEBUTTONDOWN and event.button == 1:
            return self.rect.collidepoint(pos)
        return False

# 创建按钮
buttons = [
    Button(50, 500, 200, 50, "Pygame 文档"),
    Button(280, 500, 200, 50, "示例代码"),
    Button(510, 500, 200, 50, "教程资源"),
]

# 主循环
clock = pygame.time.Clock()
running = True
mouse_pos = (0, 0)

while running:
    mouse_pos = pygame.mouse.get_pos()
    
    # 处理事件
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
            
        for button in buttons:
            if button.is_clicked(mouse_pos, event):
                # 这里可以添加按钮点击后的操作
                pass
    
    # 更新粒子
    for particle in particles:
        particle.update()
    
    # 更新旋转形状
    for shape in rotating_shapes:
        shape.update()
    
    # 绘制背景
    screen.fill(BACKGROUND)
    
    # 绘制粒子轨迹
    for particle in particles:
        pygame.draw.circle(screen, particle.color, (int(particle.x), int(particle.y)), particle.size)
    
    # 绘制标题
    title_text = title_font.render("Python Pygame 简介", True, HIGHLIGHT)
    screen.blit(title_text, (WIDTH//2 - title_text.get_width()//2, 30))
    
    # 绘制介绍文本
    intro_lines = [
        "Pygame 是一个用于开发多媒体应用程序(如游戏)的 Python 模块。",
        "它基于 SDL(Simple DirectMedia Layer)库,提供了丰富的功能:",
        "",
        "• 图形绘制(形状、图像、精灵)",
        "• 声音播放和混音",
        "• 键盘、鼠标和游戏手柄输入处理",
        "• 碰撞检测",
        "• 定时器和帧率控制",
        "",
        "Pygame 简单易学,是学习游戏开发和图形编程的理想选择。"
    ]
    
    for i, line in enumerate(intro_lines):
        text = body_font.render(line, True, TEXT_COLOR)
        screen.blit(text, (50, 120 + i * 30))
    
    # 绘制旋转形状标题
    shapes_title = heading_font.render("Pygame 图形绘制能力", True, ACCENT)
    screen.blit(shapes_title, (WIDTH//2 - shapes_title.get_width()//2, 380))
    
    # 绘制旋转形状
    for shape in rotating_shapes:
        shape.draw(screen)
    
    # 绘制按钮
    for button in buttons:
        button.check_hover(mouse_pos)
        button.draw(screen)
    
    # 绘制底部信息
    info_text = small_font.render("按 ESC 退出 | Pygame 版本: " + pygame.version.ver, True, (150, 150, 180))
    screen.blit(info_text, (WIDTH//2 - info_text.get_width()//2, HEIGHT - 30))
    
    # 绘制鼠标位置
    mouse_text = small_font.render(f"鼠标位置: ({mouse_pos[0]}, {mouse_pos[1]})", True, (180, 180, 220))
    screen.blit(mouse_text, (WIDTH - mouse_text.get_width() - 20, 20))
    
    # 绘制帧率
    fps_text = small_font.render(f"帧率: {int(clock.get_fps())} FPS", True, (180, 220, 180))
    screen.blit(fps_text, (20, 20))
    
    # 绘制交互提示
    hint_text = small_font.render("将鼠标悬停在按钮上查看效果", True, (255, 215, 100))
    screen.blit(hint_text, (WIDTH//2 - hint_text.get_width()//2, 560))
    
    # 更新屏幕
    pygame.display.flip()
    clock.tick(60)

# 退出 Pygame
pygame.quit()
sys.exit()

Pygame 简介

这个程序展示了 Pygame 的以下关键特性:

  1. 基本图形绘制

    • 绘制各种形状(圆形、三角形、正方形、五边形)
    • 使用颜色和透明度
    • 创建旋转动画
  2. 粒子系统

    • 创建简单的粒子效果
    • 粒子运动和边界处理
  3. 用户界面

    • 创建交互式按钮
    • 鼠标悬停效果
    • 按钮点击检测
  4. 文本渲染

    • 使用不同字体和大小
    • 多行文本渲染
  5. 性能监控

    • 显示当前帧率
    • 显示鼠标位置
  6. 动画效果

    • 旋转形状
    • 移动粒子

如何运行

  1. 确保已安装 Python(建议 Python 3.7 或更高版本)
  2. 安装 Pygame 库:
    pip install pygame
    
  3. 运行上面的 Python 代码

程序交互

  • 将鼠标悬停在底部按钮上可以看到高亮效果
  • 程序会显示当前鼠标位置和帧率
  • 按 ESC 键或关闭窗口退出程序

Pygame 学习资源

要了解更多关于 Pygame 的信息,可以参考以下资源:

  • 官方文档:https://www.pygame.org/docs/
  • Pygame 教程:https://pygame.org/tags/tutorial
  • Pygame 示例:https://github.com/pygame/pygame/tree/main/examples

这个演示程序展示了 Pygame 的基本功能,您可以根据需要扩展它或创建自己的游戏和应用程序!

你可能感兴趣的:(pygame,python,开发语言)