妙趣横生: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
相关推荐
数据智能老司机1 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机3 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i4 小时前
django中的FBV 和 CBV
python·django
c8i4 小时前
python中的闭包和装饰器
python
这里有鱼汤7 小时前
小白必看:QMT里的miniQMT入门教程
后端·python
TF男孩17 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在1 天前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP1 天前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法