0

I'm working on a simple minesweeper game in python, and am trying to create a function that inserts mines into an empty board.

Note that the board is in the form of a list of lists, as so:

[[col, col, col...],[col,col,col...],[...],[...]...]

my function looks like this:

def insert_mines(NUM_MINES):
for mine in range(NUM_MINES):
    rand_row = randint(0, NUM_ROWS - 1)
    rand_col = randint(0, NUM_COLS - 1)
    if BOARD[rand_row][rand_col] == 'O':
        BOARD[rand_row][rand_col] = 'X'
        NUM_MINES = NUM_MINES - 1
    else:
        BOARD[rand_row][rand_col] = 'X'

print NUM_MINES

when I run it with num_mines = 96, it never prints zero, which is what it should print if all the mines have been inserted.

What could be the cause of this?

note that 'X' represents a mine and 'O' is just a board space with no mine.

2
  • By the way, the most uniform way to distribute mines is to put the required number of mines at the front of your grid, then shuffle the whole lot. Commented Oct 17, 2014 at 4:02
  • 1
    It's not guaranteed that after 96 iterations all empty space will be selected and replaced with mine, since sampling is done uniformly over the grid; i.e. the sampled indices might be repeated. Commented Oct 17, 2014 at 4:06

1 Answer 1

1

The only way to have zero printed is if

BOARD[rand_row][rand_col] == 'O'

for every iteration. Depending on the NUM_ROWS and NUM_COLS this may be surprisingly unlikely due to the "birthday paradox"

An easier way to make your board as suggested by Chris

cells = ['O'] * NUM_ROWS * NUM_COLS
cells[:NUM_MINES] = ['X'] * NUM_MINES
random.shuffle(cells)
BOARD = [cells[i::NUM_ROWS] for i in range(NUM_ROWS)]
Sign up to request clarification or add additional context in comments.

1 Comment

a much more elegant answer than mine. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.