基于pygame的Python小游戏
时间: 2023-11-05 22:03:01 浏览: 88
pygame Python 小游戏
好的,我可以给你介绍一个基于pygame的Python小游戏——Flappy Bird。
Flappy Bird是一款非常经典的手机游戏,这里我们将使用pygame模块重新创建一个简化版的Flappy Bird游戏。
首先,你需要安装pygame模块。在控制台中运行以下命令:
```
pip install pygame
```
接下来,我们需要导入pygame和其他必要的模块:
```python
import pygame
import random
import sys
```
然后,我们需要定义一些常量,包括窗口大小、背景颜色、地面高度等:
```python
WIDTH = 288
HEIGHT = 512
FPS = 60
GROUND_HEIGHT = 112
BACKGROUND_COLOR = (153, 204, 255)
```
接下来,我们需要定义游戏中的各种元素,包括鸟、管道、地面等:
```python
class Bird(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("bird.png").convert_alpha()
self.rect = self.image.get_rect(center=(50, HEIGHT // 2))
self.vel = 0
self.gravity = 0.5
def update(self):
self.vel += self.gravity
self.rect.y += self.vel
class Pipe(pygame.sprite.Sprite):
def __init__(self, height):
super().__init__()
self.image = pygame.image.load("pipe.png").convert_alpha()
self.image = pygame.transform.scale(self.image, (52, height))
self.rect = self.image.get_rect(midtop=(WIDTH, 0))
self.vel = 2
def update(self):
self.rect.x -= self.vel
class Ground(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("ground.png").convert_alpha()
self.rect = self.image.get_rect(bottomleft=(0, HEIGHT))
self.vel = 2
def update(self):
self.rect.x -= self.vel
```
我们还需要定义一些辅助函数,比如创建管道、检测碰撞等:
```python
def create_pipe():
pipe_height = random.randint(100, HEIGHT - GROUND_HEIGHT - 200)
top_pipe = Pipe(pipe_height)
bottom_pipe = Pipe(HEIGHT - GROUND_HEIGHT - pipe_height - 80)
bottom_pipe.rect.y = top_pipe.rect.bottom + 80
return top_pipe, bottom_pipe
def check_collision(bird, pipes):
if bird.rect.bottom >= HEIGHT - GROUND_HEIGHT:
return True
for pipe in pipes:
if bird.rect.colliderect(pipe.rect):
return True
return False
```
最后,我们可以开始编写主游戏循环:
```python
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
bird = Bird()
pipes = pygame.sprite.Group()
ground = Ground()
score = 0
font = pygame.font.Font(None, 36)
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird.vel = -8
if len(pipes) < 3:
pipe_pair = create_pipe()
pipes.add(pipe_pair)
bird.update()
pipes.update()
ground.update()
for pipe in pipes:
if pipe.rect.right < 0:
pipes.remove(pipe)
score += 1
if check_collision(bird, pipes):
pygame.quit()
sys.exit()
screen.fill(BACKGROUND_COLOR)
pipes.draw(screen)
screen.blit(ground.image, ground.rect)
screen.blit(bird.image, bird.rect)
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
pygame.display.update()
```
这就是一个简化版的Flappy Bird游戏,你可以根据自己的需求进行修改和扩展。
阅读全文