90 lines
2.1 KiB
Dart
90 lines
2.1 KiB
Dart
import 'dart:math';
|
|
import 'gem.dart';
|
|
import '../../utils/constants.dart';
|
|
|
|
class GameGrid {
|
|
late List<List<Gem?>> _grid;
|
|
final Random _random = Random();
|
|
|
|
GameGrid() {
|
|
_initializeGrid();
|
|
}
|
|
|
|
void _initializeGrid() {
|
|
_grid = List.generate(
|
|
GameConstants.gridHeight,
|
|
(row) => List.generate(
|
|
GameConstants.gridWidth,
|
|
(col) => Gem(
|
|
type: _random.nextInt(GameConstants.gemTypes.length),
|
|
row: row,
|
|
col: col,
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Gem? getGem(int row, int col) {
|
|
if (row < 0 ||
|
|
row >= GameConstants.gridHeight ||
|
|
col < 0 ||
|
|
col >= GameConstants.gridWidth) {
|
|
return null;
|
|
}
|
|
return _grid[row][col];
|
|
}
|
|
|
|
void setGem(int row, int col, Gem? gem) {
|
|
if (row >= 0 &&
|
|
row < GameConstants.gridHeight &&
|
|
col >= 0 &&
|
|
col < GameConstants.gridWidth) {
|
|
_grid[row][col] = gem;
|
|
}
|
|
}
|
|
|
|
List<List<Gem?>> get grid => _grid;
|
|
|
|
bool isValidPosition(int row, int col) {
|
|
return row >= 0 &&
|
|
row < GameConstants.gridHeight &&
|
|
col >= 0 &&
|
|
col < GameConstants.gridWidth;
|
|
}
|
|
|
|
clone() {
|
|
final clonedGrid = GameGrid();
|
|
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("");
|
|
}
|
|
}
|