private Point2D GenerateIsolatedGoal(Random rand, HashSet<Point2D> used, List<Obstacle> obstacles, List<Robot> robots, int minDistance = 3)
        {
            const int maxAttempts = 1000;
            for (int attempt = 0; attempt < maxAttempts; attempt++)
            {
                // 在地图右下区域生成候选点(根据你的 startArea 逻辑调整)
                int x = rand.Next(startArea.X, MapWidth);
                int y = rand.Next(startArea.Y, MapHeight);
                var candidate = new Point2D(x, y);

                // 1. 不在障碍物上
                if (obstacles.Any(o => o.Position == candidate))
                    continue;

                // 2. 不与其他机器人的 Start/Goal 冲突
                if (used.Contains(candidate))
                    continue;

                // 3. 与所有已有机器人的 Goal 至少保持 minDistance 距离
                bool tooClose = false;
                foreach (var r in robots)
                {
                    if (ManhattanDistance(candidate, r.Goal) < minDistance)
                    {
                        tooClose = true;
                        break;
                    }
                }
                if (tooClose)
                    continue;

                return candidate;
            }

            // 如果实在找不到,退而求其次(可选:抛异常或放宽条件)
            throw new InvalidOperationException("无法为新机器人生成隔离的 Goal 点,请减少机器人数量或扩大地图。");
        }
 private int ManhattanDistance(Point2D a, Point2D b)
 {
     return Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y);
 }
 #endregion
posted on 2025-11-06 10:56  魔法乐  阅读(14)  评论(0)    收藏  举报