Search code examples
pythonlistminesweeper

Randomly placing items in a list of lists in Python


I'm a beginner at using Python and I've been trying to code a Minesweeper game. Basically, I'm a bit lost on how to set up my class so that it creates a 5x5 grid of cells using a list of lists, then randomly places 3 mines on this grid, and counts the number of mines in each cell's neighborhood.

I figured I would use an __init__ method that would call on two other methods: one for placing the mines, and another for counting each cell's neighborhood.

I'm a bit lost on how to set those up though so any suggestions?


Solution

  • Here's a little code to get you started:

    >>> import random
    >>> cells = [['empty'] * 5 for i in range(5)]
    >>> for i in range(3):
            x = random.randrange(5)
            y = random.randrange(5)
            cells[x][y] = 'mine'
    
    
    >>> import pprint
    >>> pprint.pprint(cells)
    [['empty', 'empty', 'empty', 'empty', 'empty'],
     ['mine', 'empty', 'mine', 'empty', 'empty'],
     ['empty', 'empty', 'empty', 'empty', 'mine'],
     ['empty', 'empty', 'empty', 'empty', 'empty'],
     ['empty', 'empty', 'empty', 'empty', 'empty']]