import pygame
import random
import sys

# 初始化
pygame.init()
WIDTH, HEIGHT = 480, 640
FPS = 60

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("简易射击游戏")
clock = pygame.time.Clock()

# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
PLAYER_COLOR = (50, 200, 255)
ENEMY_COLOR = (255, 80, 80)
BULLET_COLOR = (255, 255, 0)

# 玩家设置
PLAYER_W, PLAYER_H = 50, 30
PLAYER_SPEED = 5

# 子弹设置
BULLET_W, BULLET_H = 4, 10
BULLET_SPEED = -8
FIRE_DELAY = 300  # 毫秒

# 敌人设置
ENEMY_W, ENEMY_H = 40, 28
ENEMY_SPEED_MIN = 1
ENEMY_SPEED_MAX = 2.5
ENEMY_SPAWN_DELAY = 800  # 毫秒

# 字体
font = pygame.font.SysFont(None, 36)

# 游戏对象类
class Player:
    def __init__(self):
        self.rect = pygame.Rect((WIDTH - PLAYER_W) // 2, HEIGHT - PLAYER_H - 10, PLAYER_W, PLAYER_H)
        self.speed = PLAYER_SPEED
        self.last_shot = 0

    def move(self, dx):
        self.rect.x += dx * self.speed
        # 限制在屏幕内
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH

    def can_shoot(self):
        return pygame.time.get_ticks() - self.last_shot >= FIRE_DELAY

    def shoot(self):
        self.last_shot = pygame.time.get_ticks()
        # 子弹从玩家顶部中心发射
        bx = self.rect.centerx - BULLET_W // 2
        by = self.rect.top - BULLET_H
        return Bullet(bx, by)

    def draw(self, surf):
        pygame.draw.rect(surf, PLAYER_COLOR, self.rect)


class Bullet:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, BULLET_W, BULLET_H)
        self.speed = BULLET_SPEED

    def update(self):
        self.rect.y += self.speed

    def off_screen(self):
        return self.rect.bottom < 0

    def draw(self, surf):
        pygame.draw.rect(surf, BULLET_COLOR, self.rect)


class Enemy:
    def __init__(self):
        x = random.randint(0, WIDTH - ENEMY_W)
        y = -ENEMY_H
        self.rect = pygame.Rect(x, y, ENEMY_W, ENEMY_H)
        self.speed = random.uniform(ENEMY_SPEED_MIN, ENEMY_SPEED_MAX)

    def update(self):
        self.rect.y += self.speed

    def off_screen(self):
        return self.rect.top > HEIGHT

    def draw(self, surf):
        pygame.draw.rect(surf, ENEMY_COLOR, self.rect)


def draw_text(surf, text, x, y, color=WHITE):
    img = font.render(text, True, color)
    surf.blit(img, (x, y))


def main():
    player = Player()
    bullets = []
    enemies = []
    score = 0
    running = True
    game_over = False

    # 定时生成敌人事件（也可以用手动计时）
    SPAWNENEMY = pygame.USEREVENT + 1
    pygame.time.set_timer(SPAWNENEMY, ENEMY_SPAWN_DELAY)

    while running:
        dt = clock.tick(FPS)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == SPAWNENEMY and not game_over:
                enemies.append(Enemy())

        # 输入处理
        keys = pygame.key.get_pressed()
        if not game_over:
            dx = 0
            if keys[pygame.K_LEFT] or keys[pygame.K_a]:
                dx = -1
            if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
                dx = 1
            player.move(dx)

            if keys[pygame.K_SPACE] and player.can_shoot():
                bullets.append(player.shoot())

        # 更新对象
        if not game_over:
            for b in bullets:
                b.update()
            for e in enemies:
                e.update()

            # 移除屏幕外的子弹
            bullets = [b for b in bullets if not b.off_screen()]

            # 子弹与敌人碰撞检测
            for b in bullets[:]:
                for e in enemies[:]:
                    if b.rect.colliderect(e.rect):
                        bullets.remove(b)
                        enemies.remove(e)
                        score += 10
                        break

            # 敌人到达底部或与玩家碰撞：游戏结束
            for e in enemies:
                if e.rect.colliderect(player.rect) or e.off_screen():
                    game_over = True
                    break

            # 可选：随分数提高敌人刷新速度或数量（简单示例）
            # 每 100 分提升敌人速度上限
            # 可以调整 ENEMY_SPAWN_DELAY 或 ENEMY_SPEED_MAX 动态变化

        # 绘制
        screen.fill(BLACK)
        player.draw(screen)
        for b in bullets:
            b.draw(screen)
        for e in enemies:
            e.draw(screen)

        draw_text(screen, f"Score: {score}", 10, 10)

        if game_over:
            draw_text(screen, "GAME OVER", WIDTH // 2 - 80, HEIGHT // 2 - 20)
            draw_text(screen, "Press R to restart or Q to quit", WIDTH // 2 - 180, HEIGHT // 2 + 20)

            # 重启或退出
            if keys[pygame.K_r]:
                # 重置游戏状态
                player = Player()
                bullets = []
                enemies = []
                score = 0
                game_over = False
            if keys[pygame.K_q]:
                running = False

        pygame.display.flip()

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()