// ship should be 'A', 'B', 'C', or 'D' // loc should be validated // Orientation should be determined by the view/controller from user input public boolean placeShip(boolean isPlayer1, char ship, String loc, Orientation o) { Ship shipToPlace = getShip(ship); int startRow = getRow(loc); int startCol = getCol(loc); int dx = o.dx; int dy = o.dy; // attempt to place the ship in each BoardSquare for (int i = 0; i < shipToPlace.getLength(); i++) { int row = startRow + i * dy; int col = startCol + i * dx; Ship toChange = (isPlayer1) ? board[row][col].P1Ship : board[row][col].P2Ship; if (row < 0 || row > 9 || col < 0 || col > 9 || toChange != null) { shipToPlace = null; return false; } else { toChange = shipToPlace; } } // incrementShipCount() if (isPlayer1) { player1ShipCount++; } else { player2ShipCount++; } return true; }
// returns "Hit", "Miss", "Hit and sunk <ship_name>", or "Unsuccessful" public String makeShot(boolean isPlayer1, String loc) { int row = getRow(loc); int col = getCol(loc); BoardSquare current = board[row][col]; boolean isShot = (isPlayer1) ? current.P1Offensive : current.P2Offensive; if (isShot) { return "Unsuccessful"; } else { // loc has not been shot by player, set it as shot if (isPlayer1) { current.P1Offensive = true; } else { current.P2Offensive = true; } Ship target = (isPlayer1) ? board[row][col].P2Ship : board[row][col].P1Ship; if (target == null) { return "Miss"; } else { target.damage++; if (target.damage == target.getLength()) { // ship is destroyed, decrement ship count if (isPlayer1) { player2ShipCount--; } else { player2ShipCount--; } isGameOver = player1ShipCount <= 0 || player2ShipCount <= 0; String playerName = (isPlayer1) ? player1Name : player2Name; return "Hit and sunk " + playerName + "'s " + target.getReference() + "!"; } } return "Hit"; } }