this code creates a custom-sized minesweeper game field and places a custom number of bombs (I haven't added a check yet if there are more bombs than the field size). But I ran into a problem: for example, when entering:
Height: 10
Width: 10
How many bombs: 98
During the placement of bombs, the code does not place them according to coordinates, more precisely, it observes the second coordinate, and as a result, bombs are placed on all lines of the field according to y coordinates. How to fix it?
import random
def create_field(height, width):
return [[[0] * width] * height]
def place_bombs(field, number):
x_y_bombs = []
width = len(field[0])
height = len(field)
if number <= height * width // 2:
while len(x_y_bombs) < number:
x_y_bombs.append([random.randint(0, height - 1), random.randint(0, width - 1)])
temp = x_y_bombs.copy()
del temp[-1]
for item in temp:
if x_y_bombs[-1] == item:
del x_y_bombs[-1]
print(f'x_y_bombs: {x_y_bombs}')
for coord in x_y_bombs:
field[coord[0]][coord[-1]] = 'x'
else:
number = height * width - number
field = [[['x'] * width] * height][0]
while len(x_y_bombs) < number:
x_y_bombs.append([random.randint(0, height - 1), random.randint(0, width - 1)])
temp = x_y_bombs.copy()
del temp[-1]
for item in temp:
if x_y_bombs[-1] == item:
del x_y_bombs[-1]
print(f'x_y_bombs: {x_y_bombs}')
for coord in x_y_bombs:
field[coord[0]][coord[-1]] = 0
return field
def main():
field = create_field(int(input('Height: ')), int(input('Width: ')))[0]
field = place_bombs(field, int(input('How many bombs: ')))
print(field)
if __name__ == '__main__':
main()