import pygame
import sys
import random# 初始化 Pygame
pygame.init()# 设置窗口尺寸
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("雷电战机")# 设置颜色
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
WHITE = (255, 255, 255)# 战机初始位置
plane_pos = [WIDTH // 2, HEIGHT - 100] # 战机的中心位置# 敌机列表
enemies = []
enemy_speed = 5 # 敌机移动速度# 积分
score = 0# 子弹类
class Bullet:def __init__(self, x, y, speed, damage):self.x = xself.y = yself.speed = speedself.damage = damagedef move(self):self.y -= self.speed # 子弹向上移动def draw(self):pygame.draw.rect(screen, YELLOW, (self.x - 2, self.y, 4, 10)) # 绘制子弹# 创建敌机
def create_enemy():x = random.randint(0, WIDTH - 30) # 随机生成敌机的 x 坐标enemies.append([x, 0]) # 敌机初始位置在屏幕顶部# 创建子弹
def create_bullet():x = plane_pos[0] # 子弹的 x 坐标与战机相同y = plane_pos[1] - 20 # 子弹的 y 坐标在战机上方# 随机选择子弹类型bullet_type = random.choice([{"speed": 10, "damage": 1}, # 普通子弹{"speed": 15, "damage": 2}, # 强力子弹{"speed": 5, "damage": 0.5} # 弱力子弹])return Bullet(x, y, bullet_type["speed"], bullet_type["damage"])# 游戏主循环
bullets = [] # 子弹列表
while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()# 获取按键状态keys = pygame.key.get_pressed()if keys[pygame.K_LEFT] and plane_pos[0] > 0:plane_pos[0] -= 5 # 向左移动if keys[pygame.K_RIGHT] and plane_pos[0] < WIDTH:plane_pos[0] += 5 # 向右移动if keys[pygame.K_UP] and plane_pos[1] > 0:plane_pos[1] -= 5 # 向上移动if keys[pygame.K_DOWN] and plane_pos[1] < HEIGHT:plane_pos[1] += 5 # 向下移动if keys[pygame.K_SPACE]: # 按空格键发射子弹bullets.append(create_bullet()) # 添加新子弹到列表# 填充背景screen.fill(BLACK)# 绘制三角形作为战机point1 = (plane_pos[0], plane_pos[1] - 20) # 顶点point2 = (plane_pos[0] - 15, plane_pos[1] + 10) # 左下角point3 = (plane_pos[0] + 15, plane_pos[1] + 10) # 右下角pygame.draw.polygon(screen, RED, [point1, point2, point3]) # 绘制战机# 创建敌机if random.randint(1, 30) == 1: # 每30帧大约生成一个敌机create_enemy()# 更新并绘制敌机for enemy in enemies:enemy[1] += enemy_speed # 敌机向下移动# 绘制敌机(使用三角形表示)enemy_points = [(enemy[0], enemy[1] - 20), # 顶点(enemy[0] - 15, enemy[1] + 10), # 左下角(enemy[0] + 15, enemy[1] + 10) # 右下角]pygame.draw.polygon(screen, GREEN, enemy_points) # 绘制敌机# 更新并绘制子弹for bullet in bullets[:]: # 使用切片以避免修改列表时出错bullet.move() # 移动子弹bullet.draw() # 绘制子弹# 检查子弹与敌机的碰撞bullets = [bullet for bullet in bullets if bullet.y > 0] # 移除超出屏幕的子弹for bullet in bullets[:]: # 使用切片以避免修改列表时出错for enemy in enemies[:]: # 使用切片以避免修改列表时出错if (bullet.x > enemy[0] - 15 and bullet.x < enemy[0] + 15 andbullet.y < enemy[1] + 10 and bullet.y > enemy[1] - 20):bullets.remove(bullet) # 移除子弹enemies.remove(enemy) # 移除敌机score += 10 * bullet.damage # 根据子弹的伤害增加积分break # 退出内层循环# 移除超出屏幕的敌机enemies = [enemy for enemy in enemies if enemy[1] < HEIGHT]# 显示当前积分font = pygame.font.Font(None, 36) # 创建字体对象score_surface = font.render(f"Score: {int(score)}", True, WHITE) # 渲染积分文本screen.blit(score_surface, (10, 10)) # 在屏幕上绘制积分# 更新显示pygame.display.flip()# 控制帧率pygame.time.Clock().tick(60)
实现效果: