diff --git a/lib/main.dart b/lib/main.dart index 73c4823..71e1186 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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 { } 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 @@ -124,17 +126,29 @@ class _MyHomePageState extends State { } void _onTileTap(int row, int col) { - setState(() { - if (_selectedRow == -1 && _selectedCol == -1) { - _selectedRow = row; - _selectedCol = col; - } else { + setState(() { + if (_selectedRow == -1 && _selectedCol == -1) { + _selectedRow = row; + _selectedCol = col; + } else { + if (_isValidMove(_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) { int temp = _grid[row1][col1]; _grid[row1][col1] = _grid[row2][col2];