Our app isn't playable yet:
All of this is coded in the mouseDown
event handler, and we also need a variable lastCellClicked
of type Cell
in the Board
class. Of course, this is exactly the cell which we get in the
mouseDown
event handler. So, we set this in line (5)
in the following code snippet:
void onMouseDown(MouseEvent e) { // same code as in Spiral 4 - if (cell.twin == lastCellClicked && lastCellClicked.shown) { (1) lastCellClicked.hidden = false; (2) if (memory.recalled) memory.hide(); (3) } else { new Timer(const Duration(milliseconds: 1000), () => cell.hidden = true); (4) } lastCellClicked = cell; (5) }
In line (1)
, we check whether the last clicked cell was the twin cell, and if this is still shown. Then we make sure in (2)
that it stays visible. shown
is a new getter in the Cell
class to make the code more readable: bool get shown => !hidden;
. If at that moment all cells are shown (the memory is recalled), we again hide them all in line (3)
. If the last clicked cell was not the twin cell, we hide the current cell after one second in line (4)
. recalled
is a simple getter (read-only property) in the Memory
class, and it makes use of a Boolean variable in Memory
that is initialized to false
(_recalled = false;
):
bool get recalled { if (!_recalled) { if (cells.every((c) => c.shown)) { (6) _recalled = true; } } return _recalled; }
In line (6)
, we test that if every cell is shown
then this variable is set to true
(the game is over). every
is a new method in Cells
and a nice functional way to write this is given as follows:
bool every(Function f) => list.every(f);
The hide
method is straightforward: hide every cell and reset the _recalled
variable to false
:
hide() { for (final cell in cells) cell.hidden = true; _recalled = false; }
That's it, our game works!
13.59.227.82