import pygame
import random
# 初始化 Pygame 库
pygame.init()
# 定义窗口大小和标题
SCREEN_WIDTH, SCREEN_HEIGHT = 480, 800
SCREEN_TITLE = '雷霆战机'
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption(SCREEN_TITLE)
# 定义背景图像
background_img = pygame.image.load('background.png').convert()
# 定义玩家飞机图像和位置
player_img = pygame.image.load('player.png').convert_alpha()
player_x = SCREEN_WIDTH // 2
player_y = SCREEN_HEIGHT - player_img.get_height() - 50
# 定义敌机图像列表和出现的位置列表
enemy_imgs = [
pygame.image.load('enemy1.png').convert_alpha(),
pygame.image.load('enemy2.png').convert_alpha(),
pygame.image.load('enemy3.png').convert_alpha()
]
enemy_positions = [
(SCREEN_WIDTH // 2 - enemy_imgs[0].get_width() // 2, -enemy_imgs[0].get_height()),
(SCREEN_WIDTH // 2 - enemy_imgs[1].get_width() // 2, -enemy_imgs[1].get_height() * 3),
(SCREEN_WIDTH // 2 - enemy_imgs[2].get_width() // 2, -enemy_imgs[2].get_height() * 5)
]
enemies = []
# 定义子弹图像和子弹列表
bullet_img = pygame.image.load('bullet.png').convert_alpha()
bullets = []
# 定义计时器和分数
clock = pygame.time.Clock()
score = 0
# 定义游戏循环
while True:
# 处理窗口事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
# 检测键盘按键
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_LEFT] and player_x >= 5:
player_x -= 5
elif pressed_keys[pygame.K_RIGHT] and player_x <= SCREEN_WIDTH - player_img.get_width() - 5:
player_x += 5
elif pressed_keys[pygame.K_SPACE]:
bullets.append(
{'rect': pygame.Rect(player_x + player_img.get_width() // 2 - bullet_img.get_width() // 2,
player_y - bullet_img.get_height(), bullet_img.get_width(),
bullet_img.get_height()), 'speed': -10})
# 绘制背景
screen.blit(background_img, (0, 0))
# 绘制玩家飞机
screen.blit(player_img, (player_x, player_y))
# 绘制敌机
if random.randint(1, 50) == 1:
enemy_index = random.randint(0, len(enemy_imgs) - 1)
enemies.append({'rect': pygame.Rect(enemy_positions[enemy_index][0], enemy_positions[enemy_index][1],
enemy_imgs[enemy_index].get_width(), enemy_imgs[enemy_index].get_height()),
'img': enemy_imgs[enemy_index], 'speed': random.randint(1, 3)})
for enemy in enemies:
screen.blit(enemy['img'], enemy['rect'])
enemy['rect'].move_ip(0, enemy['speed'])
if enemy['rect'].bottom > SCREEN_HEIGHT:
enemies.remove(enemy)
# 绘制子弹
for bullet in bullets:
screen.blit(bullet_img, bullet['rect'])
bullet['rect'].move_ip(0, bullet['speed'])
if bullet['rect'].top < 0:
bullets.remove(bullet)
# 检测子弹和敌机的碰撞
for bullet in bullets:
for enemy in enemies:
if bullet['rect'].colliderect(enemy['rect']):
bullets.remove(bullet)
enemies.remove(enemy)
score += 10
# 绘制分数
font = pygame.font.SysFont('arial', 24)
score_text = font.render('Score: {}'.format(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新窗口
pygame.display.update()
# 设置游戏帧率
clock.tick(60)