妙趣横生:Python 动画程序的实现与多样化拓展

以下是另一个使用Python的pygame库实现的简单动画程序示例,实现了一个小球在窗口内反弹的动画效果,标题为《Python之Pygame实现小球反弹动画》:

python 复制代码
import pygame

# 初始化pygame
pygame.init()

# 设置窗口大小
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball Animation")

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# 小球的初始参数
ball_radius = 20
ball_x = width // 2
ball_y = height // 2
ball_speed_x = 3
ball_speed_y = 3

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 填充背景色
    screen.fill(black)

    # 更新小球位置
    ball_x += ball_speed_x
    ball_y += ball_speed_y

    # 检测小球与边界的碰撞
    if ball_x - ball_radius <= 0 or ball_x + ball_radius >= width:
        ball_speed_x = -ball_speed_x
    if ball_y - ball_radius <= 0 or ball_y + ball_radius >= height:
        ball_speed_y = -ball_speed_y

    # 绘制小球
    pygame.draw.circle(screen, red, (ball_x, ball_y), ball_radius)

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

# 退出pygame
pygame.quit()

在这个程序中:

  1. 首先初始化pygame库,创建一个指定大小的窗口并设置标题。
  2. 定义了白色、黑色和红色三种颜色,用于背景和小球的绘制。
  3. 设定了小球的半径、初始位置和移动速度。
  4. 在游戏主循环中,处理退出事件。然后填充背景色,根据当前速度更新小球位置,并检测小球是否与窗口边界碰撞,若碰撞则改变相应方向的速度。接着在新位置绘制小球,最后更新屏幕显示。
  5. 当用户关闭窗口时,退出pygame
相关推荐
cup111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi003 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵5 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf6 小时前
Agent 流程编排
后端·python·agent
copyer_xyf6 小时前
Agent RAG
后端·python·agent
copyer_xyf6 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf6 小时前
Agent 记忆管理
后端·python·agent
星云穿梭21 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵1 天前
用 Pygame 实现 15 puzzle
python·数学·游戏