妙趣横生: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 小时前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽6 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码6 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱16 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵17 小时前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio21 小时前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户0332126663671 天前
使用 Python 从零创建 Word 文档
python
Csvn1 天前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽1 天前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate
用户556918817531 天前
#从脚本到独立程序:Python + Playwright 批量抓取的完整踩坑记录
python·自动化运维