0

I'm running into an issue when initializing a minesweeper board in Python 2.7. Here is my code so far:

class Minesweeper():

def __init__(self, size, num_bombs):

    # Initialize board of zeros
    self.board = [[0]*size]*size
    self.game_over = False
    self.size = size

    self.add_bombs(num_bombs)


def add_bombs(self, num_bombs): 
    # Add bombs
    for i in range(num_bombs):
        row = randint(0, self.size-1)
        column = randint(0, self.size-1)
        self.board[row][column] = 'B'

    print self.board

For some reason, my add_bombs code is manipulating each sub-array of my board identically, and I have no idea why.

ie. x = Minesweeper(5,2) is resulting in:

[[0, 0, 0, 'B', 'B'], [0, 0, 0, 'B', 'B'], [0, 0, 0, 'B', 'B'], [0, 0, 0, 'B', 'B'], [0, 0, 0, 'B', 'B']]

Instead of adding 2 total bombs. Does anyone see what I am doing wrong?

1 Answers1

0

Initialize the list of empty zeros as this instead:

[[0] * size for _ in range(size)]

This creates copies of each sublist instead of creating references to the same list.

iz_
  • 15,923
  • 3
  • 25
  • 40