妙趣横生: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
相关推荐
ZhengEnCi4 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi5 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽5 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187916 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L1 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅1 天前
海天线算法的前世今生
python·计算机视觉
韩师傅1 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L1 天前
LangGraph的MessageState and HumanMessage
python
韩师傅1 天前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L1 天前
python的类&继承
python