用python编写愤怒的小鸟游戏
时间: 2023-05-11 19:04:32 浏览: 199
非常感谢您的提问,以下是用 Python 编写愤怒的小鸟游戏的代码:
```python
import pygame
import pymunk
import random
# 初始化 Pygame
pygame.init()
# 设置窗口大小
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
# 创建空间
space = pymunk.Space()
space.gravity = (0.0, -900.0)
# 添加地面
body = pymunk.Body(body_type=pymunk.Body.STATIC)
shape = pymunk.Segment(body, (0, 0), (width, 0), 0.0)
shape.friction = 1.0
space.add(shape)
# 添加小鸟
bird_body = pymunk.Body(1, 100)
bird_shape = pymunk.Circle(bird_body, 25)
bird_shape.elasticity = 0.95
bird_shape.friction = 1.0
bird_body.position = (100, height / 2)
space.add(bird_body, bird_shape)
# 添加障碍物
obstacles = []
for i in range(5):
x = random.randint(200, 500)
y = random.randint(100, 400)
body = pymunk.Body(body_type=pymunk.Body.STATIC)
shape = pymunk.Poly.create_box(body, (50, 50))
shape.friction = 1.0
body.position = (x, y)
space.add(body, shape)
obstacles.append(shape)
# 游戏循环
clock = pygame.time.Clock()
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 更新物理引擎
space.step(1 / 60.0)
# 绘制场景
screen.fill((255, 255, 255))
for obstacle in obstacles:
pygame.draw.polygon(screen, (0, 0, 0), obstacle.get_vertices())
pygame.draw.circle(screen, (255, 0, 0), bird_body.position, 25)
pygame.display.flip()
# 控制小鸟
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
bird_body.apply_impulse_at_local_point((0, 10000))
if bird_body.position.y < 0:
pygame.quit()
exit()
# 控制障碍物
for obstacle in obstacles:
if obstacle.body.position.x < -50:
x = random.randint(700, 1000)
y = random.randint(100, 400)
obstacle.body.position = (x, y)
# 控制帧率
clock.tick(60)
```
希望这个代码对您有所帮助!
阅读全文