
Bryce B.
asked 04/28/22Computer Science Code
I need the code and some explanations to the following prompt for coding because I am struggling with arrays and loops(1301 computer science)
How could I create a game for combat ships? I have to allow users to pick a board size between 6x6 and 10x10, then generate placements for 2 of each of the following ships: scouts(size 2), combat ships (size 3), and carriers (size 4). Ships should be placed either horizontally or vertically, but cannot cover the area of another ship. Once the board is generated and the ships are placed, allow the user to target the board without knowing the ship placement. If the user selects a location with a ship, display "hit", otherwise "miss". Once all slots containing a ship are hit, "You sunk my shipName" where shipName is the type of ship sunk. Once all ships are sunk, display "You Win!"
I need to create a combat ships class with one attribute, a 2D array of integers for my game board. My constructor should also call a method to place my initial ship positions. I believe the ship position should take one argument which could either be a ship id number or ship length. The position method should be placed at one ship at a time and should be called by the instructor 6 times. The method should first select an empty location on the game board, then attempt to place the rest of the ship in adjacent indices either horizontally or vertically. If one of those indices is already occupied, check in other directions. If all other directions is occupied, pick a new start state and try again.
The program should include a method for targeting a ship, and returning if its a hit or a miss.
The program should also include telling the user when they sink a ship and when they have won the game.
Also include a TOstring method that displays the current state of the board.
In the main method:
-Prompt the user to provide a board size, and use that to instantiate a Combat Ships object.
-In a loop ask the user to select a position to strike
-Tell the user if they hit or miss, inform the type of ship that they have sunk, and that they have won once all the ships have been sunk
-When the user has won use the Tostring method to display the state of the board
Thanks so much!
1 Expert Answer
Emily C. answered 06/11/25
Computer Science Tutor & University Senior
I wrote this in Java:
import java.util.Random;
public class CombatShips {
private int[][] board; // 0=empty, >0 = ship id
private int size;
private int[] shipSizes = {2, 2, 3, 3, 4, 4}; // 6 ships: 2 scouts, 2 combats, 2 carriers
private String[] shipNames = {"Scout", "Scout", "Combat", "Combat", "Carrier", "Carrier"};
private int[] shipHits; // track how many hits each ship took
private boolean[] shipSunk; // track sunk state for each ship
private static final int HIT = -1; // mark hit cells
private static final int MISS = -2; // mark miss cells
private Random rand = new Random();
public CombatShips(int boardSize) {
this.size = boardSize;
board = new int[size][size];
shipHits = new int[6];
shipSunk = new boolean[6];
placeAllShips();
}
// Place all ships by calling placeShip 6 times
private void placeAllShips() {
for (int shipId = 0; shipId < shipSizes.length; shipId++) {
placeShip(shipId, shipSizes[shipId]);
}
}
// Tries to place one ship (by shipId and size) on the board randomly
private void placeShip(int shipId, int length) {
boolean placed = false;
while (!placed) {
// Random start position
int row = rand.nextInt(size);
int col = rand.nextInt(size);
// Random orientation: true = horizontal, false = vertical
boolean horizontal = rand.nextBoolean();
// Check if ship fits and doesn't overlap
if (canPlaceShip(row, col, length, horizontal)) {
// Place ship by marking board with shipId+1 (to avoid 0)
for (int i = 0; i < length; i++) {
if (horizontal) {
board[row][col + i] = shipId + 1;
} else {
board[row + i][col] = shipId + 1;
}
}
placed = true;
}
// If can't place, loop again with new random position/orientation
}
}
// Check if ship fits on board and doesn't overlap another ship
private boolean canPlaceShip(int row, int col, int length, boolean horizontal) {
if (horizontal) {
if (col + length > size) return false; // out of bounds right
for (int i = 0; i < length; i++) {
if (board[row][col + i] != 0) return false; // overlap
}
} else {
if (row + length > size) return false; // out of bounds down
for (int i = 0; i < length; i++) {
if (board[row + i][col] != 0) return false; // overlap
}
}
return true;
}
// User targets a position, returns result string
public String target(int row, int col) {
if (row < 0 || row >= size || col < 0 || col >= size) {
return "Invalid coordinates.";
}
int cell = board[row][col];
if (cell == HIT || cell == MISS) {
return "Already targeted this location.";
}
if (cell > 0) { // it's a ship
board[row][col] = HIT;
int shipId = cell - 1;
shipHits[shipId]++;
if (!shipSunk[shipId] && shipHits[shipId] == shipSizes[shipId]) {
shipSunk[shipId] = true;
if (allShipsSunk()) {
return "You sunk my " + shipNames[shipId] + "! You Win!";
}
return "You sunk my " + shipNames[shipId] + "!";
}
return "Hit!";
} else {
board[row][col] = MISS;
return "Miss.";
}
}
// Check if all ships are sunk
private boolean allShipsSunk() {
for (boolean sunk : shipSunk) {
if (!sunk) return false;
}
return true;
}
// Show the board: H = hit, M = miss, . = unknown, S = sunk ship cells shown, nothing else
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" ");
for (int c = 0; c < size; c++) {
sb.append(c).append(" ");
}
sb.append("\n");
for (int r = 0; r < size; r++) {
sb.append(r).append(" ");
for (int c = 0; c < size; c++) {
int val = board[r][c];
if (val == HIT) {
sb.append("H ");
} else if (val == MISS) {
sb.append("M ");
} else if (val > 0 && shipSunk[val - 1]) {
sb.append("S "); // show sunk ship positions
} else {
sb.append(". "); // unknown cell
}
}
sb.append("\n");
}
return sb.toString();
}
}
The Main class to help run the program: import java.util.Scanner;
public class CombatShipsGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt board size
int boardSize = 0;
do {
System.out.print("Enter board size (6 to 10): ");
boardSize = scanner.nextInt();
} while (boardSize < 6 || boardSize > 10);
CombatShips game = new CombatShips(boardSize);
System.out.println("Game started! Try to sink all ships.");
while (true) {
System.out.print("Enter row to target (0 to " + (boardSize - 1) + "): ");
int row = scanner.nextInt();
System.out.print("Enter column to target (0 to " + (boardSize - 1) + "): ");
int col = scanner.nextInt();
String result = game.target(row, col);
System.out.println(result);
if (result.contains("You Win!")) {
System.out.println("Final board:");
System.out.println(game.toString());
break;
}
}
scanner.close();
}
}
How this program works:
- combatShips() constructor creates the board and calls placeAllShips() to randomly place all ships.
- placeShip() tries random positions and orientations until it finds a valid place.
- The board uses integers:
- 0 = empty
0 = ship ID + 1
- -1 = hit spot
- -2 = miss spot
- The target(row, col) method marks hits and misses and tells when a ship is sunk.
- When all ships are sunk, it returns "You Win!" and game ends.
- The toString() shows the board, revealing hits, misses, and sunk ship parts.
- In main(), the user picks board size, then enters coordinates to target until the game ends.
Tips to Understand
- The board is a 2D array of integers representing the game state.
- We use loops to:
- Check if ship placement is valid (canPlaceShip).
- Place ships on the board.
- Display the board.
- The ship placement retries random positions until success.
- We track hits per ship with arrays: shipHits and shipSunk.
- User input drives the game loop.
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Donald W.
This problem is too big to be answered in a single answer. If you still need help with this, you should seek out a tutor to go through this in detail. There's a lot here.04/29/22