import pygame
import random

pygame.init()

#窗口设置
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("坦克大战")
clock = pygame.time.Clock()
FPS = 60

#颜色定义
BLACK = (15,15,15)
WALL_COLOR = (130, 100, 70)
PLAYER_TANK = (20, 170, 240)
ENEMY_TANK = (200, 20, 20)
BULLET_COLOR = (255, 220, 0)
BASE_COLOR = (30, 200, 50)
RED = (255, 0, 0)
WHITE = (255,255,255)

#字体修复（避开SysFont注册表报错）
font = pygame.font.Font(None, 36)

#网格大小
CELL = 40

#地图： 1=砖墙  0=空地
game_map = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,1],
[1,0,1,1,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,1],
[1,0,1,1,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
]

#玩家坦克
player_x = CELL * 1
player_y = CELL * 9
player_speed = 3
player_dir = 0   # 0上 1右 2下 3左
shoot_cd = 0
shoot_delay = 25

#基地位置
base_x = CELL * 9
base_y = CELL * 10
base_alive = True

bullets = []
enemies = []
enemy_spawn_timer = 0
max_enemy = 4
score = 0
game_over = False

def is_wall(x,y):
    cx = int(x//CELL)
    cy = int(y//CELL)
    if 0<=cx<20 and 0<=cy<12:
        return game_map[cy][cx]==1
    return True

def spawn_enemy():
    ex = random.choice([CELL*2,CELL*9,CELL*16])
    ey = CELL*1
    enemies.append({"x":ex,"y":ey,"dir":random.randint(0,3),"move_cd":0})

running = True
while running:
    clock.tick(FPS)
    shoot_cd += 1

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if not game_over:
        nx, ny = player_x, player_y
        if keys[pygame.K_w]:
            ny -= player_speed
            player_dir = 0
        if keys[pygame.K_s]:
            ny += player_speed
            player_dir = 2
        if keys[pygame.K_a]:
            nx -= player_speed
            player_dir = 3
        if keys[pygame.K_d]:
            nx += player_speed
            player_dir = 1
        #墙体碰撞
        if not is_wall(nx,player_y):
            player_x = nx
        if not is_wall(player_x,ny):
            player_y = ny

        #发射炮弹
        if keys[pygame.K_SPACE] and shoot_cd >= shoot_delay:
            if player_dir == 0:
                bullets.append([player_x+18, player_y, 0,-6])
            elif player_dir == 2:
                bullets.append([player_x+18, player_y+36, 0,6])
            elif player_dir == 1:
                bullets.append([player_x+36, player_y+18,6,0])
            elif player_dir == 3:
                bullets.append([player_x, player_y+18,-6,0])
            shoot_cd = 0

        #生成敌人
        enemy_spawn_timer += 1
        if enemy_spawn_timer >= 180 and len(enemies)<max_enemy:
            spawn_enemy()
            enemy_spawn_timer = 0

        #更新敌人坦克
        for e in enemies:
            e["move_cd"] += 1
            ex,ey = e["x"],e["y"]
            if e["dir"] == 0: ey -= 2
            elif e["dir"] == 2: ey += 2
            elif e["dir"] == 1: ex += 2
            elif e["dir"] == 3: ex -= 2
            if is_wall(ex,ey) or e["move_cd"]>120:
                e["dir"] = random.randint(0,3)
                e["move_cd"] = 0
            else:
                e["x"],e["y"] = ex,ey

        #更新炮弹
        new_bullet = []
        for b in bullets:
            bx,by,vx,vy = b
            bx += vx
            by += vy
            #撞墙
            if is_wall(bx,by):
                continue
            hit_enemy = False
            #击中敌人
            for enemy in enemies[:]:
                if enemy["x"]<bx<enemy["x"]+36 and enemy["y"]<by<enemy["y"]+36:
                    enemies.remove(enemy)
                    score += 100
                    hit_enemy = True
                    break
            #击中基地
            if base_x<bx<base_x+40 and base_y<by<base_y+40:
                base_alive = False
                game_over = True
            if not hit_enemy:
                new_bullet.append([bx,by,vx,vy])
        bullets = new_bullet

    #绘制
    screen.fill(BLACK)
    #地图墙体
    for row_idx,row in enumerate(game_map):
        for col_idx,cell in enumerate(row):
            if cell == 1:
                rect = (col_idx*CELL,row_idx*CELL,CELL-1,CELL-1)
                pygame.draw.rect(screen,WALL_COLOR,rect)

    #基地
    if base_alive:
        pygame.draw.rect(screen,BASE_COLOR,(base_x,base_y,CELL,CELL))

    #炮弹
    for b in bullets:
        pygame.draw.circle(screen,BULLET_COLOR,(int(b[0]),int(b[1])),4)

    #敌人坦克
    for e in enemies:
        pygame.draw.rect(screen,ENEMY_TANK,(e["x"],e["y"],36,36))

    #玩家坦克
    pygame.draw.rect(screen,PLAYER_TANK,(player_x,player_y,36,36))

    #UI
    score_text = font.render(f"得分:{score}",True,WHITE)
    screen.blit(score_text,(20,20))

    if game_over:
        end_text = font.render("基地被毁，游戏结束!",True,RED)
        screen.blit(end_text,(WIDTH//2-160,HEIGHT//2))

    pygame.display.flip()

pygame.quit()
