🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of pfertyk

pfertyk'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()
import re


def validate_board(board):
    if len(set(len(row) for row in board)) != 1:
        raise ValueError('Rows in the board have different lengths')

    board_symbols = set(''.join(board))
    allowed_symbols = set('+|- *')
    if not board_symbols.issubset(allowed_symbols):
        raise ValueError('The board uses incorrect symbols')

    board_str = '\n'.join(board)
    if not re.match('\+-+\+\n(\|[ \*]+\|\n)+\+-+\+', board_str):
        raise ValueError('The structure of the board is incorrect')


def board(board):
    validate_board(board)
    board = [list(row) for row in board]
    mine_coordinates = [(x, y) for x in range(len(board)) for y in range(len(board[0])) if board[x][y] == '*']
    adjacencies = [(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1) if x != 0 or y != 0]
    adjacent_coordinates = [(mx + ax, my + ay) for ax, ay in adjacencies for mx, my in mine_coordinates]
    for x, y in adjacent_coordinates:
        field = board[x][y]
        if field == ' ':
            field = 1
        elif field.isdigit():
            field = int(field) + 1
        board[x][y] = str(field)
    return [''.join(row) for row in board]

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?