Swap 2 Tiles instead of randomly change color on click

main
Lachfrosch 2024-05-08 16:23:04 +02:00
parent 07bcec6fa1
commit 9d54871427
1 changed files with 17 additions and 3 deletions

View File

@ -59,6 +59,8 @@ class MyHomePage extends StatefulWidget {
class _MyHomePageState extends State<MyHomePage> {
late List<List<int>> _grid;
int _selectedRow = -1;
int _selectedCol = -1;
@override
void initState() {
@ -123,7 +125,19 @@ class _MyHomePageState extends State<MyHomePage> {
void _onTileTap(int row, int col) {
setState(() {
_grid[row][col] = Random().nextInt(5);
if (_selectedRow == -1 && _selectedCol == -1) {
_selectedRow = row;
_selectedCol = col;
} else {
_swapTiles(_selectedRow, _selectedCol, row, col);
_selectedRow = -1;
_selectedCol = -1;
}
});
}
void _swapTiles(int row1, int col1, int row2, int col2) {
int temp = _grid[row1][col1];
_grid[row1][col1] = _grid[row2][col2];
_grid[row2][col2] = temp;
}
}