Citadel questions

Battleship

CitadelPhone screenMedium

You are building the game logic for two-player Battleship as the class Battleship, created with the board size n. Each player, "A" or "B", has their own n by n board. Rows and columns are numbered from 0, with (0, 0) at the top left.

Part 1: Place Ships

Implement place_ship(player, row, col, size, direction), which places a ship on player's board and returns true, or returns false and changes nothing.

The ship covers size consecutive cells starting at (row, col): with direction "H" it extends to the right along the row, with "V" it extends downward along the column. The placement fails when size < 1, when any covered cell is off the board, or when any covered cell already holds one of the same player's ships. Ships may touch, and a player may place any number of ships. The two players' boards are independent.

Also implement ship_cells(player), which returns every cell holding one of player's ships as [row, col] pairs, sorted by row, then column.

  1. Example 1
    init
    [5]
    operations
    [["place_ship",["A",0,0,3,"H"]],["place_ship",["A",1,2,3,"V"]],["place_ship",["A",2,0,3,"H"]],["place_ship",["A",3,3,3,"H"]],["place_ship",["B",0,0,3,"H"]],["ship_cells",["A"]],["ship_cells",["B"]]]
    Output
    [true,true,false,false,true,[[0,0],[0,1],[0,2],[1,2],[2,2],[3,2]],[[0,0],[0,1],[0,2]]]

    Why: A's first ship covers (0,0), (0,1), (0,2). The vertical ship from (1,2) covers (1,2), (2,2), (3,2): it touches the first ship but shares no cell, so it is placed. The horizontal ship from (2,0) would cover (2,2), which is taken, and the one from (3,3) would need columns 3, 4 and 5 on a 5-wide board, so both fail. B can use the cells A has, because each player has a board of their own.

Constraints

  • 1 <= n <= 20
  • player is "A" or "B", and direction is "H" or "V"
  • -100 <= row, col, size <= 100
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question