JSFiddle - React, Tailwind, and code Playground
by phloe
JavaScript
var mine = "*";
var width = 20;
var height = 20;
var difficulty = 4;
var mines = Math.floor(((width * height) / 10) * difficulty);
var level = Array(width * height + 1).join(" ").split("");
var length = level.length;
while (mines) {
var index = Math.floor(Math.random() * length);
if (level[index] !== mine) {
level[index] = mine;
mines--;
}
}
var index = 0;
while (index < length) {
if (level[index] !== mine) {
var x = index % width;
var x1 = x - ((x > 0) ? 1 : 0);
var x2 = x + ((x < width - 1) ? 1 : 0);
var y = Math.floor(index / width);
var y1 = y - ((y > 0) ? 1 : 0);
var y2 = y + ((y < height - 1) ? 1 : 0);
var neighbours = (
level.slice(y1 * width + x1, y1 * width + x2)
).concat(
level.slice(y * width + x1, y * width + x2)
).concat(
level.slice(y2 * width + x1, y2 * width + x2)
);
level[index] = neighbours.filter(function(char){
return char === mine;
}).length;
}
index++;
}
console.log("minesweeper map", level);
var d = document;
var table = d.createElement("table");
var tbody = d.createElement("tbody");
var tr, td;
var index = 0;
while (index < length) {
x = index % width;
y = Math.floor(index / width);
if (!x) {
if (tr) {
tbody.appendChild(tr);
}
tr = d.createElement("tr");
}
td = d.createElement("td");
td.innerHTML = level[index];
tr.appendChild(td);
index++;
}
tbody.appendChild(tr);
table.appendChild(tbody);
document.body.appendChild(table);