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

rootulp's solution

to Queen Attack 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.

Given the position of two queens on a chess board, indicate whether or not they are positioned so that they can attack each other.

In the game of chess, a queen can attack pieces which are on the same row, column, or diagonal.

A chessboard can be represented by an 8 by 8 array.

So if you're told the white queen is at (2, 3) and the black queen at (5, 6), then you'd know you've got a set-up like so:

_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ W _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ B _
_ _ _ _ _ _ _ _
_ _ _ _ _ _ _ _

You'd also be able to answer whether the queens can attack each other. In this case, that answer would be yes, they can, because both pieces share a diagonal.

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 queen_attack_test.py
  • Python 3.4+: pytest queen_attack_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 queen_attack_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/queen-attack 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.

Source

J Dalbey's Programming Practice problems http://users.csc.calpoly.edu/~jdalbey/103/Projects/ProgrammingPractice.html

Submitting Incomplete Solutions

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

queen_attack_test.py

import unittest

from queen_attack import Queen


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

class QueenAttackTest(unittest.TestCase):

    # Test creation of Queens with valid and invalid positions
    def test_queen_valid_position(self):
        try:
            Queen(2, 2)
        except ValueError:
            self.fail("Unexpected Exception")

    def test_queen_negative_row(self):
        with self.assertRaisesWithMessage(ValueError):
            Queen(-2, 2)

    def test_queen_invalid_row(self):
        with self.assertRaisesWithMessage(ValueError):
            Queen(8, 4)

    def test_queen_negative_column(self):
        with self.assertRaisesWithMessage(ValueError):
            Queen(2, -2)

    def test_queen_invalid_column(self):
        with self.assertRaisesWithMessage(ValueError):
            Queen(4, 8)

    # Test the ability of one queen to attack another
    def test_attack_false(self):
        self.assertIs(Queen(2, 4).can_attack(Queen(6, 6)), False)

    def test_attack_same_row(self):
        self.assertIs(Queen(2, 4).can_attack(Queen(2, 6)), True)

    def test_attack_same_column(self):
        self.assertIs(Queen(4, 5).can_attack(Queen(2, 5)), True)

    def test_attack_diagonal1(self):
        self.assertIs(Queen(2, 2).can_attack(Queen(0, 4)), True)

    def test_attack_diagonal2(self):
        self.assertIs(Queen(2, 2).can_attack(Queen(3, 1)), True)

    def test_attack_diagonal3(self):
        self.assertIs(Queen(2, 2).can_attack(Queen(1, 1)), True)

    def test_attack_diagonal4(self):
        self.assertIs(Queen(2, 2).can_attack(Queen(5, 5)), True)

    # Track-specific tests
    def test_queens_same_position_can_attack(self):
        with self.assertRaisesWithMessage(ValueError):
            Queen(2, 2).can_attack(Queen(2, 2))

    # 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 Board:

    EMPTY_BOARD = ["_" * 8 for _ in range(8)]

    def __init__(self, white_coords, black_coords):
        self.white_coords = white_coords
        self.black_coords = black_coords
        if not self.valid_coords():
            raise ValueError
        self.board = self.generate_board()

    def generate_board(self):
        board = map(lambda row: list(row), self.EMPTY_BOARD)
        board = self.place_piece(board, "W", self.white_coords)
        board = self.place_piece(board, "B", self.black_coords)
        return map(lambda row: "".join(row), board)

    def can_attack(self):
        return self.same_row() or self.same_col() or self.same_diag()

    def same_row(self):
        return self.white_coords[0] == self.black_coords[0]

    def same_col(self):
        return self.white_coords[1] == self.black_coords[1]

    def same_diag(self):
        return (abs(self.white_coords[0] - self.black_coords[0]) ==
                abs(self.white_coords[1] - self.black_coords[1]))

    def valid_coords(self):
        return (self.different_coords() and
                self.valid_coord(self.white_coords) and
                self.valid_coord(self.black_coords))

    def different_coords(self):
        return self.white_coords != self.black_coords

    @staticmethod
    def valid_coord(coord):
        return (0 <= coord[0] <= 7 and 0 <= coord[1] <= 7)

    @staticmethod
    def place_piece(board, piece, coords):
        board[coords[0]][coords[1]] = piece
        return board


def board(white_coords, black_coords):
    return Board(white_coords, black_coords).board


def can_attack(white_coords, black_coords):
    return Board(white_coords, black_coords).can_attack()

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?