下面是一个简单的Python飞机大战游戏的源码示例:
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏界面大小、背景图片及标题
screen = pygame.display.set_mode((480, 640))
background = pygame.image.load('background.png').convert()
pygame.display.set_caption('飞机大战')
# 加载玩家飞机图片
player = pygame.image.load('player.png').convert_alpha()
player_rect = player.get_rect()
player_rect.topleft = [200, 500]
# 加载敌机图片
enemy = pygame.image.load('enemy.png').convert_alpha()
enemy_rect = enemy.get_rect()
# 创建子弹列表
bullet_list = []
bullet = pygame.image.load('bullet.png').convert_alpha()
# 设置敌机参数
enemy_rect.topleft = [random.randint(0, 480 - enemy_rect.width), 0]
enemy_speed = 2
# 设置得分
score = 0
font = pygame.font.Font(None, 32)
# 设置游戏帧率
clock = pygame.time.Clock()
# 游戏主循环
running = True
while running:
# 控制游戏最大帧率为60
clock.tick(60)
# 绘制背景
screen.blit(background, (0, 0))
# 绘制玩家飞机和敌机
screen.blit(player, player_rect)
screen.blit(enemy, enemy_rect)
# 移动玩家飞机
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_UP]:
player_rect.top -= 5
if key_pressed[pygame.K_DOWN]:
player_rect.top += 5
if key_pressed[pygame.K_LEFT]:
player_rect.left -= 5
if key_pressed[pygame.K_RIGHT]:
player_rect.left += 5
# 控制玩家飞机不超出屏幕范围
if player_rect.left < 0:
player_rect.left = 0
if player_rect.right > 480:
player_rect.right = 480
if player_rect.top < 0:
player_rect.top = 0
if player_rect.bottom > 640:
player_rect.bottom = 640
# 移动敌机
enemy_rect.top += enemy_speed
if enemy_rect.top > 640:
enemy_rect.top = 0
enemy_rect.left = random.randint(0, 480 - enemy_rect.width)
# 发射子弹
if key_pressed[pygame.K_SPACE]:
bullet_rect = bullet.get_rect()
bullet_rect.centerx = player_rect.centerx
bullet_rect.bottom = player_rect.top
bullet_list.append(bullet_rect)
for b in bullet_list:
b.top -= 5
if b.top < 0:
bullet_list.remove(b)
# 检测子弹与敌机的碰撞
for b in bullet_list:
if b.colliderect(enemy_rect):
bullet_list.remove(b)
enemy_rect.topleft = [random.randint(0, 480 - enemy_rect.width), 0]
score += 1
# 绘制子弹
for b in bullet_list:
screen.blit(bullet, b)
# 绘制得分
score_text = font.render('Score: {}'.format(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.update()
# 处理游戏退出事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 退出游戏
pygame.quit()
注意:以上代码仅为一个简单的示例,可能存在一些不足之处。你可以根据自己的需求对代码进行更改和优化。此外,你还需要准备好游戏所需的图片资源,并将其保存在与代码文件相同的目录下。