Allow Swaps only if tiles are next to each other
parent
9d54871427
commit
7c89ee518e
|
@ -7,6 +7,7 @@ void main() {
|
||||||
|
|
||||||
class MyApp extends StatelessWidget {
|
class MyApp extends StatelessWidget {
|
||||||
const MyApp({super.key});
|
const MyApp({super.key});
|
||||||
|
|
||||||
final int gridSize = 12;
|
final int gridSize = 12;
|
||||||
|
|
||||||
// This widget is the root of your application.
|
// This widget is the root of your application.
|
||||||
|
@ -69,7 +70,8 @@ class _MyHomePageState extends State<MyHomePage> {
|
||||||
}
|
}
|
||||||
|
|
||||||
void _initializeGrid() {
|
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
|
@override
|
||||||
|
@ -124,17 +126,29 @@ class _MyHomePageState extends State<MyHomePage> {
|
||||||
}
|
}
|
||||||
|
|
||||||
void _onTileTap(int row, int col) {
|
void _onTileTap(int row, int col) {
|
||||||
setState(() {
|
setState(() {
|
||||||
if (_selectedRow == -1 && _selectedCol == -1) {
|
if (_selectedRow == -1 && _selectedCol == -1) {
|
||||||
_selectedRow = row;
|
_selectedRow = row;
|
||||||
_selectedCol = col;
|
_selectedCol = col;
|
||||||
} else {
|
} else {
|
||||||
|
if (_isValidMove(_selectedRow, _selectedCol, row, col)) {
|
||||||
_swapTiles(_selectedRow, _selectedCol, row, col);
|
_swapTiles(_selectedRow, _selectedCol, row, col);
|
||||||
_selectedRow = -1;
|
|
||||||
_selectedCol = -1;
|
|
||||||
}
|
}
|
||||||
});
|
_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) {
|
void _swapTiles(int row1, int col1, int row2, int col2) {
|
||||||
int temp = _grid[row1][col1];
|
int temp = _grid[row1][col1];
|
||||||
_grid[row1][col1] = _grid[row2][col2];
|
_grid[row1][col1] = _grid[row2][col2];
|
||||||
|
|
Loading…
Reference in New Issue