pygame碰到边缘就反弹
时间: 2023-12-19 09:31:51 浏览: 204
以下是一个简单的pygame碰到边缘就反弹的例子:
```python
import pygame
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置小球的初始位置和速度
ball_pos = [50, 50]
ball_speed = [5, 5]
# 游戏循环
while True:
# 处理退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 移动小球
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
# 碰到左右边缘反弹
if ball_pos[0] < 0 or ball_pos[0] > screen_width:
ball_speed[0] = -ball_speed[0]
# 碰到上下边缘反弹
if ball_pos[1] < 0 or ball_pos[1] > screen_height:
ball_speed[1] = -ball_speed[1]
# 填充背景色
screen.fill((230, 230, 230))
# 绘制小球
pygame.draw.circle(screen, (255, 0, 0), ball_pos, 20)
# 更新屏幕
pygame.display.update()
```
阅读全文