import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏窗口的宽度和高度
screen_width = 800
screen_height = 600
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("飞机大战")
# 加载背景图片
background = pygame.image.load("background.jpg")
# 加载玩家飞机图片
player_img = pygame.image.load("player.png")
player_width = player_img.get_width()
player_height = player_img.get_height()
player_x = (screen_width - player_width) // 2
player_y = screen_height - player_height - 10
# 加载敌人飞机图片
enemy_img = pygame.image.load("enemy.png")
enemy_width = enemy_img.get_width()
enemy_height = enemy_img.get_height()
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = -enemy_height
enemy_speed = 3
# 记录分数
score = 0
# 创建字体对象
font = pygame.font.Font(None, 36)
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动玩家飞机
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= 5
if keys[pygame.K_RIGHT]:
player_x += 5
if keys[pygame.K_UP]:
player_y -= 5
if keys[pygame.K_DOWN]:
player_y += 5
# 边界检测
if player_x < 0:
player_x = 0
if player_x > screen_width - player_width:
player_x = screen_width - player_width
if player_y < 0:
player_y = 0
if player_y > screen_height - player_height:
player_y = screen_height - player_height
# 移动敌人飞机
enemy_y += enemy_speed
# 碰撞检测
if player_x < enemy_x + enemy_width and player_x + player_width > enemy_x and player_y < enemy_y + enemy_height and player_y + player_height > enemy_y:
score += 1
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = -enemy_height
# 绘制背景
screen.blit(background, (0, 0))
# 绘制玩家飞机
screen.blit(player_img, (player_x, player_y))
# 绘制敌人飞机
screen.blit(enemy_img, (enemy_x, enemy_y))
# 绘制分数
score_text = font.render("分数: " + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()