0

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()
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • The problem is in `create_field` - please see the linked duplicate. For future reference: if you prefer to ask in Russian, there is https://ru.stackoverflow.com. When posting on the main site, please do not include any "original" Russian text. This is *not a discussion forum*, so we don't care if you have to translate; we care about the question itself. If there are grammar or spelling problems, normally we just edit these without comment. – Karl Knechtel Feb 01 '22 at 18:00
  • @KarlKnechtel where is the linked duplicate? – kpie Feb 01 '22 at 18:02
  • 1
    In the light blue box above the question. You may need to refresh the page. – Karl Knechtel Feb 01 '22 at 18:03

0 Answers0