import tkinter as tk
from tkinter import messagebox
import math

# 配置常量
CELL_SIZE = 60
MAP_WIDTH = 10
MAP_HEIGHT = 8
RANGE_ATTACK = 2  # 攻击射程

# 兵种单位类
class Unit:
    def __init__(self, x, y, team, hp=100, attack=30):
        self.x = x
        self.y = y
        self.team = team  # red / blue
        self.hp = hp
        self.max_hp = hp
        self.attack = attack
        self.moved = False    # 本回合是否移动
        self.acted = False    # 本回合是否攻击

class WargameApp:
    def __init__(self, root):
        self.root = root
        self.root.title("战争兵棋推演")
        self.current_team = "red"  # 先手红方
        self.selected_unit = None
        self.units = []

        # 画布
        self.canvas = tk.Canvas(root, width=MAP_WIDTH*CELL_SIZE, height=MAP_HEIGHT*CELL_SIZE, bg="#3a5f3a")
        self.canvas.pack(padx=10, pady=10)
        self.canvas.bind("<Button-1>", self.on_click)

        # 控制面板
        frame = tk.Frame(root)
        frame.pack()
        self.info_label = tk.Label(frame, text=f"当前回合：红方", font=("SimHei",12))
        self.info_label.grid(row=0,column=0,padx=10)
        btn_end = tk.Button(frame, text="结束回合", command=self.next_turn)
        btn_end.grid(row=0,column=1,padx=5)
        btn_reset = tk.Button(frame, text="重置战场", command=self.reset_game)
        btn_reset.grid(row=0,column=2,padx=5)

        self.init_army()
        self.draw_map()

    # 初始化双方兵力
    def init_army(self):
        self.units.clear()
        # 红方（左侧）
        self.units.append(Unit(1,2,"red"))
        self.units.append(Unit(1,4,"red"))
        self.units.append(Unit(2,3,"red"))
        # 蓝方（右侧）
        self.units.append(Unit(7,2,"blue"))
        self.units.append(Unit(7,4,"blue"))
        self.units.append(Unit(8,3,"blue"))

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

    # 格子点击事件
    def on_click(self, event):
        cx = event.x // CELL_SIZE
        cy = event.y // CELL_SIZE
        if not (0 <= cx < MAP_WIDTH and 0 <= cy < MAP_HEIGHT):
            return
        clicked_unit = self.get_unit_at(cx, cy)

        # 情况1：点击自己的单位，选中
        if clicked_unit and clicked_unit.team == self.current_team:
            self.selected_unit = clicked_unit
            self.draw_map()
            return

        # 已有选中单位
        if self.selected_unit:
            sel = self.selected_unit
            target_unit = self.get_unit_at(cx, cy)
            dist = math.hypot(sel.x - cx, sel.y - cy)

            # 移动到空地
            if not target_unit and not sel.moved and dist <= 3:
                sel.x = cx
                sel.y = cy
                sel.moved = True
            # 攻击敌方单位
            elif target_unit and target_unit.team != sel.team and not sel.acted and dist <= RANGE_ATTACK:
                target_unit.hp -= sel.attack
                sel.acted = True
                if target_unit.hp <= 0:
                    self.check_win()
            self.selected_unit = None
            self.draw_map()

    # 切换回合
    def next_turn(self):
        # 重置所有单位行动标记
        for u in self.units:
            u.moved = False
            u.acted = False
        # 换阵营
        self.current_team = "blue" if self.current_team == "red" else "red"
        self.selected_unit = None
        self.info_label.config(text=f"当前回合：{'蓝方' if self.current_team=='blue' else '红方'}")
        self.draw_map()

    # 判断胜负
    def check_win(self):
        red_alive = any(u.team=="red" and u.hp>0 for u in self.units)
        blue_alive = any(u.team=="blue" and u.hp>0 for u in self.units)
        if not red_alive:
            messagebox.showinfo("战局结束", "蓝方获得胜利！")
        elif not blue_alive:
            messagebox.showinfo("战局结束", "红方获得胜利！")

    def reset_game(self):
        self.current_team = "red"
        self.selected_unit = None
        self.info_label.config(text="当前回合：红方")
        self.init_army()
        self.draw_map()

    def draw_map(self):
        self.canvas.delete("all")
        # 绘制网格
        for x in range(MAP_WIDTH):
            for y in range(MAP_HEIGHT):
                x1 = x*CELL_SIZE
                y1 = y*CELL_SIZE
                x2 = x1+CELL_SIZE
                y2 = y1+CELL_SIZE
                self.canvas.create_rectangle(x1,y1,x2,y2,outline="#224422")

        # 绘制单位
        for unit in self.units:
            if unit.hp <= 0:
                continue
            x1 = unit.x*CELL_SIZE+5
            y1 = unit.y*CELL_SIZE+5
            x2 = x1+CELL_SIZE-10
            y2 = y1+CELL_SIZE-10
            color = "#dd3333" if unit.team=="red" else "#3333dd"
            # 选中高亮
            if unit == self.selected_unit:
                self.canvas.create_rectangle(x1-3,y1-3,x2+3,y2+3,outline="#ffff00",width=3)
            self.canvas.create_oval(x1,y1,x2,y2,fill=color)
            # 血量文字
            self.canvas.create_text((x1+x2)/2,(y1+y2)/2,text=f"{unit.hp}",fill="white",font=("SimHei",11))

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