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.
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*"