- Add proper validation for null gems during swap operations - Implement swap-back animation for invalid moves (no matches) - Restructure swap flow to emit animation states before match detection - Add move limit validation before processing matches - Improve error handling and logging for edge cases
66 lines
1.9 KiB
Dart
66 lines
1.9 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 < grid.height; row++) {
|
|
for (int col = 0; col < grid.width; col++) {
|
|
final gem = grid.getGem(row, col);
|
|
if (gem == null) {
|
|
continue;
|
|
}
|
|
currentMatch.add(gem);
|
|
for (int i = row + 1; i < grid.height; 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 < grid.width; 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);
|
|
}
|
|
}
|