1.0.1 • Published 7 years ago

bombsweeper.js v1.0.1

Weekly downloads
286
License
ISC
Repository
github
Last release
7 years ago

bombsweeper.js

Build Status Codacy Badge

A JavaScript module that implements state management for a Minesweeper style bombsweeper.

Installation

npm install --save bombsweeper.js

Usage

import BombSweeper from 'bombsweeper.js';

const bombsweeper = new BombSweeper(8, 8); // create a bombsweeper board at 8x8

bombsweeper.onWin = () => { alert('Win!'); }; // callback invoked on win
bombsweeper.onLoss = () => { alert('Lose!'); }; // callback invoked on loss

bombsweeper.PlaceBombs(10); // places 10 bombs randomly

// rendering game based on the following:
bombsweeper.board;
bombsweeper.mask;

// ...
bombsweeper.CheckCell(0, 0); // user clicked cell at 0, 0
// ...

Methods

You can interact with the bombsweeper state after creation:

const bombsweeper = new BombSweeper(width, height);

.PlaceBomb(x, y)

Places a bomb at the specified (x, y) coordinates and increments any non-bomb adjacent cells. You most likely won't be using this method as .PlaceBombs(count) is a better fit for most use cases.

const bombsweeper = new BombSweeper(5, 5);
bombsweeper.PlaceBomb(1,1);

/*
    0 0 0 0 0
    0 1 1 1 0
    0 1 * 1 0
    0 1 1 1 0
    0 0 0 0 0
*/

.PlaceBombs(count)

This will randomly place count bombs on the bombsweeper board, utilising the .PlaceBomb(x, y) method mentioned above.

const bombsweeper = new BombSweeper(5, 5);
bombsweeper.PlaceBombs(4);

/*
    * * 1 0 0
    2 3 2 1 0
    0 1 * 1 0
    0 1 1 2 1
    0 0 0 1 *
*/

If the count supplied is greater than the area of the board, .PlaceBombs() will run until the board has been filled.

.CheckCell(x, y)

This method is used to chip through the mask, flood filling if a zero cell is selected and checking win/loss all in one.

const bombsweeper = new BombSweeper(5, 5);
bombsweeper.PlaceBombs(4);

/*
    Board:      Mask:
    * * 1 0 0   F F F F F
    2 3 2 1 0   F F F F F
    0 1 * 1 0   F F F F F
    0 1 1 2 1   F F F F F
    0 0 0 1 *   F F F F F
*/

bombsweeper.CheckCell(3, 0); // flood fill

/*
    Board:      Mask:
    * * 1 0 0   F F F T T
    2 3 2 1 0   F F F F T
    0 1 * 1 0   F F F F T
    0 1 1 2 1   F F F F F
    0 0 0 1 *   F F F F F
*/

bombsweeper.CheckCell(1, 1); // numeric cell > 0

/*
    Board:      Mask:
    * * 1 0 0   F F F T T
    2 3 2 1 0   F T F F T
    0 1 * 1 0   F F F F T
    0 1 1 2 1   F F F F F
    0 0 0 1 *   F F F F F
*/