Note: The numbers on the board are generated just like in a real Minesweeper game, but they’re purely cosmetic — they don’t encode any part of the message. The real data is entirely in the pattern of mines (*) and empty cells (.), read left to right, row by row.
function textToBinary(text) {
return text
.split('')
.map(c => c.charCodeAt(0).toString(2).padStart(8, '0'))
.join('');
}
function binaryToGrid(binary, size = 9) {
const maxBits = size * size;
binary = binary.slice(0, maxBits);
const grid = Array.from({ length: size }, () => Array(size).fill('.'));
for (let i = 0; i < Math.min(binary.length, size * size);length; i++) {
const row = Math.floor(i / size);
const col = i % size;
grid[row][col] = binary[i] === '1' ? '*' : '.';
}
return grid;
}
function computeHints(grid) {
const size = grid.length;
const result = grid.map(row => row.slice());
const directionsdirs = [-1, 0, 1];
for (let r = 0; r < size; r++) {
for (let c = 0; c < size; c++) {
if (grid[r][c] === '*') continue;
let count = 0;
for (let dr of directionsdirs) {
for (let dc of directionsdirs) {
if (dr === 0 && dc === 0) continue;
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < size && nc >= 0 && nc < size && grid[nr][nc] === '*') {
count++;
}
}
}
if (count > 0) result[r][c] = count.toString();
}
}
return result;
}
function renderGrid(grid) {
return grid.map(row => row.join(' ')).join('\n');
}
// Exampleexample
const message = "TREASURE";
const binary = textToBinary(message);
const mines = binaryToGrid(binary, 9);
const hintGrid = computeHints(mines);
console.log("Minesweeper encoding of:", message, "\n");
console.log(renderGrid(hintGrid));
When I run the script withLive demo and console output are now synchronized: both use the message "TREASURE"same bit padding and encoding logic, I get:
Minesweeper encoding of: TREASURE
* . . 1 1 1 . . .
. . . 1 * 2 1 . .
. * . 1 2 * 2 1 .
. . . . 1 2 * 2 1
. . . . . 1 2 * 1
. . . . . . 1 2 *
. . . . . . . 1 2
To decode:
- Read each cell left to right, top to bottom.
*=1,.=0. Ignore the numbers.- Recombine the bits into 8-bit characters.
The result? "TREASURE"ensuring that examples match exactly. Thanks to André for catching that!
Here’s a board. Can you figure out what itthis board says? (Encoded with the same logic as above — full 9×9 grid used for an 8-character message.)
* . . 1 1 1 . . .
. . . 1 * 2 1 . .
. * . 1 2 * 2 1 .
. . . . 1 2 * 2 1
. . . . . 1 2 * 1
. . . . . . 1 2 *
. . . . . . . 1 2
. . . . . . . . 1
. . . . . . . . .
Ignore the numbers. Just read * as 1 and . as 0, left to right, and see what secret lies beneath.
Huge thanks to André for spotting the mismatched example and helping clarify the role of the numbers — great feedback!