简体   繁体   中英

Problem in implementing minesweeper reveal in python without functions

I am working on making the game minesweeper for a project, but have encountered a problem with the reveal part of the game (If if enter the coordinates of any cell that has 0 mines surrounding it, then the game is supposed to keep revealing neighboring tiles unless a non-zero cell value is reached). I have also searched the internet for this but cannot find any appropriate solution (I am not allowed to use functions as it is not a part of this year's curriculum). Can somebody pls provide any insight as to how I can implement this in python.

PS For reference you can have a look at this code

def neighbours(r, col):
 
global mine_values
global numbers
global vis

# If the cell already not visited
if [r,col] not in vis:

    # Mark the cell visited
    vis.append([r,col])

    # If the cell is zero-valued
    if numbers[r][col] == 0:

        # Display it to the user
        mine_values[r][col] = numbers[r][col]

        # Recursive calls for the neighbouring cells
        if r > 0:
            neighbours(r-1, col)
        if r < n-1:
            neighbours(r+1, col)
        if col > 0:
            neighbours(r, col-1)
        if col < n-1:
            neighbours(r, col+1)    
        if r > 0 and col > 0:
            neighbours(r-1, col-1)
        if r > 0 and col < n-1:
            neighbours(r-1, col+1)
        if r < n-1 and col > 0:
            neighbours(r+1, col-1)
        if r < n-1 and col < n-1:
            neighbours(r+1, col+1)  
             
    # If the cell is not zero-valued            
    if numbers[r][col] != 0:
            mine_values[r][col] = numbers[r][col]

Link - https://www.askpython.com/python/examples/create-minesweeper-using-python

This should work:

    #before main loop
    shifts = [
        (-1,-1),
        (-1, 1),
        (-1, 0),
        ( 1,-1),
        ( 1, 1),
        ( 1, 0),
        ( 0,-1),
        ( 0, 1),
    ]
    #main loop
    to_reveal = []
    if (x,y) not in vis:
        to_reveal.append((x,y))

    while to_reveal != []:
        cell = to_reveal.pop()
        vis.append(cell)
        if board[cell[1]][cell[0]] == 0:
            for shift in shifts:
                if (cell[0] + shift[0],cell[1] + shift[1]) not in vis and 0 <= (cell[0] + shift[0]) <= 9 and 0 <= (cell[1] + shift[1]) <= 9:
                    to_reveal.append((cell[0] + shift[0],cell[1] + shift[1]))

What this code does, is after the player picks a tile to uncover, that tile is added to a list. Then it if is a 0 add all neighbors to the list, ect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM