How do you represent the MineSweeper grid in Python?

What data structure would you use in Python to represent the internal state of the MineSweeper grid?

Each x, y position will contain a numerical value that represents its current state of the cell (uncharted, mine, flag ,?).

Should I use nested lists? This is similar to the closest to a 2D array, and this is what I would probably use in any other language (2d array).

Am I not so experienced with Python that anyone give me a suggestion?

+3
source share
7 answers

Use the nested list. Easy to set up:

field = [([None] * height) for x in range(width)]

field[x][y] = "*"

The brightest will probably be the new class:

class MineField(object):
    class _SingleField(object):
        mine = False
        flagged = False
        covered = True

    width = None
    height = None

    def __init__(self, width, height):
        super(MineField, self).__init__()
        self.width = width
        self.height = height
        self._field = [[self._SingleField() for y in range(height)]
                                            for x in range(width)]

        self.init_field(10)

    def init_field(self, minecount):
        pass

    def __getitem__(self, index):
        x, y = index
        return self._field[x][y]

Used as follows:

> m = MineField(10,10)
> m[4,9].mine
False
+8

2- , :

class FieldState(object):
  def __init__(self):
    self.unexplored = True
    self.mine = Random()
    self.flag = Random()
    ...

for x in range(12):
  for y in range(24):
    list[x][y] = FieldState()
+6

, ,

board = {}
board[1, 2] = 9
+3

Board, .

class Board(object):
    def __init__(self, width, height):
        self.__width, self.__height = width, height
        self._board = [[FieldState() for y in xrange(height)]
                       for x in xrange(width)]
    @property
    def width(self):
        return self.__width

    def mark(self, x, y):
        self._board[x][y].mark()

    def __getitem__(self, coord):
        """
        >>> board = Board(3, 4)
        >>> field = board[1,2] # 2nd column, 3rd row
        """
        x, y = coord
        return self._board[x][y]

    ...

FieldState @zlack answer.

+1

, : 1) : (, -1) , 2) , : , , , , , .

, ( ).

+1

int, , , . .

00 nothing, noflag
10 bomb, noflag
01 nothing,flagged
11 bomb, flagged

, int , , .

000 no-neighbor
001 one neighbor
010 two...

.. .

0

'tile' 'cell', .

current = (1,1)
if grid[current].isFlagged():
   do_whatever;

, , , , , , 1024x1024, .

If you are doing more than looking at tiles in a grid, then consider a JF Board object to wrap an array.

Python is an OO language, and often the simplest and clearest thing that works is to use classes and objects wisely.

Note. You can also look at the named_tuple class for situations that seem too simple for the corresponding class.

0
source

Source: https://habr.com/ru/post/1724035/


All Articles