Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Minesweeper in the Python Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Add the numbers to a minesweeper board.

Minesweeper is a popular game where the user has to find the mines using numeric hints that indicate how many mines are directly adjacent (horizontally, vertically, diagonally) to a square.

In this exercise you have to create some code that counts the number of mines adjacent to a square and transforms boards like this (where * indicates a mine):

+-----+
| * * |
|  *  |
|  *  |
|     |
+-----+

into this:

+-----+
|1*3*1|
|13*31|
| 2*2 |
| 111 |
+-----+

Exception messages

Sometimes it is necessary to raise an exception. When you do this, you should include a meaningful error message to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. Not every exercise will require you to raise an exception, but for those that do, the tests will only pass if you include a message.

To raise a message with an exception, just write it as an argument to the exception type. For example, instead of raise Exception, you should write:

raise Exception("Meaningful message indicating the source of the error")

Running the tests

To run the tests, run the appropriate command below (why they are different):

  • Python 2.7: py.test minesweeper_test.py
  • Python 3.4+: pytest minesweeper_test.py

Alternatively, you can tell Python to run the pytest module (allowing the same command to be used regardless of Python version): python -m pytest minesweeper_test.py

Common pytest options

  • -v : enable verbose output
  • -x : stop running tests on first failure
  • --ff : run failures from previous test before running other test cases

For other options, see python -m pytest -h

Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the $EXERCISM_WORKSPACE/python/minesweeper directory.

You can find your Exercism workspace by running exercism debug and looking for the line that starts with Workspace.

For more detailed information about running tests, code style and linting, please see the help page.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

minesweeper_test.py

""" Tests for the minesweeper exercise

Implementation note:
The board function must validate its input and raise a
ValueError with a meaningfull error message if the
input turns out to be malformed.
"""

import unittest

from minesweeper import board


# Tests adapted from `problem-specifications//canonical-data.json` @ v1.1.0

class MinesweeperTest(unittest.TestCase):

    def test_no_rows(self):
        self.assertEqual(board([]), [])

    def test_no_columns(self):
        self.assertEqual(board([""]), [""])

    def test_no_mines(self):
        inp = ["   ",
               "   ",
               "   "]
        out = ["   ",
               "   ",
               "   "]
        self.assertEqual(board(inp), out)

    def test_board_with_only_mines(self):
        inp = ["***",
               "***",
               "***"]
        out = ["***",
               "***",
               "***"]
        self.assertEqual(board(inp), out)

    def test_mine_surrounded_by_spaces(self):
        inp = ["   ",
               " * ",
               "   "]
        out = ["111",
               "1*1",
               "111"]
        self.assertEqual(board(inp), out)

    def test_space_surrounded_by_mines(self):
        inp = ["***",
               "* *",
               "***"]
        out = ["***",
               "*8*",
               "***"]
        self.assertEqual(board(inp), out)

    def test_horizontal_line(self):
        inp = [" * * "]
        out = ["1*2*1"]
        self.assertEqual(board(inp), out)

    def test_horizontal_line_mines_at_edges(self):
        inp = ["*   *"]
        out = ["*1 1*"]
        self.assertEqual(board(inp), out)

    def test_vertical_line(self):
        inp = [" ",
               "*",
               " ",
               "*",
               " "]
        out = ["1",
               "*",
               "2",
               "*",
               "1"]
        self.assertEqual(board(inp), out)

    def test_vertical_line_mines_at_edges(self):
        inp = ["*",
               " ",
               " ",
               " ",
               "*"]
        out = ["*",
               "1",
               " ",
               "1",
               "*"]
        self.assertEqual(board(inp), out)

    def test_cross(self):
        inp = ["  *  ",
               "  *  ",
               "*****",
               "  *  ",
               "  *  "]
        out = [" 2*2 ",
               "25*52",
               "*****",
               "25*52",
               " 2*2 "]
        self.assertEqual(board(inp), out)

    def test_large_board(self):
        inp = [" *  * ",
               "  *   ",
               "    * ",
               "   * *",
               " *  * ",
               "      "]
        out = ["1*22*1",
               "12*322",
               " 123*2",
               "112*4*",
               "1*22*2",
               "111111"]
        self.assertEqual(board(inp), out)

    # Additional test for this track
    def test_board9(self):
        inp = ["     ",
               "   * ",
               "     ",
               "     ",
               " *   "]
        out = ["  111",
               "  1*1",
               "  111",
               "111  ",
               "1*1  "]
        self.assertEqual(board(inp), out)

    def test_different_len(self):
        inp = [" ",
               "*  ",
               "  "]
        with self.assertRaisesWithMessage(ValueError):
            board(inp)

    def test_invalid_char(self):
        inp = ["X  * "]
        with self.assertRaisesWithMessage(ValueError):
            board(inp)

    # Utility functions
    def setUp(self):
        try:
            self.assertRaisesRegex
        except AttributeError:
            self.assertRaisesRegex = self.assertRaisesRegexp

    def assertRaisesWithMessage(self, exception):
        return self.assertRaisesRegex(exception, r".+")


if __name__ == '__main__':
    unittest.main()
class Minesweeper:

    MINE = "*"
    SPACE = " "
    CORNER = "+"
    VERTICAL_EDGE = "|"
    HORIZONTAL_EDGE = "-"

    @classmethod
    def board(cls, inp):
        if not cls.valid(inp):
            raise ValueError
        return cls.solve(inp)

    # Split rows (String -> List) and operate on board in place
    @classmethod
    def solve(cls, inp):
        inp = map(lambda row: list(row), inp)
        return map(lambda row: "".join(row), cls.generate_board(inp))

    @classmethod
    def generate_board(cls, inp):
        return [[cls.convert_square(inp, y, x)
                for x, square in enumerate(row)]
                for y, row in enumerate(inp)]

    # Only convert squares that are spaces
    @classmethod
    def convert_square(cls, inp, y, x):
        if not cls.is_space(inp[y][x]):
            return inp[y][x]
        return str(cls.output_of_neighbor_mines(inp, y, x))

    @classmethod
    def output_of_neighbor_mines(cls, inp, y, x):
        num_mines = cls.num_of_neighbor_mines(inp, y, x)
        return " " if num_mines == 0 else num_mines

    @classmethod
    def num_of_neighbor_mines(cls, inp, y, x):
        return len(filter(lambda neighbor: cls.is_neighbor_a_mine(inp,
                          neighbor), cls.all_neighbor_coords(inp, y, x)))

    # Checks if coords are within bounds then checks for is_mine
    @classmethod
    def is_neighbor_a_mine(cls, inp, neighbor):
        y, x = neighbor[0], neighbor[1]
        return (0 < y < len(inp) and 0 < x < len(inp[0]) and
                cls.is_mine(inp[y][x]))

    # Generates list of tuples for all neighboring coords
    # (excluding current coord)
    @classmethod
    def all_neighbor_coords(cls, inp, y, x):
        return [(y + dy, x + dx) for dy in range(-1, 2) for dx in range(-1, 2)
                if dy != 0 or dx != 0]

    @classmethod
    def valid(cls, inp):
        return (cls.valid_len(inp) and
                cls.valid_border(inp) and
                cls.valid_squares(inp))

    # Tests if all rows are the same size
    @classmethod
    def valid_len(cls, inp):
        return all(len(row) == len(inp[0]) for row in inp)

    @classmethod
    def valid_border(cls, inp):
        return (cls.valid_middle_borders(inp) and
                cls.valid_first_and_last_borders(inp))

    @classmethod
    def valid_middle_borders(cls, inp):
        return all(cls.valid_middle_border(row) for row in inp[1:-1])

    @classmethod
    def valid_middle_border(cls, row):
        return (cls.is_vertical_edge(row[0]) and
                cls.is_vertical_edge(row[-1]))

    @classmethod
    def valid_first_and_last_borders(cls, inp):
        return (cls.valid_first_or_last_border(inp[0]) and
                cls.valid_first_or_last_border(inp[-1]))

    @classmethod
    def valid_first_or_last_border(cls, row):
        return (cls.is_corner(row[0]) and cls.is_corner(row[-1]) and
                all(cls.is_horizontal_edge(square) for square in row[1:-1]))

    @classmethod
    def valid_squares(cls, inp):
        return all(cls.valid_square(square) for row in inp for square in row)

    @classmethod
    def valid_square(cls, square):
        return (cls.is_mine(square) or
                cls.is_space(square) or
                cls.is_corner(square) or
                cls.is_vertical_edge(square) or
                cls.is_horizontal_edge(square))

    @classmethod
    def valid_non_border(cls, square):
        return cls.is_mine(square) or cls.is_space(square)

    @classmethod
    def is_mine(cls, square):
        return square == cls.MINE

    @classmethod
    def is_space(cls, square):
        return square == cls.SPACE

    @classmethod
    def is_corner(cls, square):
        return square == cls.CORNER

    @classmethod
    def is_vertical_edge(cls, square):
        return square == cls.VERTICAL_EDGE

    @classmethod
    def is_horizontal_edge(cls, square):
        return square == cls.HORIZONTAL_EDGE


def board(inp):
    return Minesweeper.board(inp)

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?