Python综合共 3 步分步检查

实验 9:多机器人网格协作任务分配与冲突消解

使用纯 Python 标准库实现多机器人最小曼哈顿距离贪心任务分配,以及基于优先级时空预约表(Space-Time Reservation)的网格路径规划,消除顶点冲突与对向边交换冲突。

多智能体协作贪心任务分配时空预约表顶点与边冲突消解优先级规划
上机实验入口

本实验归属于《大模型与具身智能体》课程空间。在独立隔离环境中真实编译运行并逐项核验,步骤通过前不泄露参考代码。

分步实践任务说明

共 3 个核验步骤
01

步骤 1:多机器人最小曼哈顿距离贪心任务分配

从标准输入读取 JSON 配置,包含 `mode`(`assign` 或 `plan`)、`rows`、`cols`、`obstacles`、`max_time`、`robots`、`tasks`。 当 `mode="assign"` 时,实现 `assign_tasks(robots, tasks)`: 1. 在所有尚未分配的 `(robot, task)` 组合中,重复选择 `(曼哈顿距离, robot_id, task_id)` 字典序最小的一对进行绑定,直至机器人或任务分配完毕; 2. 按 `robot_id` 升序逐行输出:`ASSIGN <robot_id> -> <task_id> dist=<manhattan>`; 3. 最后一行输出总距离:`TOTAL_DIST <sum>`。

02

步骤 2:时空预约表与顶点/对向边冲突消解

当 `mode="plan"` 时,按 `robot_id` 升序为每个机器人依次调用 `plan_single_robot` 进行时空 BFS: 1. 状态为 `(r, c, t)`,每步按固定顺序 `UP(-1,0), DOWN(1,0), LEFT(0,-1), RIGHT(0,1), WAIT(0,0)` 扩展; 2. 禁止越界、进入障碍物,禁止**顶点冲突** `(nr, nc, t+1) in vertex_res`,禁止**对向边交换冲突** `(nr, nc, r, c, t) in edge_res`; 3. 机器人抵达终点并确保在之后所有已被高优先级机器人占用的时刻无冲突后停止,并将其路径及抵达后至 `max_time` 的终点停留全部写入预约表; 4. 逐个输出 `PATH <rid> steps=<k> traj=(r0,c0)->...` 及末尾 `MAKESPAN <最大步数>`。

03

步骤 3:任务分配联动时空规划与无解检测

完善协作规划闭环: 1. 当 `mode="plan"` 且提供 `tasks` 时,先自动调用 `assign_tasks` 分配目标,再按优先级依次规划无冲突路径; 2. 若机器人终点在未来时刻会被高优先级机器人路过,机器人不可提前在终点终止,必须等到 `t > last_goal_occ` 后才算安全到达; 3. 若某机器人在 `max_time` 内无可行无冲突路径,输出 `PATH <rid> FAILED`,且最终输出 `MAKESPAN FAILED`。

起步代码框架预览

Python
import json
import sys
from collections import deque

DIRS = ((-1, 0), (1, 0), (0, -1), (0, 1), (0, 0))


def assign_tasks(robots, tasks):
    """全局最小曼哈顿距离贪心分配,返回 {robot_id: (task_id, goal_tuple, dist)}。"""
    # TODO 1: 迭代选择 (dist, robot_id, task_id) 最小的未分配配对
    raise NotImplementedError("请补全 assign_tasks")


def plan_single_robot(start, goal, rows, cols, obstacles, max_time, vertex_res, edge_res):
    """在时空预约表约束下,使用时空 BFS 为单个机器人求最短无冲突路径。"""
    # TODO 2 & 3: 检查越界、障碍物、顶点冲突、对向边交换冲突与终点持续占位约束
    raise NotImplementedError("请补全 plan_single_robot")


def main():
    raw = sys.stdin.read().strip()
    if not raw:
        return
    cfg = json.loads(raw)
    mode = cfg.get("mode", "plan")
    robots = cfg.get("robots", [])
    tasks = cfg.get("tasks", [])

    if mode == "assign":
        mapping = assign_tasks(robots, tasks)
        total = 0
        for rid in sorted(mapping):
            tid, _goal, d = mapping[rid]
            total += d
            print(f"ASSIGN {rid} -> {tid} dist={d}")
        print(f"TOTAL_DIST {total}")
        return

    rows = int(cfg["rows"])
    cols = int(cfg["cols"])
    obstacles = {tuple(p) for p in cfg.get("obstacles", [])}
    max_time = int(cfg.get("max_time", 20))

    if tasks:
        mapping = assign_tasks(robots, tasks)
        goals = {rid: mapping[rid][1] for rid in mapping}
    else:
        goals = {r["id"]: tuple(r["goal"]) for r in robots}

    vertex_res = set()
    edge_res = set()
    max_steps = 0
    failed = False
    for r in sorted(robots, key=lambda x: x["id"]):
        rid = r["id"]
        start = tuple(r["start"])
        goal = goals[rid]
        path = plan_single_robot(start, goal, rows, cols, obstacles, max_time, vertex_res, edge_res)
        if path is None:
            print(f"PATH {rid} FAILED")
            failed = True
        else:
            for t, pos in enumerate(path):
                vertex_res.add((pos[0], pos[1], t))
                if t > 0:
                    edge_res.add((path[t - 1][0], path[t - 1][1], pos[0], pos[1], t - 1))
            for t in range(len(path), max_time + 1):
                vertex_res.add((goal[0], goal[1], t))
                edge_res.add((goal[0], goal[1], goal[0], goal[1], t - 1))
            max_steps = max(max_steps, len(path) - 1)
            traj = "->".join(f"({p[0]},{p[1]})" for p in path)
            print(f"PATH {rid} steps={len(path) - 1} traj={traj}")

    print(f"MAKESPAN {'FAILED' if failed else max_steps}")


if __name__ == "__main__":
    main()