Skip to content

Instantly share code, notes, and snippets.

@nofishleft nofishleft/mines.js
Last active Mar 1, 2019

Embed
What would you like to do?
Node module to add minesweeper to any discord bot
//Example Usage:
/*
const mines = require('./mines.js');
let msg = mines(14,14,20,'X',true);
*/
//X - Width
//Y - Height
//char - Character to represent bombs
// (used internally and if formatted == false, externally to represent the bombs)
//formatted - Toggles what to output:
// formatted == True : Output string formatted with linebreaks and emojis
// formatted == False : Output the raw 2D Array
let app = function (X, Y, mines, char, formatted) {
//Create blank map
let grid = new Array(Y);
for (let y = 0; y < Y; ++y) {
grid[y] = new Array(X);
for (let x = 0; x < X; ++x) {
grid[y][x] = 0;
}
}
//Spawn mines
for (let i = 0; i < mines; ++i) {
let x,y;
while (grid[y = Math.floor(Math.random()*Y)][x = Math.floor(Math.random()*X)] == char) {}
grid[y][x] = char;
//Increment counter on surrounding squares
for (let yr = y-1; yr <= y + 1; ++yr) {
for (let xr = x-1; xr <= x + 1; ++xr) {
if (xr >= 0 && xr < X && yr >= 0 && yr < Y && grid[yr][xr] >= 0) grid[yr][xr]++;
}
}
}
return formatted ? app.format(grid, X, Y, char) : grid;
};
app.format = function (grid, X, Y, char) {
let strArray = [];
for (let y = 0; y < Y; ++y) {
//strArray[y] = `||\`${grid[y].join("\`||||\`")}\`||`;
strArray[y] = `||${grid[y].join("||||")}||`;
}
const bombex = new RegExp(char, "gi");
return strArray.join('\n')
.replace(bombex, ":bomb:")
.replace(/0/gi, ":white_large_square:")
//.replace(/0/gi, ":zero:")
.replace(/1/gi, ":one:")
.replace(/2/gi, ":two:")
.replace(/3/gi, ":three:")
.replace(/4/gi, ":four:")
.replace(/5/gi, ":five:")
.replace(/6/gi, ":six:")
.replace(/7/gi, ":seven:")
.replace(/8/gi, ":eight:");
};
module.exports = app;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.