编写一个简单的pygame小游戏
时间: 2023-07-30 22:04:22 浏览: 93
Pygame小游戏:无敌斗牛士
好的,这里是一个简单的Python Pygame小游戏示例,名为“飞机大战”:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 窗口尺寸
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 800
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 创建游戏窗口
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 设置游戏窗口标题
pygame.display.set_caption('飞机大战')
# 加载背景音乐
pygame.mixer.music.load('bgm.mp3')
pygame.mixer.music.play(-1)
# 加载图片
background_img = pygame.image.load('background.png')
player_img = pygame.image.load('player.png')
enemy_img = pygame.image.load('enemy.png')
# 设置字体
font = pygame.font.SysFont(None, 48)
# 定义玩家飞机类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = player_img
self.rect = self.image.get_rect()
self.rect.centerx = WINDOW_WIDTH // 2
self.rect.bottom = WINDOW_HEIGHT - 10
self.speed = 5
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and self.rect.left > 0:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT] and self.rect.right < WINDOW_WIDTH:
self.rect.x += self.speed
# 定义敌机类
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = enemy_img
self.rect = self.image.get_rect()
self.rect.x = random.randrange(WINDOW_WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speed = random.randrange(1, 5)
def update(self):
self.rect.y += self.speed
if self.rect.top > WINDOW_HEIGHT:
self.rect.x = random.randrange(WINDOW_WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speed = random.randrange(1, 5)
# 创建精灵组
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
# 创建玩家飞机
player = Player()
all_sprites.add(player)
# 创建敌机
for i in range(10):
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# 游戏主循环
clock = pygame.time.Clock()
score = 0
running = True
while running:
clock.tick(60)
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新精灵组
all_sprites.update()
# 碰撞检测
hits = pygame.sprite.spritecollide(player, enemies, False)
if hits:
running = False
# 绘制屏幕
game_window.fill(BLACK)
game_window.blit(background_img, (0, 0))
all_sprites.draw(game_window)
# 绘制分数
score_text = font.render(f'Score: {score}', True, WHITE)
game_window.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.update()
# 退出Pygame
pygame.quit()
```
这个游戏的玩法很简单,玩家控制一个飞机躲避敌机并尽可能地存活下去,每撞毁一架敌机得一分。
阅读全文