Newer
Older
import 'dart:math';
import 'package:flutter_custom_toolbox/flutter_toolbox.dart';
import 'package:suguru/models/activity/cell.dart';
import 'package:suguru/models/activity/cell_location.dart';
class Board {
Board({
required this.cells,
required this.solvedCells,
});
BoardCells cells = const [];
BoardCells solvedCells = const [];
factory Board.createEmpty() {
return Board(
cells: [],
solvedCells: [],
);
}
factory Board.createFromCells({
required BoardCells cells,
required BoardCells solvedCells,
}) {
return Board(
cells: cells,
solvedCells: solvedCells,
);
}
void createFromTemplate({
required String template,
}) {
printlog('Creating board from template:');
printlog(template);
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
final List<String> templateParts = template.split(';');
if (templateParts.length != 3) {
printlog('Failed to get grid template (wrong format)...');
}
final String boardSizeAsString = templateParts[0];
final String blocksDefinitionAsString = templateParts[1];
final String fixedCellsDefinitionAsString = templateParts[2];
final int boardSizeHorizontal = int.parse(boardSizeAsString.split('x')[0]);
final int boardSizeVertical = int.parse(boardSizeAsString.split('x')[1]);
const String stringValues = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
int index = 0;
for (int rowIndex = 0; rowIndex < boardSizeVertical; rowIndex++) {
final List<Cell> row = [];
for (int colIndex = 0; colIndex < boardSizeHorizontal; colIndex++) {
final String blockId = blocksDefinitionAsString[index];
final String cellValueAsString = fixedCellsDefinitionAsString[index];
index++;
final int cellValue = stringValues.indexOf(cellValueAsString);
row.add(Cell(
location: CellLocation.go(rowIndex, colIndex),
blockId: blockId,
value: cellValue,
isFixed: (cellValue != 0),
));
}
cells.add(row);
}
// Do some transformations to board
transformBoard();
// Force cells fixed states (all cells with value != 0)
for (CellLocation location in getCellLocations()) {
final Cell cell = get(location);
cells[location.row][location.col] = Cell(
location: location,
blockId: cell.blockId,
value: cell.value,
isFixed: (cell.value != 0) ? true : false,
);
}
final Board solvedBoard = SuguruSolver.resolve(this);
solvedCells = solvedBoard.cells;
// FIXME: for debug only
// to start with a board (almost) automatically solved
// cells = solvedCells;
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
}
// Helper to create board from size, with "empty" cells
static BoardCells createEmptyBoard(final int width, final int height) {
final BoardCells cells = [];
for (int rowIndex = 0; rowIndex < height; rowIndex++) {
final List<Cell> row = [];
for (int colIndex = 0; colIndex < width; colIndex++) {
row.add(Cell(
location: CellLocation.go(rowIndex, colIndex),
blockId: '',
value: 0,
isFixed: false,
));
}
cells.add(row);
}
return cells;
}
List<CellLocation> getCellLocations([String? blockId]) {
if (cells.isEmpty) {
return [];
}
final List<CellLocation> locations = [];
final int boardSizeVertical = cells.length;
final int boardSizeHorizontal = cells[0].length;
for (int row = 0; row < boardSizeVertical; row++) {
for (int col = 0; col < boardSizeHorizontal; col++) {
if ((blockId == null) || (blockId == get(CellLocation.go(row, col)).blockId)) {
locations.add(CellLocation.go(row, col));
}
}
}
return locations;
}
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
void transformBoard() {
final int boardSizeVertical = cells.length;
final int boardSizeHorizontal = cells[0].length;
const List<String> allowedFlip = ['none', 'horizontal', 'vertical'];
List<String> allowedRotate = ['none', 'left', 'right', 'upsidedown'];
// Limit rotation if board is not symetric
if (boardSizeVertical != boardSizeHorizontal) {
allowedRotate = ['none', 'upsidedown'];
}
final Random rand = Random();
final String flip = allowedFlip[rand.nextInt(allowedFlip.length)];
final String rotate = allowedRotate[rand.nextInt(allowedRotate.length)];
switch (flip) {
case 'horizontal':
{
transformFlipHorizontal();
}
break;
case 'vertical':
{
transformFlipVertical();
}
break;
}
switch (rotate) {
case 'left':
{
transformRotateLeft();
}
break;
case 'right':
{
transformRotateRight();
}
break;
case 'upsidedown':
{
transformFlipHorizontal();
transformFlipVertical();
}
break;
}
}
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
void transformFlipHorizontal() {
final BoardCells transformedBoard = copyCells();
final int boardSizeVertical = cells.length;
for (CellLocation location in getCellLocations()) {
final Cell cell = cells[boardSizeVertical - location.row - 1][location.col];
transformedBoard[location.row][location.col] = Cell(
location: location,
blockId: cell.blockId,
value: cell.value,
isFixed: false,
);
}
cells = transformedBoard;
}
void transformFlipVertical() {
if (cells.isEmpty) {
return;
}
final BoardCells transformedBoard = copyCells();
final int boardSizeHorizontal = cells[0].length;
for (CellLocation location in getCellLocations()) {
final Cell cell = cells[location.row][boardSizeHorizontal - location.col - 1];
transformedBoard[location.row][location.col] = Cell(
location: location,
blockId: cell.blockId,
value: cell.value,
isFixed: false,
);
}
cells = transformedBoard;
}
void transformRotateLeft() {
final BoardCells transformedBoard = copyCells();
final int boardSizeVertical = cells.length;
for (CellLocation location in getCellLocations()) {
final Cell cell = cells[location.col][boardSizeVertical - location.row - 1];
transformedBoard[location.row][location.col] = Cell(
location: location,
blockId: cell.blockId,
value: cell.value,
isFixed: false,
);
}
cells = transformedBoard;
}
void transformRotateRight() {
if (cells.isEmpty) {
return;
}
final BoardCells transformedBoard = copyCells();
final int boardSizeHorizontal = cells[0].length;
for (CellLocation location in getCellLocations()) {
final Cell cell = cells[boardSizeHorizontal - location.col - 1][location.row];
transformedBoard[location.row][location.col] = Cell(
location: location,
blockId: cell.blockId,
value: cell.value,
isFixed: false,
);
}
cells = transformedBoard;
}
bool inBoard(CellLocation location) {
return (location.row >= 0 &&
location.row < cells.length &&
location.col >= 0 &&
location.col < cells[location.row].length);
}
if (inBoard(location)) {
return cells[location.row][location.col];
}
return Cell.none;
}
void setCell(CellLocation location, Cell cell) {
if (inBoard(location)) {
cells[location.row][location.col] = cell;
}
}
void setValue(CellLocation location, int value) {
Cell currentCell = get(location);
setCell(
location,
Cell(
blockId: currentCell.blockId,
isFixed: currentCell.isFixed,
location: location,
value: value,
));
}
void applyMove(Move move) {
// printlog('put ${move.value} in ${move.location}');
setValue(move.location, move.value);
}
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
List<String> getBlockIds() {
List<String> blockIds = [];
for (CellLocation location in getCellLocations()) {
final String blockId = get(location).blockId;
if (!blockIds.contains(blockId)) {
blockIds.add(blockId);
}
}
return blockIds;
}
List<int> getValuesInBlock(String blockId) {
final List<int> values = [];
for (CellLocation location in getCellLocations()) {
if (get(location).blockId == blockId) {
values.add(get(location).value);
}
}
return values;
}
BoardCells copyCells() {
final BoardCells copiedGrid = [];
for (int rowIndex = 0; rowIndex < cells.length; rowIndex++) {
final List<Cell> row = [];
for (int colIndex = 0; colIndex < cells[rowIndex].length; colIndex++) {
final Cell cell = cells[rowIndex][colIndex];
row.add(Cell(
location: CellLocation.go(rowIndex, colIndex),
blockId: cell.blockId,
value: cell.value,
isFixed: false,
));
}
copiedGrid.add(row);
}
return copiedGrid;
}
bool isSolved() {
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
for (CellLocation location in getCellLocations()) {
if (get(location).value == 0) {
return false;
}
}
// check each block contains all values from 1 to block size
for (String blockId in getBlockIds()) {
List<int> values = [];
List<int> duplicateValues = [];
for (CellLocation location in getCellLocations()) {
if (get(location).blockId == blockId) {
final int value = get(location).value;
if (value != 0) {
if (!values.contains(value)) {
values.add(value);
} else {
duplicateValues.add(value);
}
}
}
}
for (int duplicateValue in duplicateValues) {
for (CellLocation location in getCellLocations()) {
if (get(location).blockId == blockId && get(location).value == duplicateValue) {
return false;
}
}
}
}
if (boardHasSiblingWithSameValue()) {
return false;
}
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
return true;
}
int getMaxValueForBlock(String? blockId) {
int maxValue = 0;
for (CellLocation location in getCellLocations()) {
if (get(location).blockId == blockId) {
maxValue++;
}
}
return maxValue;
}
List<int> getMissingValuesInBlock(String blockId) {
List<int> missingValues = [];
final List<int> values = getValuesInBlock(blockId);
final List<int> expectedValues =
List<int>.generate(getMaxValueForBlock(blockId), (i) => i + 1);
for (int candidateValue in expectedValues) {
if (!values.contains(candidateValue)) {
missingValues.add(candidateValue);
}
}
return missingValues;
}
List<Move> getLastEmptyCellsInBlocks() {
List<Move> candidateCells = [];
for (CellLocation location in getCellLocations()) {
final Cell cell = get(location);
if (cell.value == 0) {
final int blockSize = getMaxValueForBlock(cell.blockId);
final List<int> blockValues = getValuesInBlock(cell.blockId);
blockValues.removeWhere((value) => value == 0);
if (blockValues.length == blockSize - 1) {
int candidateValue = 0;
for (int value = 1; value <= blockSize; value++) {
if (!blockValues.contains(value)) {
candidateValue = value;
}
}
candidateCells.add(Move(location: location, value: candidateValue));
}
}
}
return candidateCells;
}
List<Move> getOnlyCellInBlockWithoutConflict() {
List<Move> candidateCells = [];
for (String blockId in getBlockIds()) {
List<int> missingValuesInBlock = getMissingValuesInBlock(blockId);
for (int candidateValue in missingValuesInBlock) {
final List<CellLocation> allowedCellsForThisValue = [];
for (CellLocation location in getCellLocations(blockId)) {
if (get(location).value == 0) {
if (isValueAllowed(location, candidateValue)) {
allowedCellsForThisValue.add(location);
}
}
}
if (allowedCellsForThisValue.length == 1) {
final CellLocation candidateLocation = allowedCellsForThisValue[0];
candidateCells.add(Move(location: candidateLocation, value: candidateValue));
}
}
}
return candidateCells;
}
List<Move> getEmptyCellsWithUniqueAvailableValue() {
List<Move> candidateCells = [];
for (CellLocation location in getCellLocations()) {
if (get(location).value == 0) {
int allowedValuesCount = 0;
int candidateValue = 0;
final int maxValueForThisCell = getMaxValueForBlock(get(location).blockId);
for (int value = 1; value <= maxValueForThisCell; value++) {
if (isValueAllowed(location, value)) {
candidateValue = value;
allowedValuesCount++;
}
}
if (allowedValuesCount == 1) {
candidateCells.add(Move(location: location, value: candidateValue));
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
}
}
}
return candidateCells;
}
bool blockContainsDuplicates(String blockId, [int? candidateValue]) {
List<int> duplicateValues = [];
List<int> values = [];
if (candidateValue != null) {
values.add(candidateValue);
}
for (CellLocation location in getCellLocations(blockId)) {
final int value = get(location).value;
if (value != 0) {
if (!values.contains(value)) {
values.add(value);
} else {
duplicateValues.add(value);
}
}
}
return duplicateValues.isNotEmpty;
}
bool boardHasSiblingWithSameValue() {
for (CellLocation location in getCellLocations()) {
final int value = get(location).value;
if (value != 0 && cellHasSiblingWithSameValue(location)) {
return true;
}
}
return false;
}
bool cellHasSiblingWithSameValue(CellLocation cellLocation, [int? candidateValue]) {
if (cells.isEmpty) {
return false;
}
final int value = candidateValue ?? get(cellLocation).value;
if (value != 0) {
for (int deltaCol in [-1, 0, 1]) {
for (int deltaRow in [-1, 0, 1]) {
final CellLocation siblingLocation =
CellLocation.go(cellLocation.row + deltaRow, cellLocation.col + deltaCol);
if (inBoard(siblingLocation) && !(deltaRow == 0 && deltaCol == 0)) {
if (get(siblingLocation).value == value) {
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
return true;
}
}
}
}
}
return false;
}
bool isValueAllowed(CellLocation? location, int value) {
if ((location == null) || (value == 0)) {
return true;
}
// check siblings
if (cellHasSiblingWithSameValue(location, value)) {
return false;
}
// check block does not contain duplicates
if (blockContainsDuplicates(get(location).blockId, value)) {
return false;
}
return true;
}
void dump() {
const String stringValues = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
printlog('');
printlog('- blocks / values / solved -');
printlog('-------');
if (cells.isEmpty) {
printlog('empty board');
} else {
for (int rowIndex = 0; rowIndex < cells.length; rowIndex++) {
String rowBlocks = '';
String rowValues = '';
String rowSolved = '';
for (int colIndex = 0; colIndex < cells[rowIndex].length; colIndex++) {
rowBlocks += cells[rowIndex][colIndex].blockId;
rowValues += stringValues[cells[rowIndex][colIndex].value];
if (solvedCells.isEmpty) {
rowSolved += '*';
} else {
final int solvedValue = solvedCells[rowIndex][colIndex].value;
if (solvedValue == 0) {
rowSolved += ' ';
} else {
rowSolved += stringValues[solvedCells[rowIndex][colIndex].value];
}
}
}
printlog('$rowBlocks | $rowValues | $rowSolved');
}
}
printlog('-------');
printlog('');
}
@override
String toString() {
return '$Board(${toJson()})';
}
Map<String, dynamic>? toJson() {
return <String, dynamic>{
'cells': cells,
};
}
}