import pygame
import sys
import random
import math

pygame.init()

# 窗口参数
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D移动射击游戏")

# 颜色常量
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (60, 160, 255)
RED = (255, 60, 60)
GREEN = (60, 255, 100)

# 玩家配置
player_x = WIDTH // 2
player_y = HEIGHT // 2
player_radius = 22
player_speed = 5
shoot_cd = 180  # 射击冷却(毫秒)
last_shot_time = 0

# 子弹配置
bullets = []
bullet_speed = 12
bullet_radius = 5

# 敌人配置
enemies = []
enemy_radius = 18
enemy_speed = 2.2
spawn_timer = 0
spawn_interval = 1200

score = 0
# ========== 修复字体部分 ==========
try:
    font = pygame.font.SysFont("arial", 36)
except:
    font = pygame.font.Font(None, 36)

clock = pygame.time.Clock()
game_over = False

running = True
while running:
    current_time = pygame.time.get_ticks()
    clock.tick(60)
    screen.fill(BLACK)

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # 游戏结束按空格重启
        if event.type == pygame.KEYDOWN and game_over:
            if event.key == pygame.K_SPACE:
                # 重置所有数据
                player_x = WIDTH // 2
                player_y = HEIGHT // 2
                bullets.clear()
                enemies.clear()
                score = 0
                game_over = False

    if not game_over:
        # WASD移动
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w] and player_y - player_radius > 0:
            player_y -= player_speed
        if keys[pygame.K_s] and player_y + player_radius < HEIGHT:
            player_y += player_speed
        if keys[pygame.K_a] and player_x - player_radius > 0:
            player_x -= player_speed
        if keys[pygame.K_d] and player_x + player_radius < WIDTH:
            player_x += player_speed

        # 鼠标左键射击
        mouse_state = pygame.mouse.get_pressed()
        if mouse_state[0]:
            if current_time - last_shot_time > shoot_cd:
                mx, my = pygame.mouse.get_pos()
                dx = mx - player_x
                dy = my - player_y
                distance = math.hypot(dx, dy)
                if distance > 1:
                    vx = dx / distance * bullet_speed
                    vy = dy / distance * bullet_speed
                    bullets.append([player_x, player_y, vx, vy])
                    last_shot_time = current_time

        # 更新子弹
        new_bullet_list = []
        for bullet in bullets:
            bx, by, vx, vy = bullet
            bx += vx
            by += vy
            # 窗口内才保留
            if 0 < bx < WIDTH and 0 < by < HEIGHT:
                new_bullet_list.append([bx, by, vx, vy])
                pygame.draw.circle(screen, WHITE, (int(bx), int(by)), bullet_radius)
        bullets = new_bullet_list

        # 生成敌人
        if current_time - spawn_timer > spawn_interval:
            side = random.choice(["top", "bottom", "left", "right"])
            if side == "top":
                ex = random.randint(0, WIDTH)
                ey = -enemy_radius
            elif side == "bottom":
                ex = random.randint(0, WIDTH)
                ey = HEIGHT + enemy_radius
            elif side == "left":
                ex = -enemy_radius
                ey = random.randint(0, HEIGHT)
            else:
                ex = WIDTH + enemy_radius
                ey = random.randint(0, HEIGHT)
            enemies.append([ex, ey])
            spawn_timer = current_time

        # 更新敌人
        new_enemy_list = []
        for enemy_pos in enemies:
            ex, ey = enemy_pos
            # 敌人向玩家移动
            edx = player_x - ex
            edy = player_y - ey
            dist = math.hypot(edx, edy)
            if dist > 1:
                ex += edx / dist * enemy_speed
                ey += edy / dist * enemy_speed

            # 检测敌人撞到玩家
            if math.hypot(ex - player_x, ey - player_y) < player_radius + enemy_radius:
                game_over = True
                continue

            # 子弹击中敌人判断
            is_hit = False
            # 倒序遍历安全删除子弹
            for i in range(len(bullets)-1, -1, -1):
                bx, by, _, _ = bullets[i]
                if math.hypot(bx - ex, by - ey) < enemy_radius + bullet_radius:
                    bullets.pop(i)
                    is_hit = True
                    score += 10
                    break

            if not is_hit:
                new_enemy_list.append([ex, ey])
                pygame.draw.circle(screen, RED, (int(ex), int(ey)), enemy_radius)
        enemies = new_enemy_list

        # 绘制玩家
        pygame.draw.circle(screen, BLUE, (int(player_x), int(player_y)), player_radius)
        # 瞄准辅助线
        mx, my = pygame.mouse.get_pos()
        pygame.draw.line(screen, (80, 80, 80), (player_x, player_y), (mx, my), 1)

        # 分数显示
        score_text = font.render(f"分数: {score}", True, GREEN)
        screen.blit(score_text, (10, 10))
    else:
        # 游戏结束界面
        over_text = font.render("游戏结束！按空格重新开始", True, (255, 80, 80))
        screen.blit(over_text, (WIDTH//2 - 180, HEIGHT//2))

    pygame.display.flip()

pygame.quit()
sys.exit()