以下是一个简单的Python球球游戏代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
screen_width = 800
screen_height = 600
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("球球游戏")
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义球类
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(-5, 5)
self.speed_y = random.randint(-5, 5)
def move(self):
self.x += self.speed_x
self.y += self.speed_y
# 碰到边界反弹
if self.x - self.radius < 0 or self.x + self.radius > screen_width:
self.speed_x *= -1
if self.y - self.radius < 0 or self.y + self.radius > screen_height:
self.speed_y *= -1
def draw(self):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
# 创建球列表
balls = []
for i in range(10):
x = random.randint(50, screen_width - 50)
y = random.randint(50, screen_height - 50)
radius = random.randint(20, 50)
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
ball = Ball(x, y, radius, color)
balls.append(ball)
# 游戏循环
game_over = False
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 移动球
for ball in balls:
ball.move()
# 检测球的碰撞
for i in range(len(balls)):
for j in range(i + 1, len(balls)):
dx = balls[i].x - balls[j].x
dy = balls[i].y - balls[j].y
distance = ((dx ** 2) + (dy ** 2)) ** 0.5
if distance < balls[i].radius + balls[j].radius:
balls[i].speed_x *= -1
balls[i].speed_y *= -1
balls[j].speed_x *= -1
balls[j].speed_y *= -1
# 绘制背景
screen.fill(white)
# 绘制球
for ball in balls:
ball.draw()
# 更新屏幕
pygame.display.update()
# 设置帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
这个游戏会生成多个随机大小和颜色的球,球会在屏幕中移动,并且会相互碰撞。当球碰撞时,它们会反弹。游戏会一直运行直到用户关闭游戏窗口。