Skip to content

Instantly share code, notes, and snippets.

@CodingKoopa
Forked from vgmoose/discordminesweeper.py
Last active June 12, 2022 21:07
Show Gist options
  • Select an option

  • Save CodingKoopa/ae1e6e1c329e5aff318dae9bb4925d13 to your computer and use it in GitHub Desktop.

Select an option

Save CodingKoopa/ae1e6e1c329e5aff318dae9bb4925d13 to your computer and use it in GitHub Desktop.
Discord minesweeper grid generator with emojis and spoiler tags
#!/bin/python3
import sys
import random
emojis = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "X"]
mine = -1
def gen_grid(num_row, num_col, mines):
grid = [[0 for col in range(num_col)] for row in range(num_row)]
half_x = num_col // 2
half_y = num_row // 2
# generate mines randomly
for _ in range(mines):
y = random.randint(0, num_row-1)
x = random.randint(0, num_col-1)
grid[y][x] = mine
# the position of the zero we're going to reveal
zero_pos = (-1, -1)
# go through the grid and count up neighboring mines
for y, row in enumerate(grid):
for x, cell in enumerate(row):
if cell != mine:
# for ±1 cell in each direction
for j in range(-1, 2):
for i in range(-1, 2):
ny = y+j
nx = x+i
# out of bounds check
if ny >= 0 and nx >= 0 and ny < num_row and nx < num_col:
grid[y][x] += grid[ny][nx] == -1
if grid[y][x] == 0:
# save the zero position if it's closer than our previous one to the middle
zy, zx = zero_pos
if abs(y - half_y) + abs(x - half_x) < abs(zy - half_y) + abs(zx - half_x):
zero_pos = (y, x)
# print out grid
for y, row in enumerate(grid):
for x, cell in enumerate(row):
emoji = f"`{emojis[cell]}`"
if zero_pos != (y, x):
# spoiler it, not our starting 0
emoji = f"||{emoji}||"
sys.stdout.write(f"{emoji}")
print("")
# 4x5 grid with 3-ish mines
gen_grid(4, 5, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment