import tkinter as tk
import random

CELL = 50
ROWS, COLS = 10, 10

# 兵种配置：名称 / 符号 / 血量 / 攻击力 / 移动范围
UNIT_TYPES = {
    "infantry": ("步兵", "♟", 3, 1, 1),
    "cavalry": ("骑兵", "♞", 4, 2, 2),
    "archer": ("弓兵", "🏹", 2, 2, 1),
}

class Unit:
    def __init__(self, faction, utype, x, y):
        self.faction = faction
        self.utype = utype
        data = UNIT_TYPES[utype]
        self.name, self.symbol, self.hp, self.atk, self.move = data
        self.x, self.y = x, y
        self.max_hp = self.hp

    def is_alive(self):
        return self.hp > 0


class Game:
    def __init__(self, root):
        self.root = root
        self.root.title("040. 战争兵棋推演")
        self.root.resizable(False, False)

        self.canvas = tk.Canvas(root, width=COLS * CELL, height=ROWS * CELL, bg="white")
        self.canvas.pack()

        self.info = tk.Label(root, font=("微软雅黑", 12))
        self.info.pack()

        self.restart_btn = tk.Button(root, text="重新开始", command=self.restart)
        self.restart_btn.pack(pady=5)

        self.units = []
        self.selected = None
        self.turn = "红方"
        self.game_over = False

        self.canvas.bind("<Button-1>", self.click)

        self.init_units()
        self.draw()

    # ========== 初始化 ==========
    def init_units(self):
        self.units.clear()
        # 红方
        self.units.append(Unit("红方", "infantry", 1, 8))
        self.units.append(Unit("红方", "cavalry", 2, 9))
        self.units.append(Unit("红方", "archer", 3, 8))

        # 蓝方
        self.units.append(Unit("蓝方", "infantry", 8, 1))
        self.units.append(Unit("蓝方", "cavalry", 7, 0))
        self.units.append(Unit("蓝方", "archer", 6, 1))

    def restart(self):
        self.turn = "红方"
        self.selected = None
        self.game_over = False
        self.init_units()
        self.draw()

    # ========== 绘制 ==========
    def draw(self):
        self.canvas.delete("all")

        # 棋盘
        for r in range(ROWS):
            for c in range(COLS):
                x1, y1 = c * CELL, r * CELL
                x2, y2 = x1 + CELL, y1 + CELL
                self.canvas.create_rectangle(
                    x1, y1, x2, y2,
                    fill="#F5F5DC" if (r + c) % 2 == 0 else "#DEB887",
                    outline="#8B4513"
                )

        # 单位
        for u in self.units:
            if not u.is_alive():
                continue
            x = u.x * CELL
            y = u.y * CELL
            color = "#D32F2F" if u.faction == "红方" else "#1976D2"

            self.canvas.create_oval(
                x + 5, y + 5, x + CELL - 5, y + CELL - 5,
                fill=color, outline="black", width=2
            )
            self.canvas.create_text(
                x + CELL // 2, y + CELL // 2,
                text=u.symbol, font=("Arial", 20),
                fill="white"
            )
            # 血条
            hp_width = int(CELL * u.hp / u.max_hp)
            self.canvas.create_rectangle(
                x + 5, y + CELL - 10,
                x + 5 + hp_width, y + CELL - 5,
                fill="lime"
            )

        # 信息
        if self.game_over:
            self.info.config(text=f"🎉 {self.winner} 获胜！")
        else:
            self.info.config(text=f"当前回合：{self.turn} | 点击单位选择")

    # ========== 点击逻辑 ==========
    def click(self, e):
        if self.game_over:
            return

        cx, cy = e.x // CELL, e.y // CELL

        if self.turn == "红方":
            self.player_turn(cx, cy)
        # 蓝方 AI 自动走

    def player_turn(self, cx, cy):
        u = self.unit_at(cx, cy)

        # 选中己方单位
        if u and u.faction == "红方" and u.is_alive():
            self.selected = u
            self.draw()
            return

        # 执行操作
        if self.selected:
            if self.in_move_range(self.selected, cx, cy):
                target = self.unit_at(cx, cy)
                if target and target.faction != self.selected.faction:
                    self.attack(self.selected, target)
                else:
                    self.move(self.selected, cx, cy)
                self.end_turn()
            else:
                self.selected = None
                self.draw()

    # ========== 移动 / 攻击 ==========
    def move(self, unit, x, y):
        unit.x, unit.y = x, y

    def attack(self, a, d):
        d.hp -= a.atk
        if d.hp <= 0:
            d.hp = 0
        # 反击
        if d.is_alive():
            a.hp -= d.atk
            if a.hp <= 0:
                a.hp = 0

    # ========== 规则 ==========
    def unit_at(self, x, y):
        for u in self.units:
            if u.x == x and u.y == y and u.is_alive():
                return u
        return None

    def in_move_range(self, unit, x, y):
        return abs(unit.x - x) + abs(unit.y - y) <= unit.move

    def end_turn(self):
        self.draw()
        self.check_win()
        if not self.game_over:
            self.turn = "蓝方" if self.turn == "红方" else "红方"
            if self.turn == "蓝方":
                self.root.after(500, self.ai_turn)

    # ========== AI ==========
    def ai_turn(self):
        if self.game_over:
            return

        units = [u for u in self.units if u.faction == "蓝方" and u.is_alive()]
        enemies = [u for u in self.units if u.faction == "红方" and u.is_alive()]

        for u in units:
            # 找最近敌人
            targets = sorted(
                enemies,
                key=lambda e: abs(u.x - e.x) + abs(u.y - e.y)
            )
            if not targets:
                break

            target = targets[0]

            # 可攻击
            if abs(u.x - target.x) + abs(u.y - target.y) <= u.move:
                self.attack(u, target)
                self.draw()
                self.check_win()
                continue

            # 移动靠近
            dx = 1 if target.x > u.x else -1 if target.x < u.x else 0
            dy = 1 if target.y > u.y else -1 if target.y < u.y else 0

            nx, ny = u.x + dx, u.y + dy
            if not self.unit_at(nx, ny):
                self.move(u, nx, ny)

        self.turn = "红方"
        self.draw()

    # ========== 胜负判定 ==========
    def check_win(self):
        red = any(u.faction == "红方" and u.is_alive() for u in self.units)
        blue = any(u.faction == "蓝方" and u.is_alive() for u in self.units)

        if not red:
            self.winner = "蓝方"
            self.game_over = True
        elif not blue:
            self.winner = "红方"
            self.game_over = True

        if self.game_over:
            self.draw()


if __name__ == "__main__":
    root = tk.Tk()
    Game(root)
    root.mainloop()