checkLine method

bool checkLine(
  1. List<int> line
)

Implementation

bool checkLine(List<int> line) {
  final groups = <int, int>{};
  // 统计颜色
  for (var i in line) {
    if (lastColor != null) {
      if (i == lastColor || (i - lastColor!).abs() / 255 < tolerance) {
        groups[lastColor!] = (groups[lastColor] ?? 0) + 1;
      }
    } else {
      if (groups.containsKey(i)) {
        groups[i] = groups[i]! + 1;
      } else {
        groups[i] = 1;
      }
    }
  }

  if (groups.isEmpty) return false;

  // 尝试合并颜色
  if (groups.length > 1) {
    final sorted = groups.entries.toList()
      ..sort((e, e2) => e.value - e2.value);
    final first = sorted.removeAt(0);
    if (first.value < purity * line.length) {
      if (tolerance == 0) {
        return false;
      }
      int count = first.value;
      for (var e in sorted) {
        if ((e.key - first.key).abs() / 255 <= tolerance) {
          count += e.value;
        }
      }
      final passed = count / line.length > purity;
      if (passed && lastColor == null) {
        lastColor = first.key;
      }
      return passed;
    }
  }
  if (lastColor == null) {
    lastColor ??= groups.keys.first;
    return true;
  } else {
    return groups.values.first / line.length > purity;
  }
}