Home > Software engineering >  Why does my Minesweeper clone count the neighboring bombs inaccurately?
Why does my Minesweeper clone count the neighboring bombs inaccurately?

Time:09-06

I am writing a Minesweeper clone in Python 3 that runs in the terminal window. The minefield is represented by a 10x10 array:

minefield = [[0 for i in range(LENGTH)] for j in range(HEIGHT)]

20 mines are placed into minefield and an example is shown below. Bombs are denoted by -1.

 0-1-1-1 0 0 0-1-1 0
 0 0 0-1 0 0 0 0 0 0
 0-1 0-1-1-1 0 0 0-1
 0 0 0 0 0-1 0 0 0 0
 0 0 0 0-1 0 0-1 0-1
 0 0 0 0 0 0 0-1 0 0
 0 0-1 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0
-1 0-1 0 0 0 0-1 0-1

Both the functions place_numbers() and count_neighbours(a, b) work on the global 10x10 array minefield. count_neighbours(a, b) takes an elementminefield[a][b] and counts the neighbouring bombs in the 8 squares around it. This function is returning incorrect values.

def place_numbers():
    global minefield
    for i in range(0, LENGTH):
        for j in range(0, HEIGHT):
            if minefield[i][j] != -1:
                neighbours = count_neighbours(i, j)
                minefield[i][j] = neighbours
    print("Bombs placed!!")
    pretty_print(minefield)


@staticmethod
def count_neighbours(a, b):
    neighbours = 0
    for i in (a-1, a, a 1):
        for j in (b-1, b, b 1):
            if i != a and j != b: # we do not need to count the square itself whose neighbours we're counting
                if i in range(0, 10) and j in range(0, 10): # to check if the square is within bounds
                    if minefield[i][j] == -1: #neighbour at i, j located
                        neighbours  = 1
    return neighbours

The output of the code after counting the neighbouring bombs in the above example is given below.

 0-1-1-1 1 0 0-1-1 0
 2 1 4-1 3 1 2 1 2 1
 0-1 1-1-1-1 1 0 0-1
 1 0 2 2 2-1 2 0 3 0
 0 0 0 0-1 0 2-1 1-1
 0 1 0 2 0 1 1-1 2 0
 0 0-1 0 0 0 1 0 1 0
 0 1 0 1 0 0 0 0 0 0
 0 2 0 1 0 0 1 0 2 0
-1 0-1 0 0 0 0-1 0-1

count_neighbours(a, b) iterates through the 8 squares around [a, b] except itself. What could be causing this issue?

CodePudding user response:

You want to change this line:

if i != a and j != b:

to

if i != a or j != b:

Consider a = 3, b = 3. Your code will not run if i = 3, j = 2. Because the and condition will be false. You want it to run when one of the pairs are not equal.

  • Related