生产一个大球吃小球的代码
时间: 2024-03-09 07:48:02 浏览: 212
基于 Java 实现的大球吃小球游戏
以下是一个简单的 Python 代码实现:
```python
import pygame, random
# 定义颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 初始化 Pygame
pygame.init()
# 设置窗口尺寸
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置窗口标题
pygame.display.set_caption('大球吃小球')
# 创建大球类
class Ball(pygame.sprite.Sprite):
def __init__(self, color, radius):
super().__init__()
self.color = color
self.radius = radius
self.image = pygame.Surface([radius * 2, radius * 2])
self.image.fill(WHITE)
pygame.draw.circle(self.image, color, [radius, radius], radius)
self.rect = self.image.get_rect()
def update(self):
pass
# 创建小球类
class SmallBall(Ball):
def __init__(self, color, radius, speed):
super().__init__(color, radius)
self.speed = speed
self.rect.x = random.randrange(SCREEN_WIDTH - radius * 2)
self.rect.y = random.randrange(SCREEN_HEIGHT - radius * 2)
def update(self):
self.rect.x += self.speed[0]
self.rect.y += self.speed[1]
if self.rect.right > SCREEN_WIDTH or self.rect.left < 0:
self.speed[0] = -self.speed[0]
if self.rect.bottom > SCREEN_HEIGHT or self.rect.top < 0:
self.speed[1] = -self.speed[1]
# 创建大球对象
big_ball = Ball(RED, 50)
big_ball.rect.x = SCREEN_WIDTH / 2 - 50
big_ball.rect.y = SCREEN_HEIGHT / 2 - 50
# 创建小球列表
small_balls = pygame.sprite.Group()
# 创建多个小球对象
for i in range(25):
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
radius = random.randint(10, 20)
speed = [random.randint(-5, 5), random.randint(-5, 5)]
small_ball = SmallBall(color, radius, speed)
small_balls.add(small_ball)
# 创建时钟对象
clock = pygame.time.Clock()
# 游戏主循环
done = False
while not done:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 获取鼠标位置
pos = pygame.mouse.get_pos()
# 移动大球
big_ball.rect.x = pos[0]
big_ball.rect.y = pos[1]
# 检测大球是否吃掉小球
small_balls_hit = pygame.sprite.spritecollide(big_ball, small_balls, True)
for small_ball in small_balls_hit:
# 创建新的小球
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
radius = random.randint(10, 20)
speed = [random.randint(-5, 5), random.randint(-5, 5)]
small_ball = SmallBall(color, radius, speed)
small_balls.add(small_ball)
# 更新小球位置
small_balls.update()
# 绘制屏幕
screen.fill(BLACK)
screen.blit(big_ball.image, big_ball.rect)
small_balls.draw(screen)
pygame.display.flip()
# 控制帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
运行以上代码,即可看到一个大球吃小球的小游戏界面。玩家可以通过鼠标控制大球移动,当大球碰到小球时,小球会被吃掉,并在其位置生成一个新的小球。
阅读全文