import pygame
import sys
import random
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 = x
self.y = y
self.speed = speed
self.damage = damage
def 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)
enemies.append([x, 0])
def create_bullet():
x = plane_pos[0]
y = plane_pos[1] - 20
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:
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 and
bullet.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)
实现效果: