Hello I'm fairly new to python and I'm currently trying to construct a minesweeper game. I've made 2 lists, 1 is shown to the player (field) and 1 contains the mines (minefield). I ask the player to select coordinates and the program then checks whether there are mines around it or not and flood fills the map around the mines using this code:
def floodfill(field, minefield, x, y)
list1 = [(x, y)]
while True:
a, b = list1.pop()
field[b][a] = 'W'
list2 = [(a, b - 1), (a, b + 1), (a - 1, b), (a + 1, b)]
for element in list2:
x2 = element[0]
y2 = element[1]
if y2 >= len(field) or x2 >= len(field[0]) or y2 < 0 or x2 < 0:
continue
if minefield[y2][x2] == 'O':
list1.append(element)
if not list1:
break
return field
So basically I'm trying to check if there are mines around the chosen coordinates by looking at the 'minefield' list and then modifying the 'field' list according the 'minefield' list. The problem I have that the program jams if there are any non-mine blocks around the given coordinates.
for example when I run it with these nothing happens.
minefield = [['O', 'O'], ['x', 'x']] # field is the same without xs
x = 0
y = 0
But with these:
minefield = [['O', 'x'], ['x', 'x']] # field is the same without xs
x = 0
y = 0
It returns this:
field = [['W', 'O'], ['O', 'O']] # Os are covered mines
Problem seems to be in
because You don't modify minefield array in the loop, it will always have an 'O' and in each for loop a coordinate will be appended to list1. You could check both minefield and field for values at (y2, x2) and if both are 'O' then append it to the list1:
After running code with above modification and this data:
it returns:
Also its very dangerous to do just
because, as observed, program can enter infinite loop. There should be some kind of iteration limiter, of course big enough that algorithm can do correct calculations and small enough that it will quite after some time if there is a mistake in code. So in this case limitation should be set to a value that is at least as big as the size of whole minefield (case if there is no mines in whole minefiled). Plus there could be a proper warning printed if iteration limits was exceeded - debug and informational purpose.