妙趣横生: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
相关推荐
MeixianAgent4 小时前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6257 小时前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python
SelectDB1 天前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵2 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li2 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田3 天前
Pydantic校验配置文件
python
hboot3 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络