1

I have to create a function that creates a game board for minesweeper (I am also very new to coding).

I intend to have the board initially start with every space being covered and mine free, represented by the string "C ".

I then need to assign mines to random spaces in my 2D list, replacing instances of "C " with "C*"

# create board function
def createBoard (rows, cols, mines):

    board = []
    #set the range to the number of rows and columns provided +1
    #for every row, create a row and a column
    for r in range (0,rows+1):
        board.append([])
        for c in range (0,cols+1):
            board[r].append("C ")

    #set # of mines to 0

    num_mines=0

    while num_mines < mines :
        x = random.choice(board)
        y = random.choice(x)
        if y == "C ":
            x[y]= "C*"


            num_mines = num_mines+1

My problem is that I don't know how to actually replace the string.

Remi Guan
  • 21,506
  • 17
  • 64
  • 87

2 Answers2

0

When you pick a random item, you end up with a reference to it. Since you're getting a string, you have a reference to a string. When you want to change it... you can't do so, because strings are immutable. Instead of getting a reference to the string, get a reference to its position in the list. You can then replace that element.

x = random.choice(board)
y = random.randint(0, len(x)-1)
if x[y] == "C ":
    x[y] = "C*"

Instead of using random.choice, use random.randint to pick a random integer between the two arguments (inclusive, so we have to subtract 1 from the length of that sublist). It's used as an index to that sublist so that we can change the corresponding element.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

First notice that your board has one extra column and row. (Just use range(rows) and range(cols))

Then pick random 'coordinates':

    x = random.randrange(rows)
    y = random.randrange(cols)

Then just naturally:

    if board[x][y] == "C ":
        board[x][y] = "C*"
Julien
  • 13,986
  • 5
  • 29
  • 53