python球球大作战源码
时间: 2025-01-06 22:30:21 浏览: 6
### Python 编写的游戏《球球大作战》源代码
为了实现一个简单的2D版《球球大作战》,可以采用Pygame库,这是一个非常适合初学者用于开发游戏的Python库。下面是一个简化版本的《球球大作战》源码示例:
#### 安装依赖项
首先需要确保已经安装了`pygame`库。如果尚未安装此库,则可以通过pip工具轻松完成安装。
```bash
pip install pygame
```
#### 游戏核心逻辑
接下来展示的是该游戏的核心部分——定义玩家可控的角色以及AI控制的小球对象,并实现了基本碰撞检测机制来判断是否发生吞噬行为。
```python
import random
import sys
import math
import pygame
class Ball(pygame.sprite.Sprite):
def __init__(self, color, radius, position=(0, 0), velocity=[0, 0]):
super().__init__()
self.image = pygame.Surface([radius * 2, radius * 2])
self.rect = self.image.get_rect()
self.radius = radius
# 绘制圆形图像作为小球外观
pygame.draw.circle(self.image, color, (radius, radius), radius)
self.rect.center = position
self.velocity = velocity
def update(self):
"""更新位置"""
self.rect.x += self.velocity[0]
self.rect.y += self.velocity[1]
def main():
screen_width = 800
screen_height = 600
player_radius = 30
ai_balls_count = 50
score = 0
pygame.init()
size = [screen_width, screen_height]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
all_sprites_list = pygame.sprite.Group()
colors = [(random.randint(0, 255), random.randint(
0, 255), random.randint(0, 255)) for _ in range(ai_balls_count)]
positions = [[random.randrange(player_radius, screen_width - player_radius),
random.randrange(player_radius, screen_height - player_radius)] for _ in range(ai_balls_count)]
velocities = [[random.choice([-2, 2]), random.choice([-2, 2])]
for _ in range(ai_balls_count)]
balls = []
for i in range(len(colors)):
ball = Ball(color=colors[i], radius=random.randint(
10, 20), position=positions[i], velocity=velocities[i])
balls.append(ball)
all_sprites_list.add(ball)
player_ball = Ball((255, 0, 0), player_radius,
(screen_width//2, screen_height//2))
all_sprites_list.add(player_ball)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_ball.velocity[0] = -4
elif keys[pygame.K_RIGHT]:
player_ball.velocity[0] = 4
else:
player_ball.velocity[0] = 0
if keys[pygame.K_UP]:
player_ball.velocity[1] = -4
elif keys[pygame.K_DOWN]:
player_ball.velocity[1] = 4
else:
player_ball.velocity[1] = 0
all_sprites_list.update()
collisions = pygame.sprite.spritecollide(
player_ball, all_sprites_list, dokill=True)
for collision in collisions:
if isinstance(collision, Ball) and id(collision) != id(player_ball):
distance_between_centers_squared = sum([(a-b)**2 for a,b in zip(collision.rect.center,player_ball.rect.center)])
combined_radii_squared = (collision.radius + player_ball.radius)**2
if distance_between_centers_squared <= combined_radii_squared:
score += 1
print(f'Score: {score}')
screen.fill((255, 255, 255))
all_sprites_list.draw(screen)
pygame.display.flip()
clock.tick(60)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nGame terminated by user.")
pygame.quit()
sys.exit()
```
这段程序创建了一个窗口,在其中显示一个小红球代表玩家角色和其他随机颜色大小不一的小球表示敌人。玩家能够利用方向键操控红色小球上下左右移动尝试去接触并“吃掉”其他更小的小球从而获得分数[^1]。
阅读全文