以下是一个简单的用Python编写的飞机大战游戏的源代码:
python">import pygame
import random# 初始化游戏
pygame.init()# 设置游戏窗口的尺寸
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))# 设置游戏标题
pygame.display.set_caption("飞机大战")# 加载背景图片
background = pygame.image.load("background.png")# 加载玩家飞机图片
player_image = pygame.image.load("player.png")
player_rect = player_image.get_rect()
player_rect.topleft = ((screen_width - player_rect.width) // 2, screen_height - player_rect.height - 20)# 加载敌机图片
enemy_image = pygame.image.load("enemy.png")# 音效
bullet_sound = pygame.mixer.Sound("bullet.wav")
explosion_sound = pygame.mixer.Sound("explosion.wav")
pygame.mixer.music.load("background_music.mp3")
pygame.mixer.music.play(-1)# 设置游戏帧率
clock = pygame.time.Clock()# 玩家子弹列表
player_bullets = []# 敌机列表
enemies = []
enemy_frequency = 0# 设置游戏分数
score = 0
font = pygame.font.SysFont(None, 36)# 游戏结束标志
game_over = False# 游戏主循环
while not game_over:# 处理游戏事件for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_SPACE:bullet_sound.play()player_bullet = pygame.Rect(player_rect.left + player_rect.width // 2 - 2, player_rect.top - 10, 4, 10)player_bullets.append(player_bullet)# 移动玩家飞机keys = pygame.key.get_pressed()if keys[pygame.K_LEFT] and player_rect.left > 0:player_rect.left -= 5if keys[pygame.K_RIGHT] and player_rect.right < screen_width:player_rect.left += 5if keys[pygame.K_UP] and player_rect.top > 0:player_rect.top -= 5if keys[pygame.K_DOWN] and player_rect.bottom < screen_height:player_rect.top += 5# 绘制游戏界面screen.blit(background, (0, 0))screen.blit(player_image, player_rect)# 绘制玩家子弹for bullet in player_bullets:bullet.top -= 10if bullet.top < -10:player_bullets.remove(bullet)pygame.draw.rect(screen, (255, 0, 0), bullet)# 生成敌机if enemy_frequency % 50 == 0:enemy_rect = enemy_image.get_rect()enemy_rect.topleft = (random.randint(0, screen_width - enemy_rect.width), -enemy_rect.height)enemies.append(enemy_rect)enemy_frequency += 1# 移动敌机for enemy in enemies:enemy.top += 5if enemy.top > screen_height:enemies.remove(enemy)# 检测子弹和敌机碰撞for bullet in player_bullets:for enemy in enemies:if bullet.colliderect(enemy):explosion_sound.play()enemies.remove(enemy)player_bullets.remove(bullet)score += 10# 绘制敌机for enemy in enemies:screen.blit(enemy_image, enemy)# 显示分数score_text = font.render("Score: " + str(score), True, (255, 255, 0))screen.blit(score_text, (10, 10))# 检测玩家飞机和敌机碰撞for enemy in enemies:if player_rect.colliderect(enemy):game_over = True# 更新游戏界面pygame.display.update()# 控制游戏帧率clock.tick(60)# 游戏结束,显示最终得分
game_over_text = font.render("Game Over! Your Score: " + str(score), True, (255, 0, 0))
screen.blit(game_over_text, (screen_width // 2 - 150, screen_height // 2))
pygame.display.update()# 延迟退出游戏
pygame.time.wait(2000)# 退出游戏
pygame.quit()
请注意,这只是一个简单的示例代码,游戏中可能还有许多不完善的地方。你可以根据自己的需求进行修改和优化。此外,你还需要准备飞机、背景、子弹、敌机的图像和音效文件,并将它们与代码放在同一目录下。然后,你可以使用Python解释器来运行代码并开始游戏。