Estoy desarrollando el juego del sudoku para aprender flutter. Estoy intentando hacer que al señalar una casilla del tablero de sudoku, ésta se pinte de verde. Esto lo realizo mediante cubit para guardar el estado de todo el juego.
Sospecho que fue al cambiar los widgets que se rompió esta funcionalidad porque antes funcionaba con un Table en vez de con Columns y Rows.
Os muestro el código a continuación:
En PlayScreen es donde inicializo el cubit con los datos del juego porque es la pantalla que va a mostrar el tablero y la botonera.
class PlayScreen extends StatelessWidget {
final int level;
const PlayScreen({Key? key, required this.level}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => sl<GameCubit>()..initialState(level),
child: BlocBuilder<GameCubit, Game>(builder: (context, game) => WillPopScope(
child: Scaffold(
appBar: AppBar(
title: const Text('Sudoku'),
),
backgroundColor: primaryBackgroundColor,
body: Column(
children: const [
Expanded(
child: Padding(
padding: EdgeInsets.all(10.0),
child: SudokuBoard(),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.all(10.0),
child: KeyPad(),
),
),
],
),
)
))
);
}
}
En SudouBoard es donde genero el tablero del juego
class SudokuBoard extends StatelessWidget {
const SudokuBoard({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: List.generate(9, (int rowNumber ) {
return _getRow(context, rowNumber);
})
);
}
Widget _getRow(BuildContext context, int row) {
return Expanded(
child: Row(
children: List.generate(9, (int col) {
return Expanded(
child: Center(
child: SudokuCell(row: row, col: col)
),
);
})
)
);
}
}
En SudokuCell es donde se genera cada casilla con los datos correspondientes:
class SudokuCell extends StatelessWdget {
final int row, col;
const SudokuCell({Key? key, required this.row, required this.col}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocBuilder<GameCubit, Game>(
builder: (context, game) {
var cell = game.board!.cells[row][col];
var ss = cell.cellStatus;
return InkResponse(
enableFeedback: true,
onTap: () {
if (!cell.initial) {
BlocProvider.of<GameCubit>(context, listen: false)
.setPosition(row, col);
}
},
child: Container(
padding: EdgeInsets.zero,
margin: EdgeInsets.zero,
decoration: BoxDecoration(
color: cell.initial ? Colors.grey : getColorCellByStatus(cell),
border: Border(
right: BorderSide(
width: (col % 3 == 2) ? 2.0 : 1.0,
color: Colors.black,
),
bottom: BorderSide(
width: (row % 3 == 2) ? 2.0 : 1.0,
color: Colors.black,
),
top: BorderSide(
width: (row == 0) ? 2.0 : 1.0,
color: Colors.black,
),
left: BorderSide(
width: (col == 0) ? 2.0 : 1.0,
color: Colors.black,
),
),
),
child: Center(
child: Text(
cell.value.toString(),
style: TextStyle(
fontSize: 25,
fontWeight:
cell.initial ? FontWeight.bold : FontWeight.normal
),
),
),
)
);
}
);
}
Color getColorCellByStatus(Cell cell){
switch (cell.cellStatus) {
case CellState.selected:
return Colors.lightGreen;
case CellState.error:
return Colors.red;
default:
return Colors.white;
}
}
}
La llamada a la función del cubit la realiza perfectamente.
class GameCubit extends Cubit<Game> {
//TODO quitar _board cuando vaya dinamico
late Board _board;
GameCubit(this._persistenceRepository, this._gameRepository) : super(Game(id: '0', initialBoard: Board(cells: []), gameStatus: GameState.initial, selectedRow: -1, selectedCol: -1));
final GameLocalDataSource _persistenceRepository;
final GameRepository _gameRepository;
Future<void> initialState(int level) async {
//editado 2 -->
_board = Board(cells: _getInitialBoard());
Game game = Game(id: '0',initialBoard: _board, board:_board,gameStatus: GameState.initial, selectedRow: -1, selectedCol: -1);
emit(game);
}
// editado -->
void setPosition(int row, int col){
_board = state.board!;
if (state.selectedRow != -1 && state.selectedCol != -1){
_board.cells[state.selectedRow][state.selectedCol].cellStatus = CellState.none;
}
_board.cells[row][col].cellStatus = CellState.selected;
Game game = state.copyWith(
board: _board,
selectedRow: row,
selectedCol: col
);
emit(game);
}
void setSelectedCell(int num){
List<List<Cell>> cells = List.from(state.board!.cells);
Cell cell = Cell(initial: false, value: num);
cells[state.selectedRow][state.selectedCol] = cell;
cells[state.selectedRow][state.selectedCol].cellStatus = CellState.none;
if (num != 0){
bool isValid = _gameRepository.checkValue(cells, state.selectedRow, state.selectedCol);
if (!isValid) {
cells[state.selectedRow][state.selectedCol].cellStatus = CellState.error;
}
}
Game game = Game(id: state.id,initialBoard: state.initialBoard,board: Board(cells: cells), gameStatus: state.gameStatus, selectedRow: state.selectedRow, selectedCol: state.selectedCol);
emit(game);
}
}
Para inicializar el cubit y los repositorios uso getit con una clase donde tengo la iyección de dependencias:
final sl = GetIt.instance;
Future<void> init() async {
//...
sl.registerFactory(
() => GameCubit(
sl(),
sl()
)
);
//...
}
Añado la clase Game
enum GameState {
initial,
partial,
completed
}
@JsonSerializable()
class Game extends Equatable {
String id;
Board initialBoard;
Board? board;
GameState gameStatus;
int selectedRow;
int selectedCol;
// final DateTime time;
Game({required this.id, required this.initialBoard, this.board, required this.gameStatus, required this.selectedRow,required this.selectedCol});
factory Game.fromJson(Map<String, dynamic> jsonDecoded) => _$GameFromJson(jsonDecoded);
Map<String, dynamic> toJson() => _$GameToJson(this);
//editado 2 -->
Game copyWith({
String? id,
Board? initialBoard,
Board? board,
GameState? gameStatus,
int? selectedRow,
int? selectedCol,
}) {
return Game(
id: id ?? this.id,
initialBoard: initialBoard ?? this.initialBoard,
board: board != null ? this.board?.copyWith(board: board.cells) : this.board,
gameStatus: gameStatus ?? this.gameStatus,
selectedRow: selectedRow ?? this.selectedRow,
selectedCol: selectedCol ?? this.selectedCol,
);
}
// Editado 2 <--
// Editado -->
@override
List<Object?> get props => [id, board, gameStatus];
// Editado <--
}
Añado las clases Board y Cell
class Board extends Equatable {
late List<List<Cell>> cells;
Board({required this.cells});
@override
List<Object?> get props => [cells];
Board copyWith({
List<List<Cell>>? cells
}) {
return Board(
cells: cells ?? this.cells
);
}
factory Board.fromJson(Map<String, dynamic> jsonDecoded) => _$BoardFromJson(jsonDecoded);
Map<String, dynamic> toJson() => _$BoardToJson(this);
}
enum CellState {
none,
selected,
error
}
@JsonSerializable()
class Cell extends Equatable{
bool initial;
int value;
CellState cellStatus;
Cell(
{required this.initial, required this.value, this.cellStatus = CellState.none});
@override
List<Object?> get props => [initial, value, cellStatus];
factory Cell.fromJson(Map<String, dynamic> jsonDecoded) => _$CellFromJson(jsonDecoded);
Map<String, dynamic> toJson() => _$CellToJson(this);
}
UPDATE
Al final he añadido al props del Game las dos variables que modifico:
class Game extends Equatable {
String id;
Board initialBoard;
Board? board;
GameState gameStatus;
int selectedRow;
int selectedCol;
Game({required this.id, required this.initialBoard, this.board, required this.gameStatus, required this.selectedRow,required this.selectedCol});
@override
List<Object?> get props => [id, board, gameStatus, selectedRow, selectedCol];
factory Game.fromJson(Map<String, dynamic> jsonDecoded) => _$GameFromJson(jsonDecoded);
Map<String, dynamic> toJson() => _$GameToJson(this);
Game copyWith({
String? id,
Board? initialBoard,
Board? board,
GameState? gameStatus,
int? selectedRow,
int? selectedCol,
}) {
return Game(
id: id ?? this.id,
initialBoard: initialBoard ?? this.initialBoard,
board: board != null ? this.board?.copyWith(cells: board.cells) : this.board,
gameStatus: gameStatus ?? this.gameStatus,
selectedRow: selectedRow ?? this.selectedRow,
selectedCol: selectedCol ?? this.selectedCol,
);
}
}
En GameCubit cambio la función setPosition por lo siguiente
void setPosition(int row, int col){
_board = state.board!;
if (state.selectedRow != -1 && state.selectedCol != -1){
final Cell cell = _board.cells[state.selectedRow][state.selectedCol];
_board.cells[state.selectedRow][state.selectedCol] = cell.copyWith(cellStatus:CellState.none);
}
final Cell cell = _board.cells[row][col];
_board.cells[row][col] = cell.copyWith(cellStatus: CellState.selected);
Game game = state.copyWith(
board: _board,
selectedRow: row,
selectedCol: col
);
print(state);
print(game);
emit(game);
}
Y por último, la clase Cell, le indico la función copyWith
enum CellState {
none,
selected,
error
}
@JsonSerializable()
class Cell extends Equatable{
bool initial;
int value;
CellState cellStatus;
Cell(
{required this.initial, required this.value, this.cellStatus = CellState.none});
@override
List<Object?> get props => [initial, value, cellStatus];
Cell copyWith({
bool? initial,
int? value,
CellState? cellStatus
}) {
return Cell(
initial: initial ?? this.initial,
value: value ?? this.value,
cellStatus: cellStatus ?? this.cellStatus
);
}
factory Cell.fromJson(Map<String, dynamic> jsonDecoded) => _$CellFromJson(jsonDecoded);
Map<String, dynamic> toJson() => _$CellToJson(this);
}
Game
? y otra pregunta, cada vez que entra asetPosition
al emit, te aseguraste de que el objeto emitido es diferente al anterior? le agregaste unos prints para validar? Sabes si logra entrar nuevamente al builder: (context, game) { del SudokuCell?