Allow Swaps only if tiles are next to each other

main
Lachfrosch 2024-05-08 16:24:32 +02:00
parent 9d54871427
commit 7c89ee518e
1 changed files with 23 additions and 9 deletions

View File

@ -7,6 +7,7 @@ void main() {
class MyApp extends StatelessWidget {
const MyApp({super.key});
final int gridSize = 12;
// This widget is the root of your application.
@ -69,7 +70,8 @@ class _MyHomePageState extends State<MyHomePage> {
}
void _initializeGrid() {
_grid = List.generate(widget.gridSize, (_) => List.generate(widget.gridSize, (_) => Random().nextInt(5)));
_grid = List.generate(widget.gridSize,
(_) => List.generate(widget.gridSize, (_) => Random().nextInt(5)));
}
@override
@ -129,12 +131,24 @@ class _MyHomePageState extends State<MyHomePage> {
_selectedRow = row;
_selectedCol = col;
} else {
if (_isValidMove(_selectedRow, _selectedCol, row, col)) {
_swapTiles(_selectedRow, _selectedCol, row, col);
}
_selectedRow = -1;
_selectedCol = -1;
}
});
}
bool _isValidMove(int row1, int col1, int row2, int col2) {
// Check if the two tiles are adjacent
if ((row1 == row2 && (col1 - col2).abs() == 1) ||
(col1 == col2 && (row1 - row2).abs() == 1)) {
return true;
}
return false;
}
void _swapTiles(int row1, int col1, int row2, int col2) {
int temp = _grid[row1][col1];
_grid[row1][col1] = _grid[row2][col2];