56 lines
1.5 KiB
Dart
56 lines
1.5 KiB
Dart
import 'dart:math';
|
|
import '../models/gem.dart';
|
|
import '../models/grid.dart';
|
|
import '../../utils/constants.dart';
|
|
|
|
class GravitySystem {
|
|
static void applyGravity(GameGrid grid) {
|
|
for (int col = 0; col < GameConstants.gridWidth; col++) {
|
|
_dropColumn(grid, col);
|
|
}
|
|
}
|
|
|
|
static List<Gem> generateGems(GameGrid grid) {
|
|
// Fill empty spaces with new gems
|
|
final random = Random();
|
|
final List<Gem> newGems = [];
|
|
for (int row = 0; row < GameConstants.gridHeight; row++) {
|
|
for (int col = 0; col < GameConstants.gridWidth; col++) {
|
|
if (grid.getGem(row, col) == null) {
|
|
final gem = Gem(
|
|
row: row,
|
|
col: col,
|
|
type: random.nextInt(GameConstants.gemTypes.length),
|
|
);
|
|
newGems.add(gem);
|
|
grid.setGem(row, col, gem);
|
|
}
|
|
}
|
|
}
|
|
return newGems;
|
|
}
|
|
|
|
static void _dropColumn(GameGrid grid, int col) {
|
|
final gems = <Gem>[];
|
|
|
|
// Collect non-null gems from bottom to top
|
|
for (int row = GameConstants.gridHeight - 1; row >= 0; row--) {
|
|
final gem = grid.getGem(row, col);
|
|
if (gem != null) {
|
|
gems.add(gem);
|
|
}
|
|
}
|
|
|
|
// Clear column
|
|
for (int row = 0; row < GameConstants.gridHeight; row++) {
|
|
grid.setGem(row, col, null);
|
|
}
|
|
|
|
// Place gems at bottom
|
|
for (int i = 0; i < gems.length; i++) {
|
|
final newRow = GameConstants.gridHeight - 1 - i;
|
|
grid.setGem(newRow, col, gems[i].copyWith(row: newRow, col: col));
|
|
}
|
|
}
|
|
}
|