球球大作战代码python
时间: 2023-11-12 15:01:59 浏览: 239
球球大作战是一款经典的多人在线游戏,使用Python编写代码可以实现这个游戏。下面给出一个简单的示例代码:
```python
import pygame
import random
# 游戏窗口大小
WIDTH = 800
HEIGHT = 600
# 定义球类
class Ball:
def __init__(self, x, y, radius, color, speed):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.speed = speed
def move(self):
self.x += self.speed[0]
self.y += self.speed[1]
# 球碰到墙壁时反弹
if self.x - self.radius <= 0 or self.x + self.radius >= WIDTH:
self.speed[0] = -self.speed[0]
if self.y - self.radius <= 0 or self.y + self.radius >= HEIGHT:
self.speed[1] = -self.speed[1]
def draw(self, screen):
pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)
# 初始化游戏
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("球球大作战")
# 创建球列表
balls = []
for _ in range(10):
x = random.randint(0, WIDTH)
y = random.randint(0, HEIGHT)
radius = random.randint(10, 50)
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
speed = [random.randint(1, 5), random.randint(1, 5)]
ball = Ball(x, y, radius, color, speed)
balls.append(ball)
# 游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255)) # 清屏
# 移动和绘制球
for ball in balls:
ball.move()
ball.draw(screen)
pygame.display.flip() # 更新屏幕
pygame.quit()
```
这段代码使用pygame库创建了游戏窗口,并定义了Ball类来表示游戏中的球。游戏循环中,每一帧更新球的位置和绘制球到屏幕上。初始化时创建了10个随机大小、颜色和速度的球。
阅读全文