import pygame
import sys

# ===================== 基础常量 =====================
CELL_SIZE = 60
GRID_W = 12
GRID_H = 8
WINDOW_W = CELL_SIZE * GRID_W
WINDOW_H = CELL_SIZE * GRID_H

# 颜色
WHITE = (255, 255, 255)
BLACK = (30, 30, 30)
RED = (220, 30, 30)
BLUE = (30, 80, 220)
GREEN = (30, 180, 60)
ORANGE = (255, 140, 0)
BG_COLOR = (50, 70, 60)

# 单位类型配置
UNIT_TYPE = {
    "infantry": {"hp":80, "atk":25, "move":3, "range":2, "name":"步兵"},
    "tank": {"hp":150, "atk":45, "move":2, "range":3, "name":"坦克"}
}

# ===================== 单位类 =====================
class Unit:
    def __init__(self, x, y, team, utype):
        self.x = x
        self.y = y
        self.team = team  # "red" / "blue"
        self.utype = utype
        self.max_hp = UNIT_TYPE[utype]["hp"]
        self.hp = self.max_hp
        self.atk = UNIT_TYPE[utype]["atk"]
        self.move_range = UNIT_TYPE[utype]["move"]
        self.attack_range = UNIT_TYPE[utype]["range"]
        self.has_acted = False   # 本回合是否行动过

    def distance(self, tx, ty):
        return abs(self.x - tx) + abs(self.y - ty)

# ===================== 兵棋主程序 =====================
class WarGame:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((WINDOW_W, WINDOW_H))
        pygame.display.set_caption("战争兵棋推演")
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont("SimHei", 18)

        self.turn = "red"   # 当前回合 red先手
        self.units = []
        self.selected = None

        # 初始化兵力
        self.spawn_units()

    def spawn_units(self):
        # 红方（左侧）
        self.units.append(Unit(1,2,"red","infantry"))
        self.units.append(Unit(1,4,"red","infantry"))
        self.units.append(Unit(2,3,"red","tank"))
        # 蓝方（右侧）
        self.units.append(Unit(10,2,"blue","infantry"))
        self.units.append(Unit(10,4,"blue","infantry"))
        self.units.append(Unit(9,3,"blue","tank"))

    def get_unit_at(self, x, y):
        for u in self.units:
            if u.x == x and u.y == y:
                return u
        return None

    def get_movable_cells(self, unit):
        cells = []
        for cx in range(GRID_W):
            for cy in range(GRID_H):
                dist = unit.distance(cx, cy)
                if 0 < dist <= unit.move_range:
                    if not self.get_unit_at(cx, cy):
                        cells.append((cx, cy))
        return cells

    def get_attack_targets(self, unit):
        targets = []
        for u in self.units:
            if u.team != unit.team and unit.distance(u.x, u.y) <= unit.attack_range:
                targets.append((u.x, u.y))
        return targets

    def draw_grid(self):
        for x in range(GRID_W+1):
            pygame.draw.line(self.screen, BLACK, (x*CELL_SIZE,0), (x*CELL_SIZE, WINDOW_H))
        for y in range(GRID_H+1):
            pygame.draw.line(self.screen, BLACK, (0,y*CELL_SIZE), (WINDOW_W, y*CELL_SIZE))

    def draw_highlight(self, movable, attack):
        # 移动区域绿色
        for (x,y) in movable:
            rect = pygame.Rect(x*CELL_SIZE+2, y*CELL_SIZE+2, CELL_SIZE-4, CELL_SIZE-4)
            pygame.draw.rect(self.screen, (*GREEN, 80), rect)
        # 攻击区域橙色
        for (x,y) in attack:
            rect = pygame.Rect(x*CELL_SIZE+2, y*CELL_SIZE+2, CELL_SIZE-4, CELL_SIZE-4)
            pygame.draw.rect(self.screen, (*ORANGE, 100), rect)

    def draw_units(self):
        for u in self.units:
            cx = u.x * CELL_SIZE + CELL_SIZE//2
            cy = u.y * CELL_SIZE + CELL_SIZE//2
            color = RED if u.team=="red" else BLUE
            r = CELL_SIZE//2 -6
            pygame.draw.circle(self.screen, color, (cx, cy), r)
            pygame.draw.circle(self.screen, WHITE, (cx, cy), r,2)

            # 血条
            bar_w = CELL_SIZE-16
            hp_ratio = u.hp / u.max_hp
            pygame.draw.rect(self.screen, BLACK, (u.x*CELL_SIZE+8, u.y*CELL_SIZE+CELL_SIZE-12, bar_w,6))
            pygame.draw.rect(self.screen, GREEN if hp_ratio>0.5 else RED,
                             (u.x*CELL_SIZE+8, u.y*CELL_SIZE+CELL_SIZE-12, bar_w*hp_ratio,6))
            # 选中标记
            if self.selected == u:
                pygame.draw.circle(self.screen, WHITE, (cx, cy), r+4,3)

    def draw_ui(self):
        turn_text = f"当前回合：【红方】" if self.turn=="red" else "当前回合：【蓝方】"
        t_surf = self.font.render(turn_text, True, WHITE)
        self.screen.blit(t_surf, (10, 4))
        tip = self.font.render("空格：结束回合 | 点击单位操作", True, WHITE)
        self.screen.blit(tip, (WINDOW_W-320, 4))

    def check_win(self):
        red_alive = any(u.team=="red" for u in self.units)
        blue_alive = any(u.team=="blue" for u in self.units)
        if not red_alive:
            return "blue"
        if not blue_alive:
            return "red"
        return None

    def next_turn(self):
        # 清除所有单位行动标记
        for u in self.units:
            u.has_acted = False
        self.selected = None
        self.turn = "blue" if self.turn=="red" else "red"

    def run(self):
        while True:
            self.screen.fill(BG_COLOR)
            self.draw_grid()

            movable = []
            attack_pos = []
            if self.selected and not self.selected.has_acted:
                movable = self.get_movable_cells(self.selected)
                attack_pos = self.get_attack_targets(self.selected)
            self.draw_highlight(movable, attack_pos)
            self.draw_units()
            self.draw_ui()

            winner = self.check_win()
            if winner:
                win_text = "红方胜利！" if winner=="red" else "蓝方胜利！"
                s = self.font.render(win_text, True, WHITE)
                self.screen.blit(s, (WINDOW_W//2-60, WINDOW_H//2))

            pygame.display.flip()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        self.next_turn()
                if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                    mx, my = pygame.mouse.get_pos()
                    gx = mx // CELL_SIZE
                    gy = my // CELL_SIZE
                    clicked_unit = self.get_unit_at(gx, gy)

                    # 1.点击己方单位选中
                    if clicked_unit and clicked_unit.team == self.turn:
                        self.selected = clicked_unit
                    # 2.选中状态下点击移动格子
                    elif self.selected and (gx,gy) in movable:
                        self.selected.x = gx
                        self.selected.y = gy
                    # 3.点击攻击目标
                    elif self.selected and (gx,gy) in attack_pos:
                        target = self.get_unit_at(gx, gy)
                        target.hp -= self.selected.atk
                        self.selected.has_acted = True
                        if target.hp <=0:
                            self.units.remove(target)
                        self.selected = None
                    else:
                        self.selected = None

            self.clock.tick(60)

if __name__ == "__main__":
    game = WarGame()
    game.run()