Move first-click mines to random places

Fixes #106.
This commit is contained in:
Florine W. Dekker 2024-05-10 13:23:34 +02:00
parent 144f378fc1
commit fcd0207aa3
Signed by: FWDekker
GPG Key ID: D3DCFAA8A4560BE0
4 changed files with 18 additions and 16 deletions

BIN
package-lock.json generated

Binary file not shown.

View File

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

View File

@ -168,20 +168,10 @@ export class Field {
this.runUndoably(() => {
const square = this.getSquare(coords);
if (square.hasMine) {
const target = this.squareList.find(it => !it.hasMine && it !== square)!;
this.runAction(swapAction(square, target));
}
const from = [square].concat(square.neighbors).filter(it => it.hasMine);
const to = this.squareList.filter(it => !it.hasMine && from.indexOf(it) < 0).slice(0, from.length);
square.neighbors
.filter(it => it.hasMine)
.forEach(it => {
const target = this.squareList
.find(it => !it.hasMine && it !== square && square.neighbors.indexOf(it) < 0);
if (target !== undefined)
this.runAction(swapAction(it, target));
});
from.slice(0, to.length).forEach(it => this.runAction(swapAction(it, this.random.pop(to)!)));
});
}

View File

@ -31,12 +31,24 @@ export class Random {
/**
* Returns a random element from `array`, or `undefined` if the array is empty.
*
* @param array the array to return a random element from
* @param array the array to return a random element of
*/
pick<T>(array: T[]): T | undefined {
get<T>(array: T[]): T | undefined {
return array[this.uniform(0, array.length)];
}
/**
* Removes and returns a random element from `array`, or returns `undefined` if the array is empty.
*
* @param array the array to remove and return a random element of
*/
pop<T>(array: T[]): T | undefined {
const idx = this.uniform(0, array.length);
const item = array[idx];
if (idx >= 0) array.splice(idx, 1);
return item;
}
/**
* Shuffles the elements of `array` in-place.
*