酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

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]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]