import tkinter as tk
from tkinter import ttk, messagebox
import random

class Wargame:
    def __init__(self, root):
        self.root = root
        self.root.title("简易战争兵棋推演")
        self.root.geometry("850x650")
        self.root.resizable(False, False)

        # 游戏参数
        self.GRID_SIZE = 8  # 8x8棋盘
        self.CELL_SIZE = 60
        self.current_turn = "红方"  # 红方先行动
        self.selected_unit = None  # 当前选中的单位
        self.game_over = False

        # 单位属性：(生命值, 攻击力, 移动力, 颜色)
        self.unit_types = {
            "步兵": (100, 20, 2, "#8B4513"),
            "坦克": (200, 40, 3, "#4682B4"),
            "炮兵": (80, 60, 1, "#228B22")
                                      
        }

        # 初始化棋盘数据：None表示空，否则是单位字典
        self.board = [[None for _ in range(self.GRID_SIZE)] for _ in range(self.GRID_SIZE)]
        self.init_units()

        # ========== 顶部信息栏 ==========
        self.info_frame = ttk.Frame(root)
        self.info_frame.pack(pady=5, fill="x")
        self.turn_label = ttk.Label(self.info_frame, text=f"当前回合：{self.current_turn}", font=("微软雅黑", 14, "bold"))
        self.turn_label.pack(side="left", padx=20)
        self.status_label = ttk.Label(self.info_frame, text="游戏进行中", font=("微软雅黑", 12))
        self.status_label.pack(side="right", padx=20)

        # ========== 主游戏区域 ==========
        main_frame = ttk.Frame(root)
        main_frame.pack(padx=10, pady=5, fill="both", expand=True)

        # 左侧：棋盘
        self.canvas = tk.Canvas(main_frame, width=self.GRID_SIZE*self.CELL_SIZE, 
                               height=self.GRID_SIZE*self.CELL_SIZE, bg="#F5F5DC")
        self.canvas.pack(side="left", padx=5)
        self.canvas.bind("<Button-1>", self.on_click)

        # 右侧：单位信息面板
        self.info_panel = ttk.LabelFrame(main_frame, text="单位信息")
        self.info_panel.pack(side="right", padx=5, fill="y")
        self.unit_info = tk.Text(self.info_panel, width=20, height=15, font=("微软雅黑", 10))
        self.unit_info.pack(padx=5, pady=5)

        # ========== 底部操作栏 ==========
        btn_frame = ttk.Frame(root)
        btn_frame.pack(pady=10)
        ttk.Button(btn_frame, text="结束回合", command=self.end_turn, width=15).pack(side="left", padx=10)
        ttk.Button(btn_frame, text="重新开始", command=self.restart_game, width=15).pack(side="left", padx=10)

        # 绘制初始棋盘
        self.draw_board()

    # 初始化双方单位
    def init_units(self):
        # 红方（底部）
        self.board[7][0] = {"type": "坦克", "hp": 200, "team": "红方", "moved": False}
        self.board[7][3] = {"type": "步兵", "hp": 100, "team": "红方", "moved": False}
        self.board[7][4] = {"type": "步兵", "hp": 100, "team": "红方", "moved": False}
        self.board[7][7] = {"type": "炮兵", "hp": 5000, "team": "红方", "moved": False}
        self.board[6][2] = {"type": "步兵", "hp": 100, "team": "红方", "moved": False}
        self.board[6][5] = {"type": "步兵", "hp": 100, "team": "红方", "moved": False}

        # 蓝方（顶部）
        self.board[0][0] = {"type": "炮兵", "hp": 5000, "team": "蓝方", "moved": False}
        self.board[0][3] = {"type": "步兵", "hp": 100, "team": "蓝方", "moved": False}
        self.board[0][4] = {"type": "步兵", "hp": 100, "team": "蓝方", "moved": False}
        self.board[0][7] = {"type": "坦克", "hp": 200, "team": "蓝方", "moved": False}
        self.board[1][2] = {"type": "步兵", "hp": 100, "team": "蓝方", "moved": False}

    def draw_board(self):
        self.canvas.delete("all")
        # 绘制网格
        for i in range(self.GRID_SIZE+1):
            self.canvas.create_line(i*self.CELL_SIZE, 0, i*self.CELL_SIZE, self.GRID_SIZE*self.CELL_SIZE)
            self.canvas.create_line(0, i*self.CELL_SIZE, self.GRID_SIZE*self.CELL_SIZE, i*self.CELL_SIZE)

        # 绘制单位
        for row in range(self.GRID_SIZE):
            for col in range(self.GRID_SIZE):
                unit = self.board[row][col]
                if unit:
                    x1 = col*self.CELL_SIZE + 5
                    y1 = row*self.CELL_SIZE + 5
                    x2 = (col+1)*self.CELL_SIZE - 5
                    y2 = (row+1)*self.CELL_SIZE - 5
                    
                    # 单位颜色
                    color = self.unit_types[unit["type"]][3]
                    if unit["team"] == "红方":
                        outline = "red"
                    else:
                        outline = "blue"
                    
                    # 绘制单位圆形
                    self.canvas.create_oval(x1, y1, x2, y2, fill=color, outline=outline, width=2)
                    
                    # 显示单位类型缩写
                    text_x = (x1+x2)/2
                    text_y = (y1+y2)/2
                    abbr = unit["type"][0]
                    self.canvas.create_text(text_x, text_y, text=abbr, font=("微软雅黑", 16, "bold"), fill="white")
                    
                    # 显示生命值条
                    hp_percent = unit["hp"] / self.unit_types[unit["type"]][0]
                    bar_width = self.CELL_SIZE - 10
                    bar_x1 = x1
                    bar_y1 = y2 + 2
                    bar_x2 = bar_x1 + bar_width * hp_percent
                    bar_y2 = bar_y1 + 5
                    self.canvas.create_rectangle(bar_x1, bar_y1, bar_x1+bar_width, bar_y2, fill="gray")
                    self.canvas.create_rectangle(bar_x1, bar_y1, bar_x2, bar_y2, fill="green")

        # 高亮选中的单位
        if self.selected_unit:
            row, col = self.selected_unit
            x1 = col*self.CELL_SIZE
            y1 = row*self.CELL_SIZE
            x2 = (col+1)*self.CELL_SIZE
            y2 = (row+1)*self.CELL_SIZE
            self.canvas.create_rectangle(x1, y1, x2, y2, outline="yellow", width=3)

            # 显示可移动范围（绿色虚线）
            unit = self.board[row][col]
            move_range = self.unit_types[unit["type"]][2]
            for r in range(self.GRID_SIZE):
                for c in range(self.GRID_SIZE):
                    if abs(r-row) + abs(c-col) <= move_range and (r != row or c != col):
                        if not self.board[r][c]:
                            rx1 = c*self.CELL_SIZE + 2
                            ry1 = r*self.CELL_SIZE + 2
                            rx2 = (c+1)*self.CELL_SIZE - 2
                            ry2 = (r+1)*self.CELL_SIZE - 2
                            self.canvas.create_rectangle(rx1, ry1, rx2, ry2, outline="green", dash=(4,4))

            # 显示可攻击范围（红色虚线）
            for r in range(self.GRID_SIZE):
                for c in range(self.GRID_SIZE):
                    if abs(r-row) + abs(c-col) == 1 and self.board[r][c]:
                        if self.board[r][c]["team"] != unit["team"]:
                            rx1 = c*self.CELL_SIZE + 2
                            ry1 = r*self.CELL_SIZE + 2
                            rx2 = (c+1)*self.CELL_SIZE - 2
                            ry2 = (r+1)*self.CELL_SIZE - 2
                            self.canvas.create_rectangle(rx1, ry1, rx2, ry2, outline="red", dash=(4,4))

    # 处理鼠标点击
    def on_click(self, event):
        if self.game_over:
            return

        col = event.x // self.CELL_SIZE
        row = event.y // self.CELL_SIZE

        if row < 0 or row >= self.GRID_SIZE or col < 0 or col >= self.GRID_SIZE:
            return

        clicked_unit = self.board[row][col]

        # 情况1：点击自己的单位，选中它
        if clicked_unit and clicked_unit["team"] == self.current_turn and not clicked_unit["moved"]:
            self.selected_unit = (row, col)
            self.update_unit_info(clicked_unit)
            self.draw_board()
            return

        # 情况2：已经选中单位，点击可移动的空格
        if self.selected_unit:
            s_row, s_col = self.selected_unit
            unit = self.board[s_row][s_col]
            move_range = self.unit_types[unit["type"]][2]

            # 移动
            if not clicked_unit and abs(row-s_row) + abs(col-s_col) <= move_range:
                self.board[row][col] = unit
                self.board[s_row][s_col] = None
                unit["moved"] = True
                self.selected_unit = (row, col)
                self.draw_board()
                return

            # 攻击
            if clicked_unit and clicked_unit["team"] != self.current_turn and abs(row-s_row) + abs(col-s_col) == 1:
                damage = self.unit_types[unit["type"]][1]
                clicked_unit["hp"] -= damage
                unit["moved"] = True

                # 检查是否被消灭
                if clicked_unit["hp"] <= 0:
                    self.board[row][col] = None
                    messagebox.showinfo("战斗结果", f"{unit['team']}的{unit['type']}消灭了{clicked_unit['team']}的{clicked_unit['type']}！")
                    self.check_win()
                else:
                    messagebox.showinfo("战斗结果", f"{unit['team']}的{unit['type']}对{clicked_unit['team']}的{clicked_unit['type']}造成了{damage}点伤害！")

                self.selected_unit = None
                self.draw_board()
                return

        # 情况3：点击其他地方，取消选中
        self.selected_unit = None
        self.unit_info.delete(1.0, tk.END)
        self.draw_board()

    # 更新单位信息面板
    def update_unit_info(self, unit):
        self.unit_info.delete(1.0, tk.END)
        info = f"所属：{unit['team']}\n"
        info += f"类型：{unit['type']}\n"
        info += f"生命值：{unit['hp']}/{self.unit_types[unit['type']][0]}\n"
        info += f"攻击力：{self.unit_types[unit['type']][1]}\n"
        info += f"移动力：{self.unit_types[unit['type']][2]}\n"
        info += f"状态：{'已行动' if unit['moved'] else '可行动'}"
        self.unit_info.insert(tk.END, info)

    # 结束回合
    def end_turn(self):
        if self.game_over:
            return

        # 重置所有单位的行动状态
        for row in range(self.GRID_SIZE):
            for col in range(self.GRID_SIZE):
                if self.board[row][col]:
                    self.board[row][col]["moved"] = False

        # 切换回合
        self.current_turn = "蓝方" if self.current_turn == "红方" else "红方"
        self.turn_label.config(text=f"当前回合：{self.current_turn}")
        self.selected_unit = None
        self.unit_info.delete(1.0, tk.END)
        self.draw_board()

    # 检查胜负
    def check_win(self):
        red_units = 0
        blue_units = 0

        for row in range(self.GRID_SIZE):
            for col in range(self.GRID_SIZE):
                if self.board[row][col]:
                    if self.board[row][col]["team"] == "红方":
                        red_units += 1
                    else:
                        blue_units += 1

        if red_units == 0:
            self.game_over = True
            self.status_label.config(text="蓝方获胜！")
            messagebox.showinfo("游戏结束", "蓝方消灭了所有红方单位，获得胜利！")
        elif blue_units == 0:
            self.game_over = True
            self.status_label.config(text="红方获胜！")
            messagebox.showinfo("游戏结束", "红方消灭了所有蓝方单位，获得胜利！")

    # 重新开始游戏
    def restart_game(self):
        self.current_turn = "红方"
        self.selected_unit = None
        self.game_over = False
        self.board = [[None for _ in range(self.GRID_SIZE)] for _ in range(self.GRID_SIZE)]
        self.init_units()
        self.turn_label.config(text=f"当前回合：{self.current_turn}")
        self.status_label.config(text="游戏进行中")
        self.unit_info.delete(1.0, tk.END)
        self.draw_board()

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