Python巧用Pygame实现多彩小球窗口乱飞效果
以下是一个使用Python编写的窗口乱飞的程序: ```python import pygame import random # 初始化 pygame.init() # 窗口大小 screen_width = 800 screen_height = 600 # 创建窗口 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("窗口乱飞") # 颜色定义 white = (255, 255, 255) # 图片加载 icon = pygame.image.load("icon.png") pygame.display.set_icon(icon) # 小球类 class Ball: def __init__(self, color, radius, x, y, speed_x, speed_y): self.color = color self.radius = radius self.x = x self.y = y self.speed_x = speed_x self.speed_y = speed_y def move(self): self.x += self.speed_x self.y += self.speed_y # 边界检测 if self.x - self.radius < 0 or self.x + self.radius > screen_width: self.speed_x = -self.speed_x if self.y - self.radius < 0 or self.y + self.radius > screen_height: self.speed_y = -self.speed_y def draw(self): pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius) # 创建小球列表 balls = [] for i in range(10): color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) radius = random.randint(10, 50) x = random.randint(radius, screen_width - radius) y = random.randint(radius, screen_height - radius) speed_x = random.randint(-5, 5) speed_y = random.randint(-5, 5) ball = Ball(color, radius, x, y, speed_x, speed_y) balls.append(ball) # 游戏循环 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 清空屏幕 screen.fill(white) # 更新小球位置并绘制 for ball in balls: ball.move() ball.draw() # 更新窗口显示 pygame.display.update() # 退出程序 pygame.quit() ``` 这个程序使用了pygame模块来实现窗口的创建和绘制。它创建了一个窗口,并在窗口中绘制了多个随机颜色和大小的小球,然后让这些小球在窗口中乱飞。 ######[AI写代码神器 | 1344点数解答 | 2024-06-27 10:14:24]
- 修正代码实现“3D爱心粒子跳动”,附运行错误及逻辑注意点(字节豆包 | 1111点数解答 | 2025-07-28 22:34:46)167
- Python 实现 3D 爱心粒子跳动特效:代码解析与注意要点(字节豆包 | 1142点数解答 | 2025-07-28 22:36:37)167
- Python生日祝福爱心粒子特效代码优化与开发建议(字节豆包 | 2223点数解答 | 2026-03-21 14:32:57)23
- Python 运行报错:urllib3 网络连接创建失败,原因及排查建议(字节豆包 | 161点数解答 | 2024-10-31 00:39:36)488
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)371
- Python 利用 win32com 库:将 Excel 转换为 A4 横向 PDF 并单独打印首列(字节豆包 | 507点数解答 | 2025-03-10 15:48:12)328
- Python 报错:for 语句后缩进缺失,附修正示例与注意要点(字节豆包 | 170点数解答 | 2025-03-19 21:49:55)212
- Python 实战:学生信息列表转字典、遍历、深拷贝及数据修改全流程(GPT | 422点数解答 | 2024-10-29 15:43:54)441
- Python实战:学生成绩列表转字典,深拷贝与数据修改操作全解析(字节豆包 | 254点数解答 | 2024-10-29 16:01:39)435
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)342
- Python Pygame库介绍与简单示例代码(字节豆包 | 583点数解答 | 2026-02-15 10:09:00)27
- Java调用Python接口中文乱码?设置UTF - 8编码一招解决!(讯飞星火 | 263点数解答 | 2024-06-06 17:07:59)414