Avatar of helenst
0
0
Genius
0
1

helenst's solution

to Minesweeper in the Python Track

Instructions
Test suite
Solution

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()
import re
from itertools import product

# Top or bottom border, e.g. "+------+"
HORIZONTAL_BORDER = re.compile(r'''
    \+      # starts with +
    \-+     # any number of -
    \+      # ends with +
''', re.VERBOSE)

# Tile row, e.g. |   *  |
TILE_ROW = re.compile(r'''
    \|      # starts with |
    (\ |\*)+ # any number of ' ' or '*'
    \|      # ends with |
''', re.VERBOSE)


def surrounding_tiles(row, col):
    """
    Generate coordinates of all tiles surrounding (row, col),
    excluding the tile itself
    """
    return (
        (row+i, col+j)
        for (i, j) in product((1, 0, -1), repeat=2)
        if i or j       # exclude (0, 0) which is itself
    )


def board(inp):
    if not all(len(row) == len(inp[0]) for row in inp):
        raise ValueError("Rows must be of equal length")

    if not all((
        HORIZONTAL_BORDER.match(inp[0]),
        HORIZONTAL_BORDER.match(inp[-1]),
        all(TILE_ROW.match(row) for row in inp[1:-1])
    )):
        raise ValueError("Invalid board format")

    # Create a mutable structure that can be modified as we count mines
    tiles = [list(row) for row in inp]

    # Just iterate over the inner board -
    # the edges are handy for keeping indexes valid :)
    row_range = range(1, len(tiles)-1)
    col_range = range(1, len(tiles[0])-1)

    def increment_tile(row, col):
        value = tiles[row][col]
        if value == ' ':
            tiles[row][col] = '1'
        elif value.isdigit():
            tiles[row][col] = str(int(value)+1)

    # Find mines and increment surrounding tiles
    for row in row_range:
        for col in col_range:
            if tiles[row][col] == '*':
                for (r, c) in surrounding_tiles(row, col):
                    increment_tile(r, c)

    return [''.join(row) for row in tiles]

What can you learn from this solution?

A huge amount can be learnt 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 I could read more about to develop my understanding?

Community comments

See what others have said about this solution
about 2 years ago
helenst says

This version searches for mines and increments the cells around them. Should perform better where there are fewer mines than spaces (as would be expected)