Skip to content

Instantly share code, notes, and snippets.

@kolumb
Last active June 25, 2022 21:59
Show Gist options
  • Save kolumb/0c69d878193d191f48a68e1a14e7c70e to your computer and use it in GitHub Desktop.
Save kolumb/0c69d878193d191f48a68e1a14e7c70e to your computer and use it in GitHub Desktop.
// Minesweeper generator for Discord messages. Idea and emotes were peeped from SKrshe and kjagodka.
// How to use:
// Paste this code into browser's console and press Enter (it will put message with game into clipboard).
// Paste and post message in Discord.
// You can change width, height and number of mines.
// But Discord has limit of number of emotes: 199 - (number of spoilers). So 10 by 10 field is impossible.
const width = 11
const height = 9
let numberOfMines = 17
if (width * height > 99) throw new Error("Field is too big! Please, make width or height smaller.")
if (width * height < numberOfMines) throw new Error("Too many mines! Max is " + width * height)
const textures = "blue_square one two three four five six seven eight boom".split(" ")
const map = new Array(height).fill(0)
.map(_ => new Array(width).fill(false))
while (numberOfMines > 0) {
console.log("attempts to place a mine were made")
const x = Math.floor(Math.random() * width)
const y = Math.floor(Math.random() * height)
if (!map[y][x]) {
map[y][x] = true
numberOfMines--
}
}
const mapCounts = new Array(height).fill(0)
.map(_ => new Array(width).fill(0))
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
if (map[y][x]) mapCounts[y][x] = 9
else mapCounts[y][x] = countMines(x, y)
}
}
function countMines(x, y) {
let result = 0
for (let j = -1; j < 2; j++) {
for (let i = -1; i < 2; i++) {
if (i === 0 && j === 0) continue
result += map[y + j]?.[x + i] ? 1 : 0
}
}
return result
}
const discordMessage = mapCounts.map(row =>
row.map(cell => `||:${textures[cell]}:||`).join("")
).join("\n")
copy(discordMessage)
// copy(mapCounts.map(row => row.map(cell => `:${textures[cell]}:`).join("") ).join("\n")) // Solution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment