pygame小球折返碰撞
时间: 2023-09-10 11:14:48 浏览: 62
你可以使用pygame库来实现小球的折返碰撞效果。下面是一个简单的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口尺寸和标题
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Ball Collision")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义小球的类
class Ball:
def __init__(self, x, y, radius, color):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.speed_x = random.randint(1, 5)
self.speed_y = random.randint(1, 5)
def update(self):
# 更新小球的位置
self.x += self.speed_x
self.y += self.speed_y
# 检测碰撞边界,如果超出窗口范围则折返方向
if self.x <= 0 or self.x >= width:
self.speed_x = -self.speed_x
if self.y <= 0 or self.y >= height:
self.speed_y = -self.speed_y
def draw(self):
# 在窗口上绘制小球
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
# 创建两个小球对象
ball1 = Ball(400, 300, 30, WHITE)
ball2 = Ball(200, 200, 20, WHITE)
# 游戏主循环
running = True
while running:
# 处理退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 清空屏幕
screen.fill(BLACK)
# 更新小球位置和绘制
ball1.update()
ball1.draw()
ball2.update()
ball2.draw()
# 更新屏幕显示
pygame.display.flip()
# 退出游戏
pygame.quit()
```
这个示例中创建了两个小球对象,并使用随机速度让它们在窗口中移动,当小球碰撞到窗口边界时,会折返方向。你可以根据需要调整小球的数量、大小和颜色等参数。希望能对你有所帮助!