savinmax eaa6947e93 Refactor gem swap logic to handle invalid moves and animations
- 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
2025-09-28 13:00:45 +02:00

83 lines
2.0 KiB
Dart

import 'dart:math';
import 'gem.dart';
import '../../utils/constants.dart';
class GameGrid {
late List<List<Gem?>> _grid;
final Random _random = Random();
final int width;
final int height;
GameGrid({required this.width, required this.height}) {
_initializeGrid();
}
void _initializeGrid() {
_grid = List.generate(
height,
(row) => List.generate(
width,
(col) => Gem(
type: _random.nextInt(GameConstants.gemTypes.length),
row: row,
col: col,
),
),
);
}
Gem? getGem(int row, int col) {
if (row < 0 || row >= height || col < 0 || col >= width) {
return null;
}
return _grid[row][col];
}
void setGem(int row, int col, Gem? gem) {
if (row >= 0 && row < height && col >= 0 && col < width) {
_grid[row][col] = gem;
}
}
List<List<Gem?>> get grid => _grid;
bool isValidPosition(int row, int col) {
return row >= 0 && row < height && col >= 0 && col < width;
}
GameGrid clone() {
final clonedGrid = GameGrid(width: width, height: height);
for (int row = 0; row < _grid.length; row++) {
for (int col = 0; col < _grid[row].length; col++) {
final gem = getGem(row, col);
clonedGrid.setGem(row, col, gem?.copyWith());
}
}
return clonedGrid;
}
void printGrid() {
final cols = _grid[0].length;
var colHeader = " |";
for (int col = 0; col < cols; col++) {
colHeader += " ${col.toString().padRight(3, " ")} |";
}
colHeader += "\n--- |";
for (int col = 0; col < cols; col++) {
colHeader += " --- |";
}
print(colHeader);
for (int row = 0; row < _grid.length; row++) {
var rowStr = "";
for (int col = 0; col < cols; col++) {
final gem = getGem(row, col);
if (col == 0) rowStr += "${row.toString().padLeft(3, " ")} |";
rowStr += " ${(gem?.type.toString() ?? "-").padLeft(3, " ")} |";
}
print(rowStr);
}
print("");
}
}