用 Python 画一个动态爱心
时间: 2024-12-22 22:29:40 浏览: 4
在Python中,我们可以利用pygame库来创建一个简单的动态爱心动画。下面是一个基本的示例,展示如何在一个窗口上绘制一个随时间移动的爱心形状:
```python
import pygame
import sys
# 初始化Pygame
pygame.init()
# 设置窗口大小和颜色背景
window_size = (400, 400)
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("Dynamic Heart Animation")
background_color = (255, 255, 255) # 白色背景
# 爱心形状的坐标和运动速度
heart_pos = [window_size[0] // 2, window_size[1] // 2]
heart_speed = [2, 2]
def draw_heart():
heart_radius = 50
x, y = heart_pos
pygame.draw.polygon(screen, (255, 0, 0), [
(x - heart_radius, y + heart_radius),
(x, y + heart_radius * 2),
(x + heart_radius, y + heart_radius),
(x + heart_radius, y - heart_radius),
(x, y - heart_radius * 2),
(x - heart_radius, y - heart_radius),
])
# 游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新爱心的位置
heart_pos[0] += heart_speed[0]
heart_pos[1] += heart_speed[1]
# 如果爱心超出屏幕边界,则改变方向
if heart_pos[0] < heart_radius or heart_pos[0] > window_size[0] - heart_radius:
heart_speed[0] = -heart_speed[0]
if heart_pos[1] < heart_radius or heart_pos[1] > window_size[1] - heart_radius:
heart_speed[1] = -heart_speed[1]
screen.fill(background_color)
draw_heart()
pygame.display.flip()
# 关闭游戏
pygame.quit()
sys.exit()
```
阅读全文