Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Please note that in as much as your final results are correct, there are not within a 2Dlist. You are returning separate independent lists, please note that these lists you returned should be within a list. In other words, your final output should be a 2Dlist. Kindly sort out this issue and resubmit.

What I have tried:

# Compulsory Task 1
# This program takes a grid of # and -, where each # represents a mine and each dash (-)represents a mine-free spot.
# Returning a grid, where each dash is replaced by a digit, indicating the number of mines immediately adjacent to the spot.

# This functions has data manipulation on how will the grid be displayed
def minesweeper(grid):
# Firstly we initialise rows and columns
    row_num = len(grid)
    column_num = len(grid[0])
#========== New grid is created ========
# "-" are firstly replaced by 0 on this new grid
# "#" remain on the grid and is not replaced by any other value
    new_grid = [[0] * column_num for _ in range(row_num)]
    hash_count = 0
# Outer loop for rows
# The enumerate method takes two arguments, the iterable and the starting
    for count_row, row in enumerate(grid):
# Inner loop for columns
        for count_column, col in enumerate(row):
            if col == "#":
                new_grid[count_row][count_column] = "#"
#======== Further manipilation on the new grid
# 0's remains on the grid, or either replaced by 1, 2, 3 or 4.
# However # remains on the grid 
            else:
# Depending on the row count,column count and length of grid
# 0's are replaced by a new value
                if count_row >= 0 and count_row < len(grid)-1:
                    if grid[count_row+1][count_column] == "#":
                        hash_count += 1

                if count_row > 0 and count_row <= len(grid)-1:
                    if grid[count_row-1][count_column] == "#":
                        hash_count += 1  
                    
                if count_column >= 0 and count_column < len(row)-1:
                        if row[count_column+1] == "#":
                            hash_count += 1
                            
                if count_column > 0 and count_column <= len(row)-1:
                        if row[count_column-1] == "#":
                            hash_count += 1
# Depending on the row count,column count, length of grid and row
# 0's are replaced by a new value                
                if count_row >= 0 and count_row < len(grid)-1 and count_column >= 0 and count_column < len(row)-1:
                    if grid[count_column+1][count_column+1] == "#":
                        hash_count += 1
                if count_row >= 0 and count_row < len(grid)-1 and count_column > 0 and count_column <= len(row)-1:
                    if grid[count_row+1][count_column-1] == "#":
                        hash_count += 1
                        
                if count_row > 0 and count_row <= len(grid)-1 and count_column >= 0 and count_column < len(row)-1:
                    if grid[count_row-1][count_column+1] == "#":
                        hash_count += 1
                if count_row > 0 and count_row <= len(grid)-1 and count_column > 0 and count_column <= len(row)-1:
                    if grid[count_row-1][count_column-1] == "#":
                        hash_count += 1
                                        
                new_grid[count_row][count_column] = str(hash_count) 
                hash_count = 0
          
    return new_grid

grid = [["-", "-", "-", "#", "#"],
["-", "#", "-", "-", "-"],
["-", "-", "#", "-", "-"],
["-", "#", "#", "-", "-"],
["-", "-", "-", "-", "-"]]

# Function is called and new grid is displayed   
for row in minesweeper(grid):
    print(row)
Posted
Updated 24-Jun-23 5:47am
Comments
Richard Deeming 25-Jul-22 10:46am    
Nobody here is going to do your homework for you. If you don't understand the teacher's instructions, then go and talk to them and ask for clarification. That's what they're paid for!
Thandeka Zulu 25-Jul-22 11:30am    
Thanks for your response

I'm not a big fan of list comprehensions in general. I prefer the clearer loop format. You can compress the code significantly by using ranges. To check all the cells around a given cell you just need to loop over range(row-1, row+2) and range(col-1, col_2) while adding tests to ensure you stay within the defined grid as in
for r in range(max(row-1,0), min(row+2,numrows))
The rest of this should be fairly obvious.
Python
<pre>
def printGrid(grid):
    """Prints out the minsweeper grid"""
    for row in grid:
        out = ''
        for col in row:
            out += f'{col:^3}'
        print(out)
  

def numAdjacent(grid: list, row: int, col: int) -> int:
    """Returns the number of mines '#' adjacent to the given cell"""

    numrows,numcols = len(grid), len(grid[0])
    nummines = 0

    #Use range to generate a range of rows and columns from
    #one less than the given row and column to one more.

    for r in range(max(row-1,0), min(row+2,numrows)):
        for c in range(max(col-1,0), min(col+2,numcols)):
            nummines += grid[r][c] == '#'
                
    return nummines               

    
def mineSweeper(grid: list) -> list:
    """
    Takes a grid (a list of lists of equal length) where each element
    is either '-' (no mine) or '#' (mine) and returns a grid where
    each '-' in the original grid is replaced by a number indicating
    the number of mines in adjacent cells.
    """

    #determine rows and column sizes
    
    numrows = len(grid)
    numcols = len(grid[0])

    #make new grid with '-' replaced by the number of adjacent mines
    
    newgrid = grid

    for row in range(0, numrows):
        for col in range(0, numcols):
            if newgrid[row][col] == '-':
                newgrid[row][col] = numAdjacent(grid,row,col)
            
    return newgrid

grid = [
["-", "-", "-", "#", "#"],
["-", "#", "-", "-", "-"],
["-", "-", "#", "-", "-"],
["-", "#", "#", "-", "-"],
["-", "-", "-", "-", "-"],
]

printGrid(grid)
print('')
printGrid(mineSweeper(grid))
 
Share this answer
 
Replace the last two lines with:
Python
import pprint  
pp = pprint.PrettyPrinter(indent=2)
answer = minesweeper(grid)
pp.pprint(answer)


See pprint — Data pretty printer — Python 3.10.5 documentation[^].
 
Share this answer
 
v3
Comments
Thandeka Zulu 25-Jul-22 15:41pm    
@Richard MacCutchan. Thank you so much. May God bless you. I works perfectly
Thandeka Zulu 25-Jul-22 15:41pm    
@Richard MacCutchan. Thank you so much. May God bless you. I works perfectly

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900