Avatar of ABerardino

ABerardino's solution

to Queen Attack in the TypeScript Track

Published at May 03 2020 · 0 comments
Instructions
Test suite
Solution

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.

Setup

Go through the setup instructions for TypeScript to install the necessary dependencies:

https://exercism.io/tracks/typescript/installation

Requirements

Install assignment dependencies:

$ yarn install

Making the test suite pass

Execute the tests with:

$ yarn test

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing xit to it.

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.ts

import QueenAttack from "./queen-attack"

describe("Queens", () => {
  it("initialized with specific placement", () => {
    const queens = new QueenAttack({ white: [3, 7], black: [6, 1] })
    expect(queens.white).toEqual([3, 7])
    expect(queens.black).toEqual([6, 1])
  })

  xit("cannot occupy the same space", () => {
    const positioning: { black: [number, number]; white: [number, number] } = {
      black: [2, 4],
      white: [2, 4]
    }
    const expectedError = "Queens cannot share the same space"
    expect(() => new QueenAttack(positioning)).toThrow(expectedError)
  })

  xit("toString representation", () => {
    const positioning: { black: [number, number]; white: [number, number] } = {
      white: [2, 4],
      black: [6, 6]
    }
    const queens = new QueenAttack(positioning)
    const board = [
      "_ _ _ _ _ _ _ _",
      "_ _ _ _ _ _ _ _",
      "_ _ _ _ W _ _ _",
      "_ _ _ _ _ _ _ _",
      "_ _ _ _ _ _ _ _",
      "_ _ _ _ _ _ _ _",
      "_ _ _ _ _ _ B _",
      "_ _ _ _ _ _ _ _\n"
    ].join("\n")
    expect(queens.toString()).toEqual(board)
  })

  xit("queens cannot attack", () => {
    const queens = new QueenAttack({ white: [2, 3], black: [4, 7] })
    expect(queens.canAttack()).toEqual(false)
  })

  xit("queens can attack when they are on the same row", () => {
    const queens = new QueenAttack({ white: [2, 4], black: [2, 7] })
    expect(queens.canAttack()).toEqual(true)
  })

  xit("queens can attack when they are on the same column", () => {
    const queens = new QueenAttack({ white: [5, 4], black: [2, 4] })
    expect(queens.canAttack()).toEqual(true)
  })

  xit("queens can attack diagonally", () => {
    const queens = new QueenAttack({ white: [1, 1], black: [6, 6] })
    expect(queens.canAttack()).toEqual(true)
  })

  xit("queens can attack another diagonally", () => {
    const queens = new QueenAttack({ white: [0, 6], black: [1, 7] })
    expect(queens.canAttack()).toEqual(true)
  })

  xit("queens can attack yet another diagonally", () => {
    const queens = new QueenAttack({ white: [4, 1], black: [6, 3] })
    expect(queens.canAttack()).toEqual(true)
  })

  xit("queens can attack on a north-east/south-west diagonal", () => {
    const queens = new QueenAttack({ white: [7, 0], black: [0, 7] })
    expect(queens.canAttack()).toEqual(true)
  })

  xit("queens can attack on another ne/sw diagonal", () => {
    const queens = new QueenAttack({ white: [2, 6], black: [5, 3] })
    expect(queens.canAttack()).toEqual(true)
  })
})
export class QueenAttack {
  private _white: PieceType;
  private _black: PieceType;
  white: [number, number];
  black: [number, number];

  constructor(pos: positions) {

    this._black = new Queen(Team.Black, pos.black);
    this._white = new Queen(Team.White, pos.white);
    this.white = this._white.location;
    this.black = this._black.location;
    if (this.white[0] === this.black[0] && this.white[1] === this.black[1]) {
      throw new Error("Queens cannot share the same space");
    }
  }

  toString(): string {
    const board = [
      "_ _ _ _ _ _ _ _", // 7 : 0
      "_ _ _ _ _ _ _ _", // 6 : 1
      "_ _ _ _ _ _ _ _", // 5 : 2
      "_ _ _ _ _ _ _ _", // 4 : 3
      "_ _ _ _ _ _ _ _", // 3 : 2
      "_ _ _ _ _ _ _ _",
      "_ _ _ _ _ _ _ _",
      "_ _ _ _ _ _ _ _\n"
    ];
    const white_queen_row = 
    this.replaceAt(board[this._white.location[1]], 
    this._white.location[0]*2, 'W');
    
    const black_queen_row = 
    this.replaceAt(board[this._black.location[1]], 
    this._black.location[0]*2, 'B');

    board[7 - this._white.location[1]] = white_queen_row;
    board[7 - this._black.location[1]] = black_queen_row;
    console.log(board.join('\n'));
    return board.join('\n');
  }
   replaceAt(input: string, index: number, replacement:string) {
      return input.substr(0, index) + replacement+ input.substr(index + replacement.length);
  }

  canAttack(): boolean {
   return  (this.sameColumn(this._black, this._white) ||
   this.sameRow(this._black, this._white) ||
   this.sameDiagnol(this._black, this._white));
  }
  sameRow(white_piece: PieceType, black_piece: PieceType): boolean {
    return white_piece.location[0] === black_piece.location[0];
  }
  sameColumn(white_piece: PieceType, black_piece: PieceType): boolean {
    return white_piece.location[1] === black_piece.location[1];
  }
  
  sameDiagnol(white_piece: PieceType, black_piece: PieceType): boolean {
    const w_loc: [number, number] = [
      white_piece.location[0].valueOf(),
      white_piece.location[1].valueOf(),
    ];
    const b_loc: [number, number] = [
      black_piece.location[0].valueOf(),
      black_piece.location[1].valueOf(),
    ];
    const w_to_left: boolean = w_loc[0] < b_loc[0];
    const w_is_above: boolean = w_loc[1] > b_loc[1];

    // W in Lower Left
    if (w_to_left && !w_is_above) {
      while (w_loc[0] <= 7 && w_loc[1] <= 7) {
        // && w_loc[0] > 0 && w_loc[1] > 0
        if (w_loc[0] === b_loc[0] && w_loc[1] === b_loc[1]) {
          return true;
        }
        w_loc[0]++;
        w_loc[1]++;
      }
      return false;
    }
    // W in Upper Left 
    else if (w_to_left && w_is_above) {
      while (w_loc[0] <= 7 && w_loc[1] >= 0) {
        // && w_loc[0] > 0 && w_loc[1] > 0
        if (w_loc[0] === b_loc[0] && w_loc[1] === b_loc[1]) {
          return true;
        }
        w_loc[0]++;
        w_loc[1]--;
      }
      return false;
    } 
    // B in Lower Left
    else if (!w_to_left && w_is_above) {
      while (b_loc[0] <= 7 && b_loc[1] <= 7) {
        // && b_loc[0] > 0 && b_loc[1] > 0
        if (b_loc[0] === w_loc[0] && b_loc[1] === w_loc[1]) {
          return true;
        }
        b_loc[0]++;
        b_loc[1]++;
      }
      return false;
    } 
    // B in Upper Left
    else if (!w_to_left && !w_is_above) {
      while (b_loc[0] <= 7 && b_loc[1] >= 0) {
        // && b_loc[0] > 0 && b_loc[1] > 0
        if (b_loc[0] === w_loc[0] && b_loc[1] === w_loc[1]) {
          return true;
        }
        b_loc[0]++;
        b_loc[1]--;
      }
      return false;
    }
    else{
        return false;
    }
  }
}

enum Moves {
  Vertical,
  Horizontal,
  Diagnol,
  Hook,
}

enum PieceNames {
  Pawn,
  Knight,
  Bishop,
  Rook,
  Queen,
  King,
}

enum Team {
  Black,
  White,
}

abstract class PieceType {
  abstract type: PieceNames;
  abstract can_move: Moves[];
  abstract location: [number, number];
}

class Queen extends PieceType {
  type: PieceNames = PieceNames.Queen;
  can_move: Moves[] = [Moves.Diagnol, Moves.Vertical, Moves.Horizontal];
  location: [number, number];
  team: Team;
  constructor(team: Team, location: [number, number]) {
    super();
    this.team = team;
    this.location = location;
  }
}
type positions = {
  white: [number, number];
  black: [number, number];
};

export default QueenAttack;

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?