在窗口中加一个矩形,小球在矩形内运动
时间: 2024-02-13 21:01:32 浏览: 21
好的,这是一个简单的动画效果,可以使用 Python 的 Pygame 库来实现。以下是一个示例代码,可以在 Pygame 环境下运行:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 窗口尺寸
WIDTH, HEIGHT = 640, 480
# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 矩形位置和大小
rect_x, rect_y = 200, 150
rect_width, rect_height = 240, 180
# 小球半径和速度
ball_radius = 10
ball_speed_x, ball_speed_y = 5, 5
# 小球位置
ball_x = random.randint(rect_x + ball_radius, rect_x + rect_width - ball_radius)
ball_y = random.randint(rect_y + ball_radius, rect_y + rect_height - ball_radius)
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
# 关闭窗口
pygame.quit()
exit()
# 移动小球
ball_x += ball_speed_x
ball_y += ball_speed_y
# 检测小球是否碰到矩形边缘
if ball_x - ball_radius < rect_x or ball_x + ball_radius > rect_x + rect_width:
ball_speed_x = -ball_speed_x
if ball_y - ball_radius < rect_y or ball_y + ball_radius > rect_y + rect_height:
ball_speed_y = -ball_speed_y
# 填充窗口背景色
screen.fill((255, 255, 255))
# 绘制矩形和小球
pygame.draw.rect(screen, (0, 0, 0), (rect_x, rect_y, rect_width, rect_height), 2)
pygame.draw.circle(screen, (255, 0, 0), (ball_x, ball_y), ball_radius)
# 更新屏幕
pygame.display.update()
# 控制帧率
pygame.time.Clock().tick(60)
```
这段代码创建了一个大小为 640x480 的窗口,内部有一个矩形和一个小球。小球在矩形内随机运动,碰到边缘时会反弹。每秒钟更新屏幕 60 次,控制帧率为 60 帧。你可以根据需要修改代码中的参数和细节。