python弹球游戏pygame
时间: 2024-01-19 10:18:21 浏览: 40
以下是一个简单的Python弹球游戏的示例代码,使用了Pygame库:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小
size = width, height = 800, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pong")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 定义球的初始位置和速度
ball_pos = [random.randint(100, 700), random.randint(100, 500)]
ball_speed = [random.randint(2, 4), random.randint(2, 4)]
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动球
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
# 碰撞检测
if ball_pos[0] < 0 or ball_pos[0] > width:
ball_speed[0] = -ball_speed[0]
if ball_pos[1] < 0 or ball_pos[1] > height:
ball_speed[1] = -ball_speed[1]
# 填充背景色
screen.fill(BLACK)
# 绘制球
pygame.draw.circle(screen, WHITE, ball_pos, 20)
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
```
这个示例代码实现了一个简单的弹球游戏,球会在窗口中来回移动,并在碰到窗口边缘时反弹。你可以根据自己的需求进行修改和扩展。