// ============================================================================
// langton_ant.v - Langton蚂蚁硬件引擎
// 支持多色扩展（ generalized Langton's ant）
// ============================================================================
module langton_ant #(
    parameter WIDTH  = 128,           // 网格宽度
    parameter HEIGHT = 128,           // 网格高度
    parameter COLORS = 2              // 颜色数（2=经典版）
)(
    input  wire             clk,
    input  wire             rst_n,
    input  wire             enable,
    input  wire             init,
    output wire [1:0]       ant_dir,      // 蚂蚁方向(0=N,1=E,2=S,3=W)
    output wire [7:0]       ant_x,        // 蚂蚁X坐标
    output wire [7:0]       ant_y,        // 蚂蚁Y坐标
    output wire [31:0]      step_count,
    output wire [WIDTH*HEIGHT-1:0] grid   // 网格状态
);

    // ---- 网格状态（每格1位，2色版本） ----
    reg [WIDTH*HEIGHT-1:0] grid_reg;

    // ---- 蚂蚁状态 ----
    reg [7:0]  ax, ay;       // 位置
    reg [1:0]  dir;          // 方向: 00=北 01=东 10=南 11=西
    reg [31:0] steps;

    // ---- 当前格子颜色 ----
    wire [WIDTH*HEIGHT-1:0] idx = ay * WIDTH + ax;
    wire current_color = grid_reg[idx];

    // ---- 下一方向计算 ----
    // 白色(0)→右转: dir+1; 黑色(1)→左转: dir-1
    wire [1:0] next_dir = current_color ? (dir - 2'd1) : (dir + 2'd1);

    // ---- 下一位置计算 ----
    reg [7:0] next_x, next_y;
    always @(*) begin
        next_x = ax;
        next_y = ay;
        case (next_dir)
            2'd0: next_y = (ay == 0) ? HEIGHT - 1 : ay - 1;  // 北
            2'd1: next_x = (ax == WIDTH - 1) ? 0 : ax + 1;   // 东
            2'd2: next_y = (ay == HEIGHT - 1) ? 0 : ay + 1;  // 南
            2'd3: next_x = (ax == 0) ? WIDTH - 1 : ax - 1;   // 西
        endcase
    end

    // ---- 状态更新 ----
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            grid_reg <= {WIDTH*HEIGHT{1'b0}};
            ax    <= WIDTH / 2;
            ay    <= HEIGHT / 2;
            dir   <= 2'd0;
            steps <= 32'd0;
        end else if (init) begin
            grid_reg <= {WIDTH*HEIGHT{1'b0}};
            ax    <= WIDTH / 2;
            ay    <= HEIGHT / 2;
            dir   <= 2'd0;
            steps <= 32'd0;
        end else if (enable) begin
            // 翻转当前格子颜色
            grid_reg[idx] <= ~current_color;
            // 更新蚂蚁位置和方向
            ax  <= next_x;
            ay  <= next_y;
            dir <= next_dir;
            steps <= steps + 32'd1;
        end
    end

    assign ant_dir    = dir;
    assign ant_x     = ax;
    assign ant_y     = ay;
    assign step_count = steps;
    assign grid       = grid_reg;

endmodule