/
memory.dart
82 lines (70 loc) · 1.59 KB
/
memory.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
77
78
79
80
part of educ_memory_game;
class Memory {
int length;
bool _recalled = false;
Cells cells;
List usedColors = [];
Memory(this.length) {
if (length.isOdd) {
throw new Exception(
'Memory length must be an even integer: ${length}.');
}
cells = new Cells();
var cell, twinCell;
for (var x = 0; x < length; x++) {
for (var y = 0; y < length; y++) {
cell = getCell(y, x);
if (cell == null) {
cell = new Cell(this, y, x);
cell.color = _getFreeRandomColor();
cells.add(cell);
twinCell = _getFreeRandomCell();
cell.twin = twinCell;
twinCell.twin = cell;
twinCell.color = cell.color;
cells.add(twinCell);
}
}
}
}
Cell getCell(int row, int column) {
for (Cell cell in cells) {
if (cell.intersects(row, column)) {
return cell;
}
}
}
Cell _getFreeRandomCell() {
var row;
var column;
Cell cell;
do {
row = randomInt(length);
column = randomInt(length);
cell = getCell(row, column);
} while (cell != null);
return new Cell(this, row, column);
}
String _getFreeRandomColor() {
var color;
do {
color = randomColor();
} while (usedColors.any((c) => c == color));
usedColors.add(color);
return color;
}
bool get recalled {
if (!_recalled) {
if (cells.every((c) => c.shown)) {
_recalled = true;
}
}
return _recalled;
}
hide() {
for (final cell in cells) {
cell.hidden = true;
}
_recalled = false;
}
}