match-three/lib/game/systems/match_detector.dart

66 lines
2.0 KiB
Dart

import '../models/gem.dart';
import '../models/grid.dart';
import '../../utils/constants.dart';
class MatchDetector {
static List<Gem> findMatches(GameGrid grid) {
final matches = <Gem>[];
// Check matches
List<Gem> currentMatch = [];
for (int row = 0; row < GameConstants.gridHeight; row++) {
for (int col = 0; col < GameConstants.gridWidth; col++) {
final gem = grid.getGem(row, col);
if (gem == null || matches.contains(gem)) {
continue;
}
currentMatch.add(gem);
for (int i = row + 1; i < GameConstants.gridHeight; i++) {
final nextGem = grid.getGem(i, col);
if (nextGem == null || nextGem.type != gem.type) {
break;
}
currentMatch.add(nextGem);
}
if (currentMatch.length >= GameConstants.minMatchLength) {
matches.addAll(currentMatch);
}
currentMatch.clear();
currentMatch.add(gem);
for (int i = col + 1; i < GameConstants.gridWidth; i++) {
final nextGem = grid.getGem(row, i);
if (nextGem == null || nextGem.type != gem.type) {
break;
}
currentMatch.add(nextGem);
}
if (currentMatch.length >= GameConstants.minMatchLength) {
currentMatch.add(gem);
matches.addAll(currentMatch);
}
currentMatch.clear();
}
}
print("Matches found: ${matches.length}");
matches.forEach((gem) {
print(" - Match found at (${gem.row}, ${gem.col}) [${gem.type}]");
});
return matches.toSet().toList(growable: false);
}
static bool isValidSwap(
GameGrid grid, int row1, int col1, int row2, int col2) {
if (!grid.isValidPosition(row1, col1) ||
!grid.isValidPosition(row2, col2)) {
return false;
}
// Check if positions are adjacent
final rowDiff = (row1 - row2).abs();
final colDiff = (col1 - col2).abs();
return (rowDiff == 1 && colDiff == 0) || (rowDiff == 0 && colDiff == 1);
}
}