Question

CodeHS Java: Battleship part 6: The Battleship Class *please look up the entire battleship module on...

CodeHS Java: Battleship part 6: The Battleship Class

*please look up the entire battleship module on the CodeHS website beforehand to get a proper understanding

In this part we’ll start writing our Battleship class, which hooks all of the parts of our game together. You’ll want to make two Player objects. The goal for this part is to create two players, then be able to print out the current board status that they have, and then make a guess and have it update the underlying data structure as well as show in the display. Here you may need to go back and make modifications to your Player class. We recommend writing a method in the Battleship class called: askForGuess Which asks the user player for a valid row and column to guess as a location of the opponents battleship. If there is a ship on the opponents board it should indicate that.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the code for the part 6 : The Battle ship class along with test codes for others classes//Main.java

class Main {

public static void main(String[] args) {

// Test the Player class

Player user = new Player();

Player computer = new Player();

// USER

// First ship (with length 2), row 4, col 9, vertical

user.chooseShipLocation(user.getShip(0), 4, 9, 1);

// Second ship (with length 3), row 9, col 2, horizontal

user.chooseShipLocation(user.getShip(1), 9, 2, 0);

// Third ship (with length 3), row 5, col 3, horizontal

user.chooseShipLocation(user.getShip(2), 5, 3, 0);

// Fourth ship (with length 4), row 1, col 3, horizontal

user.chooseShipLocation(user.getShip(3), 1, 3, 0);

// Fifth ship (with length 5), row 4, col 9, vertical

user.chooseShipLocation(user.getShip(4), 1, 1, 1);

// COMPUTER

// First ship (with length 2), row 8, col 8, horizontal

computer.chooseShipLocation(user.getShip(0), 8, 8, 0);

// Second ship (with length 3), row 6, col 1, vertical

computer.chooseShipLocation(user.getShip(1), 6, 1, 1);

// Third ship (with length 3), row 4, col 3, vertical

computer.chooseShipLocation(user.getShip(2), 4, 3, 1);

// Fourth ship (with length 4), row 0, col 5, horizontal

computer.chooseShipLocation(user.getShip(3), 0, 5, 0);

// Fifth ship (with length 5), row 2, col 5, horizontal

computer.chooseShipLocation(user.getShip(4), 2, 5, 0);

System.out.println("Player 1's Ships");

user.printMyShips();

System.out.println();

System.out.println("Player 2's Ships");

computer.printMyShips();

System.out.println();

// System.out.println("Player 1's Guesses");

// user.printMyGuesses();

// System.out.println();

// System.out.println("Player 2's Guesses");

// computer.printMyGuesses();

// System.out.println();

computer.recordMyGuess(1, 1);

user.recordOpponentGuess(1, 1); // Computer Hits User

user.recordMyGuess(5, 5);

computer.recordOpponentGuess(5, 5); // User Misses Computer

computer.recordMyGuess(2, 5);

user.recordOpponentGuess(2, 5); // Computer Misses User

user.recordMyGuess(5, 3);

computer.recordOpponentGuess(5, 3); // User Hits Computer

System.out.println("Player 1's Opponent Guesses");

user.printOpponentGuesses();

System.out.println();

System.out.println("Player 2's Opponent Guesses");

computer.printOpponentGuesses();

System.out.println();

// // Test the Grid class

// Grid b = new Grid();

// b.printStatus();

// Ship aircraftCarrier = new Ship(5);

// Ship battleship = new Ship(4);

// Ship submarine = new Ship(3);

// Ship cruiser = new Ship(3);

// Ship destroyer = new Ship(2);

// aircraftCarrier.setLocation(1,1);

// aircraftCarrier.setDirection(1); //vertical

// battleship.setLocation(1, 3);

// battleship.setDirection(0); //horizontal

// submarine.setLocation(5,3);

// submarine.setDirection(0); //horizontal

// cruiser.setLocation(9,2);

// cruiser.setDirection(0); //horizontal

// destroyer.setLocation(4,9);

// destroyer.setDirection(1); //vertical

// b.addShip(aircraftCarrier);

// b.addShip(battleship);

// b.addShip(submarine);

// b.addShip(cruiser);

// b.addShip(destroyer);

// b.markHit(5,2);

// b.markHit(15,12);

// b.markMiss(3,8);

// b.markHit(-5,0);

// b.setStatus(0,0,1);

// b.setStatus(0,1,2);

// System.out.println();

// b.printStatus();

// System.out.println();

// b.printShips();

// //Test the Location class

// Location l = new Location();

// System.out.println(l.checkHit()); //false

// System.out.println(l.checkMiss()); //false

// System.out.println(l.isUnguessed()); //true

// System.out.println(l.hasShip()); //false

// l.setShip(true);

// System.out.println(l.hasShip()); //true

// l.markMiss();

// System.out.println(l.isUnguessed()); //false

// System.out.println(l.checkHit()); //false

// System.out.println(l.checkMiss()); //true

// l.markHit();

// System.out.println(l.isUnguessed()); //false

// System.out.println(l.checkHit()); //true

// System.out.println(l.checkMiss()); //false

// l.setStatus(0);

// System.out.println(l.isUnguessed()); //true

// System.out.println(l.checkHit()); //false

// System.out.println(l.checkMiss()); //false

// //Test the Ship class

// Ship aircraftCarrier = new Ship(5);

// Ship battleship = new Ship(4);

// Ship submarine = new Ship(3);

// Ship cruiser = new Ship(3);

// Ship destroyer = new Ship(2);

// System.out.println(aircraftCarrier);

// System.out.println(battleship);

// System.out.println(submarine);

// System.out.println(cruiser);

// System.out.println(destroyer);

}

}

Output

Also attaching codes for other classes to check and compare with your program so far.

player.java

import java.util.*;

public class Player
{
private ArrayList<Ship> ships;
private ArrayList<Grid> grids;
private Grid playerGrid;
private Grid opponentGrid;
// These are the lengths of all of the ships.
private static final int[] SHIP_LENGTHS = {2, 3, 3, 4, 5};
  
public Player(){
ships = new ArrayList<Ship>();
grids = new ArrayList<Grid>();
  
for(int i = 0; i < 5; i++)
{
Ship s = new Ship(SHIP_LENGTHS[i]);
ships.add(s);
}
  
playerGrid = new Grid();
opponentGrid = new Grid();
grids.add(playerGrid);
grids.add(opponentGrid);
}
  
public Ship getShip(int num){
return ships.get(num);
}
  
public Grid getGrid(int num){
return grids.get(num);
}
  
public void chooseShipLocation(Ship s, int row, int col, int direction){
s.setLocation(row, col);
s.setDirection(direction);
playerGrid.addShip(s);
}
  
public void printMyShips(){
playerGrid.printShips();
}
  
public void printOpponentGuesses(){
playerGrid.printStatus();
}
  
public void printMyGuesses(){
opponentGrid.printStatus();
}
  
public void recordMyGuess(int row, int col){
// this will eventually need to look at the opponent's board
// and mark a hit or miss on this player's opponentGrid
}
  
public void recordOpponentGuess(int row, int col){
int checkStatus = playerGrid.getStatus(row, col);
if(checkStatus == 0){ // if the location is unguessed
if(playerGrid.hasShip(row, col)){
playerGrid.markHit(row, col);
}
else{
playerGrid.markMiss(row, col);
}
}
}
}

ship.java

public class Ship
{
//Create instance variables
private int row;
private int col;
private int length;
private int direction;
  
// Direction constants
public static final int UNSET = -1;
public static final int HORIZONTAL = 0;
public static final int VERTICAL = 1;
  
//Create constructor
public Ship(int length){
this.length = length;
this.row = UNSET;
this.col = UNSET;
this.direction = UNSET;
}
  
//Create methods
  
// Has the location been initialized
public boolean isLocationSet(){
return row >= 0 && row <= 9 && col >= 0 && col <= 9;
}
  
// Has the direction been initialized
public boolean isDirectionSet(){
return direction == 0 || direction == 1;
}
  
// Set the location of the ship
public void setLocation(int row, int col){
if(row >= 0 && row <= 9 && col >= 0 && col <= 9){
this.row = row;
this.col = col;
}
}
  
// Set the direction of the ship
public void setDirection(int direction){
if(direction == 0 || direction == 1){
this.direction = direction;
}
}
  
// Getter for the row value
public int getRow(){
return this.row;
}
  
// Getter for the column value
public int getCol(){
return this.col;
}
  
// Getter for the length of the ship
public int getLength(){
return this.length;
}
  
// Getter for the direction
public int getDirection(){
return this.direction;
}
  
// Helper method to get a string value from the direction
private String directionToString(){
if(getDirection() == -1){
return "unset direction";
}
if(getDirection() == 0){
return "horizontal";
}
return "vertical";
}
  
// Helper method to get a (row, col) string value from the location
private String locationToString(){
if(getRow() == -1 || getCol() == -1){
return "(unset location)";
}
return "(" + getRow() + ", " + getCol() + ")";
}
  
// toString value for this Ship
public String toString(){
return directionToString() + " ship of length "+ this.length +" at "+ locationToString();
}
}


location.java

public class Location
{
public static final int UNGUESSED = 0;
public static final int HIT = 1;
public static final int MISSED = 2;
  
private boolean shipStatus;
private int status;
  
// Location constructor.
public Location(){
shipStatus = false;
status = UNGUESSED;
}
  
// Was this Location a hit?
public boolean checkHit(){
return status == HIT;
}
  
// Was this location a miss?
public boolean checkMiss(){
return status == MISSED;
}
  
// Was this location unguessed?
public boolean isUnguessed(){
return status == UNGUESSED;
}
  
// Mark this location a hit.
public void markHit(){
status = HIT;
}
  
// Mark this location a miss.
public void markMiss(){
status = MISSED;
}
  
// Return whether or not this location has a ship.
public boolean hasShip(){
return shipStatus;
}
  
// Set the value of whether this location has a ship.
public void setShip(boolean val){
shipStatus = val;
}
  
// Set the status of this Location.
public void setStatus(int status){
if(status == UNGUESSED || status == HIT || status == MISSED){
this.status = status;
}
}
  
// Get the status of this Location.
public int getStatus(){
return status;
}

}

grid.java

public class Grid
{
private Location[][] grid;

// Constants for number of rows and columns.
public static final int NUM_ROWS = 10;
public static final int NUM_COLS = 10;
  
  
// Create a new Grid. Initialize each Location in the grid
// to be a new Location object.
public Grid(){
grid = new Location[NUM_ROWS][NUM_COLS];
for(int row = 0; row < NUM_ROWS; row++){
for(int col = 0; col < NUM_COLS; col++){
Location l = new Location();
grid[row][col] = l;
}
}
}
  
/**
* This method can be called on your own grid. To add a ship
* we will go to the ships location and mark a true value
* in every location that the ship takes up.
*/
public void addShip(Ship s){
int row, col, dir, len;
row = col = dir = len = 0;
if(s.isLocationSet() && s.isDirectionSet()){
row = s.getRow();
col = s.getCol();
dir = s.getDirection();
len = s.getLength();
}
if(dir == 0){ // if the direction is horizontal
if(NUM_COLS - col >= len){
for(int i = col; i < col + len; i++){
setShip(row, i, true);
}
}
}
if(dir == 1) { //if the direction is vertical
if(NUM_ROWS - row >= len){
for(int i = row; i < row + len; i++){
setShip(i, col, true);
}
}
}
}

// Mark a hit in this location by calling the markHit method
// on the Location object.
public void markHit(int row, int col){
if(row >= 0 && row <= NUM_ROWS - 1 && col >= 0 && col <= NUM_COLS - 1){
grid[row][col].setStatus(1);
}
}

// Mark a miss on this location.
public void markMiss(int row, int col){
if(row >= 0 && row <= 9 && col >= 0 && col <= 9){
grid[row][col].setStatus(2);
}
}

// Set the status of this location object.
public void setStatus(int row, int col, int status){
if(row >= 0 && row <= NUM_ROWS - 1 && col >= 0 && col <= NUM_COLS - 1 && status >= 0 && status <= 2){
grid[row][col].setStatus(status);
}
}

// Get the status of this location in the grid
public int getStatus(int row, int col){
Location l = grid[row][col];
return l.getStatus();
}

// Return whether or not this Location has already been guessed.
public boolean alreadyGuessed(int row, int col){
Location l = grid[row][col];
return l.getStatus() == 1 || l.getStatus() == 2;
}

// Set whether or not there is a ship at this location to the val   
public void setShip(int row, int col, boolean val){
grid[row][col].setShip(val);
}

// Return whether or not there is a ship here   
public boolean hasShip(int row, int col){
return grid[row][col].hasShip();
}


// Get the Location object at this row and column position
public Location get(int row, int col){
Location l = grid[row][col];
return l;
}

// Return the number of rows in the Grid
public int numRows(){
return NUM_ROWS;
}

// Return the number of columns in the grid
public int numCols(){
return NUM_COLS;
}


// Print the Grid status including a header at the top
// that shows the columns 1-10 as well as letters across
// the side for A-J
// If there is no guess print a -
// If it was a miss print a O
// If it was a hit, print an X
// A sample print out would look something like this:
//
// 1 2 3 4 5 6 7 8 9 10
// A - - - - - - - - - -
// B - - - - - - - - - -
// C - - - O - - - - - -
// D - O - - - - - - - -
// E - X - - - - - - - -
// F - X - - - - - - - -
// G - X - - - - - - - -
// H - O - - - - - - - -
// I - - - - - - - - - -
// J - - - - - - - - - -
public void printStatus(){
System.out.println(" 1 2 3 4 5 6 7 8 9 10");
int letter = 65;
for(int row = 0; row < NUM_ROWS; row++){
System.out.print((char)letter++ + " ");
for(int col = 0; col < NUM_COLS; col++){
int currentStatus = getStatus(row, col);
if(currentStatus == 0){
System.out.print("- ");
}
else if(currentStatus == 1){
System.out.print("X ");
}
else{
System.out.print("O ");
}
}
System.out.println();
}
}

// Print the grid and whether there is a ship at each location.
// If there is no ship, you will print a - and if there is a
// ship you will print a X. You can find out if there was a ship
// by calling the hasShip method.
//
// 1 2 3 4 5 6 7 8 9 10
// A - - - - - - - - - -
// B - X - - - - - - - -
// C - X - - - - - - - -
// D - - - - - - - - - -
// E X X X - - - - - - -
// F - - - - - - - - - -
// G - - - - - - - - - -
// H - - - X X X X - X -
// I - - - - - - - - X -
// J - - - - - - - - X -
public void printShips(){
System.out.println(" 1 2 3 4 5 6 7 8 9 10");
int letter = 65;
for(int row = 0; row < NUM_ROWS; row++){
System.out.print((char)letter++ + " ");
for(int col = 0; col < NUM_COLS; col++){
boolean ship = hasShip(row, col);
if(ship){
System.out.print("X ");
}
else{
System.out.print("- ");
}
}
System.out.println();
}
}
  
}

randomizer.java

import java.util.*;

public class Randomizer{

   public static Random theInstance = null;
  
   public Randomizer(){
      
   }
  
   public static Random getInstance(){
       if(theInstance == null){
           theInstance = new Random();
       }
       return theInstance;
   }
  
   /**
   * Return a random boolean value.
   * @return True or false value simulating a coin flip.
   */
   public static boolean nextBoolean(){
       return Randomizer.getInstance().nextBoolean();
   }

   /**
   * This method simulates a weighted coin flip which will return
   * true with the probability passed as a parameter.
   *
   * @param   probability   The probability that the method returns true, a value between 0 to 1 inclusive.
   * @return True or false value simulating a weighted coin flip.
   */
   public static boolean nextBoolean(double probability){
       return Randomizer.nextDouble() < probability;
   }
  
   /**
   * This method returns a random integer.
   * @return A random integer.
   */
   public static int nextInt(){
       return Randomizer.getInstance().nextInt();
   }

   /**
   * This method returns a random integer between 0 and n, exclusive.
   * @param n   The maximum value for the range.
   * @return A random integer between 0 and n, exclusive.
   */
   public static int nextInt(int n){
       return Randomizer.getInstance().nextInt(n);
   }

   /**
   * Return a number between min and max, inclusive.
   * @param min   The minimum integer value of the range, inclusive.
   * @param max   The maximum integer value in the range, inclusive.
   * @return A random integer between min and max.
   */
   public static int nextInt(int min, int max){
       return min + Randomizer.nextInt(max - min + 1);
   }

   /**
   * Return a random double between 0 and 1.
   * @return A random double between 0 and 1.
   */
   public static double nextDouble(){
       return Randomizer.getInstance().nextDouble();
   }

   /**
   * Return a random double between min and max.
   * @param min The minimum double value in the range.
   * @param max The maximum double value in the rang.
   * @return A random double between min and max.
   */
   public static double nextDouble(double min, double max){
       return min + (max - min) * Randomizer.nextDouble();
   }

  
}

Code Screenshots for Battleship class

main.java

Add a comment
Know the answer?
Add Answer to:
CodeHS Java: Battleship part 6: The Battleship Class *please look up the entire battleship module on...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Make sure to include: Ship.java, ShipTester.java, Location.java, LocationTester.java, Grid.java, GridTester.java, Player.java, PlayerTester.java, battleship.java. please do every...

    Make sure to include: Ship.java, ShipTester.java, Location.java, LocationTester.java, Grid.java, GridTester.java, Player.java, PlayerTester.java, battleship.java. please do every part, and include java doc and comments Create a battleship program. Include Javadoc and comments. Grade 12 level coding style using java only. You will need to create a Ship class, Location class, Grid Class, Add a ship to the Grid, Create the Player class, the Battleship class, Add at least one extension. Make sure to include the testers. Starting code/ sample/methods will be...

  • For your Project, you will develop a simple battleship game. Battleship is a guessing game for...

    For your Project, you will develop a simple battleship game. Battleship is a guessing game for two players. It is played on four grids. Two grids (one for each player) are used to mark each players' fleets of ships (including battleships). The locations of the fleet (these first two grids) are concealed from the other player so that they do not know the locations of the opponent’s ships. Players alternate turns by ‘firing torpedoes’ at the other player's ships. The...

  • (C++) Please create a tic tac toe game. Must write a Player class to store each...

    (C++) Please create a tic tac toe game. Must write a Player class to store each players’ information (name and score) and to update their information (increase their score if appropriate) and to retrieve their information (name and score).The players must be called by name during the game. The turns alternate starting with player 1 in the first move of round 1. Whoever plays last in a round will play second in the next round (assuming there is one).The rows...

  • C#: Implement a multiplayer Battleship game with AI The rules are the same as before. The...

    C#: Implement a multiplayer Battleship game with AI The rules are the same as before. The game is played on an NxN grid. Each player will place a specified collection of ships: The ships will vary in length (size) from 2 to 5; There can be any number or any size ship. There may be no ships of a particular size; EXCEPT the battleship – which there will always be 1 and only 1. Player order will be random but...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT