I need help with keeping it within the range of the board at the edges. Also, after the missile launch, I would like to scan the entire board for any boats that have sunk. Meaning, I would like to check if any boats in an array of boats exist on the board. If it cannot find a boat of a specific name from the Boat array within the 2D board, I would want it to return false. This seems simple to accomplish in python, but I'm not sure how to do it for java.
Missile
At any point in the game, once the board is initialized and the
mode has been chosen, the user can type in "missile" (or whatever
way you want them to signify to the program that they wish to use a
missile).
The program will then ask the user for a coordinate. The user will
type in two numbers (Example: 0 5). The program will then check if
the coordinate (0,5) is valid for the board. If it is not, the
program will continue to ask the user to type in valid coordinates
until the user does so.
Next, the program will fire a missile in that spot, what that means
is that it will fire at a 3x3 square, with the chosen spot being in
the very center of the square. If the chosen spot is near the edge
of the board, the missile will only hit the spots on the
board.
Example:
User: Types in missile
Terminal: Where would you like to launch your missile?
User: 2 2
In the above case, a missile will launch at coordinates (2,2). This
will hit spots (1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2), and
(3,3).
Another example is if a user launches a missile at coordinates
(0,0). In this case, because (0,0) is near the edge of the board,
only the spots that are on the board will be hit. In this case
spots (0,0),(0,1),(1,0) and (1,1) will be hit. Note: It is fine if
the spot to launch the missile has already been fired upon, or even
if all the spots the missile will be hit have already been red
upon. The only invalid missile use is ring outside of the
board.
Board:
The computer will simulate a square n x n board. You are
required to use a 2-dimensional array to represent the board. The
type of this array is up to the programmer. The user will select
whether they want to play the game on Standard or Expert mode
when
the program starts. If Standard mode is selected, the program
should create a board of 8 rows by 8 columns. If Expert mode is
selected, the program should create a board of 12 rows by 12
columns. Assume that the points in the normal mode board range from
(0; 0) to (7; 7) inclusive, and from (0; 0) to (11; 11) inclusive
in the hard mode.
BattleBoatsBoard Class
- Contains a 2D Array (Can contain ints or strings depending on
implementation)
- Contains int variables to keep tracks of total shots, turns, and
ships remaining.
- Constructor takes in an int size variable as argument (Will be 8
in case of standard mode, 12
in expert), and correctly sizes the array upon construction.
- Has placeBoats() function to randomly place boats on board.
- Has fire(int x, int y) function to handle ring on a
coordinate.
- Has display() function to print out the player board state every
turn.
- Has print() function to print out the fully revealed board if a
player types in the print
command
- Has missile(int x, int y) function to re a missile on a specifed
coordinate
- Has drone(int direction,int index) function to scan a specific
row or column
private String[][] gameboard; private String[][] display; // array that keeps track of where user has already fired private Boats[] arrayBoat; private int size; // size of board private int boats; // number of boats that start on the board private int drone; // number of drones available to use private int missile; // number of missiles available to use private int turns = 1; // counter for turns private int shots; // number of shots user has taken
Program File
Main.java
public class Main {
public static void main(String[] args){
// call the construcor of BattleBoatsGame
BattleBoatsGame b1 = new BattleBoatsGame();
// start the game
b1.main();
}
}

BattleBoat.java
public class BattleBoat {
private int[][] boat;
private int length;
private char symbol;
//Automatic Constructor
public BattleBoat(int size, char sym, char[][] board){
boat = new int[size][2];
length = size;
symbol = sym;
this.placeBoatRandom(board);
}//End of Automatic Constructor
//Manual Constructor
public BattleBoat(int size, char sym, char[][] board, int
originRow, int originCol, char dir){
boat = new int[size][2];
length = size;
symbol = sym;
this.fillSpaces(originRow, originCol,dir);
if(this.placeBoat(board)){
System.out.println("Boat Placed.");
}else{
System.out.println("Boat is Invalid.");
}
}//End of Manual Constructor
//Getter and Setters
public char getSymbol(){return symbol;}
//Helper Method, returns true if coordinates belong to the
boat
public boolean isBoatThere(int row, int col){
for(int[] coords: boat){
if(coords[0] == row && coords[1] == col){
return true;
}
}
return false;
}
//Helper Method, takes in a coordinate and direction and
calculates the reamining coordinates and stores them
//in the boat variable
//Used by: generateNewPlacement
public void fillSpaces(int originRow,int originCol, char
direction){
if(direction == 'h'){
for(int i = 0; i < length; i++){
boat[i][0] = originRow;
boat[i][1] = originCol + i;
}
}
if(direction == 'v'){
for(int i = 0; i < length; i++){
boat[i][0] = originRow + i;
boat[i][1] = originCol;
}
}
}
//Takes in a max value(size of the board) and generates a random
direction and starting to coordinate,
//then calls a helper method to fill in the remaining coordinates
in boat
//Used by: placeBoatRandom
public void generateNewPlacement(int max){
//Determine Direction
char dir = ' ';
if(Math.random() > 0.5){
dir = 'h';
}else{
dir = 'v';
}
//Determine Origin
int originX = (int)(Math.random()*max);
int originY = (int)(Math.random()*max);
this.fillSpaces(originX,originY,dir);
}
//Attempts to place a boat, returns false if space is occupied or
out of bounds. If it can succesfully place
//the boat, will modify the board and return true.
//Used by: placeBoatRandom
public boolean placeBoat(char[][] board){
for(int i = 0; i < boat.length;i++){
if((boat[i][0] > board.length-1) || (boat[i][1] >
board.length-1) || !(board[boat[i][0]][boat[i][1]] == '_')){
//System.out.println("Could not place boat");
return false;
}
}
for(int i = 0; i < boat.length;i++){
board[boat[i][0]][boat[i][1]] = symbol;
}
return true;
}
//Keeps attempting to place the boat in a random location until
successful
//Used by: Constructor
public void placeBoatRandom(char[][] board){
do{
this.generateNewPlacement(board.length);
}while(!(this.placeBoat(board)));
}
public boolean isSunk(char[][] board){
for(int[] coord: boat){//For each coord in boat
if(board[coord[0]][coord[1]] != 'X'){//If is not hit
return false;
}
}
return true;
}
}

BattleBoatsBoard.java
public class BattleBoatsBoard {
private int drone;
private int missle;
private char[][] board;
private BattleBoat[] boats;
private int size;
private boolean skipNextTurn = false;
public BattleBoatsBoard(int size){
this.size = size;
//Build Board
board = new char[size][size];
for(int x=0; x<size; x++) {
for (int y = 0; y < size; y++) {
board[x][y] = '_';
}
}
//STANDARD MODE
if(size == 8){
boats = new BattleBoat[5];
drone = 1;
missle = 1;
//Place Boats
boats[0] = new BattleBoat(2,'a',board);
boats[1] = new BattleBoat(3,'b',board);
boats[2] = new BattleBoat(3,'c',board);
boats[3] = new BattleBoat(4,'d',board);
boats[4] = new BattleBoat(5,'e',board);
}
//EXPERT MODE
if(size == 12){
boats = new BattleBoat[10];
drone = 2;
missle = 2;
//Place Boats
boats[0] = new BattleBoat(2,'a',board);
boats[1] = new BattleBoat(2,'b',board);
boats[2] = new BattleBoat(3,'c',board);
boats[3] = new BattleBoat(3,'d',board);
boats[4] = new BattleBoat(3,'e',board);
boats[5] = new BattleBoat(3,'f',board);
boats[6] = new BattleBoat(4,'g',board);
boats[7] = new BattleBoat(4,'h',board);
boats[8] = new BattleBoat(5,'i',board);
boats[9] = new BattleBoat(5,'j',board);
}
}//End of Constructor
//Getters and Setters
public char[][] getBoard(){return board;}
public boolean doSkip(){return skipNextTurn;}
public int getMissles(){return missle;}
public int getDrones(){return drone;}
public int getSize(){return size;}
//Skip Turn
public void skipTurn(){
skipNextTurn = false;
}
//Gets a boat if coordinates are correct
public BattleBoat getBoat(int row, int col){
for(BattleBoat boat : boats){
if(boat.isBoatThere(row,col)){
return boat;
}
}
return null;
}
//Typical Fire
//Returns a string depending on the outcome.
public String fire(int row, int col){
if(row < 0 || col < 0 || row>= size || col>=
size){
skipNextTurn = true;
return "Out of Bounds. Penalty.";
}
char target = board[row][col];
switch(target){
case 'X':
skipNextTurn = true;
return "Already fired there! Penalty.";
case 'O':
skipNextTurn = true;
return "Already fired there! Penalty.";
case '_':
board[row][col] = 'O';
return "Miss";
default:
board[row][col] = 'X';
return "Hit";
}
}//End of fire
//Scans a row or column and returns spots with boats
public int drone(String mode, int n){
drone -= 1;
int result = 0;
for(int i = 0; i < size; i++){
if(mode.equals("row") || mode.equals("r")){
if(board[n][i] != 'O' && board[n][i] != '_'){
result += 1;
}
}
if(mode.equals("col") || mode.equals("c")){
if(board[i][n] != 'O' && board[i][n] != '_'){
result += 1;
}
}
}
return result;
}//End of drone
//Hits a 3x3 area, returns false if out of range, true if the
launch was succesful
public boolean missle(int row, int col){
if(row >= size || col >= size || row < 0 || col <
0){
System.out.println("Invalid Input, try again.");
return false;
}else{
for(int i = -1; i<2; i++){
for(int j = -1; j<2; j++){
fire(row + i,col + j);
}
}
missle -= 1;
skipNextTurn = false;//Prevent a false penalty
return true;
}
}
//Checks to see if Game is Over
public boolean isGameOver(){
for(BattleBoat boat : boats){
if(!boat.isSunk(board)){
return false;
}
}
return true;
}
//Shows Boat Locations
public String toString(){
String result = "";
for(int row = 0; row < size;row++){
for(int col = 0; col < size; col++){
result = result + "["+board[row][col]+"]";
}
result = result + "\n";
}
return result;
}
//Shows Info Only Avaiable to User
public String toDisplay(){
String result = "\n";
for(int row = 0; row < size;row++){
for(int col = 0; col < size; col++){
if(board[row][col] == 'X'){
result = result + "["+this.getBoat(row,col).getSymbol()+"]";
}else if(board[row][col] == 'O'){
result = result + "[O]";
}else{
result = result + "[_]";
}
}
result = result + "\n";
}
return result;
}
}//End of Class



BattleBoatsGame.java
import java.util.Scanner;
public class BattleBoatsGame {
private int turns = 0;
private int shots = 0;
private Scanner myScanner = new Scanner(System.in);
private BattleBoatsBoard board;
private String drone = "";
private String help = "\nType in 'missle' or 'm' to use a
missle.\n" +
"Type in 'drone' or 'd' to use a drone.\n" +
"Enter 'print' or 'p' to see the board again.\n"+
"Enter coordinates in the format '<row> <col>' to
fire.\n";
public BattleBoatsGame(){
String input = "";
do{
System.out.println("Type in 'standard' or 's' to play in standard
mode.\n"+
"Type in 'expert' or 'e' to play in expert mode.\n");
input = myScanner.nextLine();
input = input.toLowerCase();
if(input.equals("standard") || input.equals("s")){
board = new BattleBoatsBoard(8);
System.out.println(help);
}else if(input.equals("expert") || input.equals("e")){
board = new BattleBoatsBoard(12);
System.out.println(help);
}
}while(!(input.equals("standard")||input.equals("s")||input.equals("expert")||input.equals("e")));
}
//Takes a turn, should return true if turn executed correctly
public boolean turn(){
turns += 1;
//Skips a turn
if(board.doSkip()){
System.out.println("\nTurn Skipped.\n");
board.skipTurn();
return true;//Ends Turn
}
//Display Board
System.out.println("\nCurrent Board:"+board.toDisplay());
//Asks player what to do next
do {
String input = "";
do {
input = myScanner.nextLine();
input = input.toLowerCase();
}while((input.equals("")));//Check to see if anything was
entered.
//Print Board
if (input.equals("print") || input.equals("p")) {
System.out.print(drone);
turns -= 1;//Doesnt count as a turn
return true;
}
//Missile
else if (input.equals("missle") || input.equals("m")) {
if (board.getMissles() == 0) {
System.out.println("Out of Missles, try again.");
} else {
boolean result = false;//To track wheather missle is invalid or
not
do {
System.out.println("Enter center coordinates:");
String line = myScanner.nextLine();
String[] coords = line.split(" ");
try {
int row = Integer.parseInt(coords[0]);
int col = Integer.parseInt(coords[1]);
result = board.missle(row, col);
} catch (NumberFormatException e) {
System.out.println("Invalid coordinates, try again.");
}
if (result) { //If succesful turn is over
System.out.println("Missle Fired.\n");
return true;//Ends turn
}
} while (!result);//If false, invalid coordinates were entered. Try
again.
}
}else if(input.equals("drone") || input.equals("d")) {//Drone
if (board.getDrones() == 0) {
System.out.println("Out of Drones, try again.");
}else{
String mode = "";
do {
System.out.println("Enter 'row' or 'col' to scan.");
mode = myScanner.nextLine();
mode = mode.toLowerCase();
} while (!(mode.equals("row") || mode.equals("col") ||
mode.equals("r") || mode.equals("c")));
int scan = 0;
do {
System.out.println("Enter a number to scan.");
scan = myScanner.nextInt();
} while (!(scan < board.getSize() && scan >=
0));
drone += "\nShip tiles found in "+mode+" "+scan+" : " +
board.drone(mode,scan);
System.out.println(drone);
return true;//Ends turn
}
}else{//Fire
try {
String[] coords = input.split(" ");
int row = Integer.parseInt(coords[0]);
int col = Integer.parseInt(coords[1]);
System.out.println(board.fire(row, col));
shots += 1;
return true;
} catch (NumberFormatException n) {
System.out.println("Invalid input, try again.\n");
System.out.println(help);
turns -= 1;//Doesnt count as a turn
} catch (ArrayIndexOutOfBoundsException a) {
System.out.println("Enter two numbers seperated by a space to fire,
try again.\n");
turns -= 1;//Doesnt count as a turn
}
}
} while(true);
}
public void main(){
do{
this.turn();
}while(!(board.isGameOver()));
System.out.println(board.toDisplay());
System.out.println("\nYou sunk all the battle ships!");
System.out.println("Total turns: "+turns);
System.out.println("Total shots:"+shots);
}
}


output
Type in 'standard' or 's' to play in standard
mode.
Type in 'expert' or 'e' to play in expert mode.
s
Type in 'missle' or 'm' to use a missle.
Type in 'drone' or 'd' to use a drone.
Enter 'print' or 'p' to see the board again.
Enter coordinates in the format '<row> <col>' to
fire.
Current Board:
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
m
Enter center coordinates:
1 4
Missle Fired.
Current Board:
[_][_][_][O][O][O][_][_]
[_][_][_][O][O][a][_][_]
[_][_][_][b][b][O][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
[_][_][_][_][_][_][_][_]
m
Out of Missles, try again.

Hope this helps!
Please let me know if any changes needed.
Thank you!
I need help with keeping it within the range of the board at the edges. Also,...
Imagine we are using a two-dimensional array as the basis for creating the game battleship. In the game of battleship a '~' character entry in the array represents ocean, a '#' character represents a place ion the ocean where part of a ship is present, and an 'H' character represents a place in the ocean where part of a ship is present and has been hit by a torpedo. Thus, a ship with all 'H' characters means the ship has...
There are a number of changes that we need to make: 1) We need to take the board size (width and height) as command line parameters. If these are not specified, we should print out a message informing the user how to call the program. 2) We need to initialize a game board. Allocate memory, decide if each square has bombs, and count the squares surrounding that have bombs. 3) We need to free the game board. Because we need...
For this exercise, you will complete the TicTacToe Board that we started in the 2D Arrays Lesson. We will add a couple of methods to the TicTacToe class. To track whose turn it is, we will use a counter turn. This is already declared as a private instance variable. Create a getTurn method that returns the value of turn. Other methods to implement: printBoard()- This method should print the TicTacToe array onto the console. The board should include numbers that...
Please I need your help I have the code below but I need to add one thing, after player choose "No" to not play the game again, Add a HELP button or page that displays your name, the rules of the game and the month/day/year when you finished the implementation. import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; import javax.swing.event.*; import java.util.Random; public class TicTacToe extends JFrame implements ChangeListener, ActionListener { private JSlider slider; private JButton oButton, xButton; private Board...
c++ help please!
Create a 2D character array in your main function and
use nested for loops to fill the array with the letter ‘e’ to
represent empty spaces.
Create a function to print the board on the screen using
a nested for loop. The function header is:
void printBoard (char board [][3])
Create a function that checks whether a particular space
has already been filled. If the space is filled it returns a
boolean value of true, otherwise false....
I need help finishing my C++ coding assignment! My teacher has provided a template but I need help finishing it! Details are provided below and instructions are provided in the //YOU: comments of the template... My teacher has assigned a game that is similar to battleship but it is single player with an optional multiplayer AI... In the single player game you place down a destroyer, sub, battleship, and aircraft carrier onto the grid.... Then you attack the ships you...
Please, I need help with program c++. This is a chutes and ladders program. The code must be a novel code to the specifications of the problem statement. Thank you very much. Assignment Overview This program will implement a variation of the game “chutes and ladders” or “snakes and ladders:” https://en.wikipedia.org/wiki/Snakes_and_Ladders#Gameplay. Just like in the original game, landing on certain squares will jump the player ahead or behind. In this case, you are trying to reach to bottom of the...
In C++ please.. I only need the game.cpp. thanks. Game. Create a project titled Lab8_Game. Use battleship.h, battleship.cpp that mentioned below; add game.cpp that contains main() , invokes the game functions declared in battleship.h and implements the Battleship game as described in the introduction. ——————————————- //battleship.h #pragma once // structure definitions and function prototypes // for the battleship assignment // 3/20/2019 #include #include #ifndef BATTLESHIP_H_ #define BATTLESHIP_H_ // // data structures definitions // const int fleetSize = 6; // number...
could you please help me with this problem, also I
need a little text so I can understand how you solved the
problem?
import java.io.File; import java.util.Scanner; /** *
This program lists the files in a directory specified by * the
user. The user is asked to type in a directory name. * If the name
entered by the user is not a directory, a * message is printed and
the program ends. */ public class DirectoryList { public static...
I have already finished most of this assignment. I just need some help with the canMove and main methods; pseudocode is also acceptable. Also, the programming language is java. Crickets and Grasshoppers is a simple two player game played on a strip of n spaces. Each space can be empty or have a piece. The first player plays as the cricket pieces and the other plays as grasshoppers and the turns alternate. We’ll represent crickets as C and grasshoppers as...