createSnake static method

List<FreeHexagon> createSnake({
  1. required FreeHexagon start,
  2. required int count,
  3. double? size,
  4. double gap = 0.0,
  5. double bendFactor = 0.3,
  6. int initialDirection = 0,
})

创建蛇形排列的六边形

start 起始六边形 count 六边形总数(不包括起始六边形) size 六边形大小(如果为null则使用起始六边形的大小) gap 间隙 bendFactor 弯折系数 (0.0 - 1.0) 0.0 = 完全直线 0.5 = 中等弯折 1.0 = 最大弯折(每隔一个就转向) initialDirection 初始方向(边索引 0-5)

Implementation

static List<FreeHexagon> createSnake({
  required FreeHexagon start,
  required int count,
  double? size,
  double gap = 0.0,
  double bendFactor = 0.3,
  int initialDirection = 0,
}) {
  if (count <= 0) return [];

  final hexSize = size ?? start.size;
  final result = <FreeHexagon>[];

  var currentHex = start;
  var currentDirection = initialDirection;

  // 根据弯折系数计算转向频率
  // bendFactor = 0: 永不转向
  // bendFactor = 1: 每个都转向
  // bendFactor = 0.3: 大约每3-4个转向一次
  final bendInterval = bendFactor > 0
      ? (1.0 / bendFactor).round()
      : count + 1;

  for (var i = 0; i < count; i++) {
    // 计算下一个六边形的位置
    final nextCenter = HexagonLayoutHelper.calculateAdjacentCenter(
      sourceHex: currentHex,
      sourceEdge: currentDirection,
      targetSize: hexSize,
      gap: gap,
    );

    final nextHex = FreeHexagon(
      id: '${start.id}_snake_$i',
      center: nextCenter,
      size: hexSize,
      orientation: start.orientation,
    );

    result.add(nextHex);

    // 决定是否转向
    if ((i + 1) % bendInterval == 0) {
      // 转向:可以左转或右转
      // 使用伪随机选择方向(基于索引)
      final turnRight = (i ~/ bendInterval) % 2 == 0;
      if (turnRight) {
        currentDirection = (currentDirection + 1) % 6; // 右转60度
      } else {
        currentDirection = (currentDirection + 5) % 6; // 左转60度
      }
    }

    currentHex = nextHex;
  }

  return result;
}