Make `uncover` non-recursive

Fixes #35.
This commit is contained in:
Florine W. Dekker 2020-08-01 01:49:25 +02:00
parent ebb56ee7c1
commit 1450da5f1c
Signed by: FWDekker
GPG Key ID: B1B567AF58D6EE0F
2 changed files with 13 additions and 6 deletions

View File

@ -1,6 +1,6 @@
{
"name": "minesweeper",
"version": "0.0.42",
"version": "0.0.43",
"description": "Just Minesweeper!",
"author": "Felix W. Dekker",
"browser": "dist/bundle.js",

View File

@ -127,6 +127,9 @@ export class Field {
* @param square the square that was clicked on
*/
onUncover(square: Square): void {
if (square.isCovered)
throw new Error(`Cannot invoke 'onUncover' on covered square at (${square.x}, ${square.y}).`);
if (!this.started) {
this.started = true;
this.startTime = Date.now();
@ -256,11 +259,15 @@ export class Square {
uncover(): void {
if (!this.isCovered || this.hasFlag || this.field.won || this.field.lost) return;
this.isCovered = false;
this.hasFlag = false;
this.field.onUncover(this); // Also moves mine on first click
const uncoverQueue: Square[] = [this];
while (uncoverQueue.length > 0) {
const next = uncoverQueue.pop()!;
next.isCovered = false;
next.hasFlag = false;
this.field.onUncover(next); // Also moves mine on first click
if (!this.hasMine && this.getNeighborCount(it => it.hasMine) === 0)
this.chord();
if (!next.hasMine && next.getNeighborCount(it => it.hasMine) === 0)
uncoverQueue.push(...next.getNeighbors().filter(it => it.isCovered));
}
}
}