Question

Assignment - Battleship In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next...

Assignment - Battleship

In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next two assignments you will be creating a one-player version of the game.

The game is extremely simple. Each player arranges a fleet of ships in a grid. The grid is hidden from the opponent. Here is an ASCII representation of a 10x10 grid. The ‘X’s represent ships, the ‘~’s represent empty water. There are three ships in the picture:

A vertical ship with a length of 3, at point (2, 1)

A vertical ship with a length of 2, at point (3,5)

A horizontal ship with a length of 4, at point (5,3)

9 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

8 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

7 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

6 ~ ~ ~ O ~ ~ ~ ~ ~ ~

5 ~ ~ ~ O ~ ~ ~ ~ ~ ~

4 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

3 ~ ~ O ~ ~ O O O O ~

2 ~ ~ O ~ ~ ~ ~ ~ ~ ~

1 ~ ~ O ~ ~ ~ ~ ~ ~ ~

0 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

0 1 2 3 4 5 6 7 8 9

To play the game, the players then take turns guessing where their opponent's ships are located. On each thrun they guess one coordinate point. This is referred to as an imaginary “shot” at this location. The opponent tells them whether the shot is a hit or a miss. The first player to hit every point that is covered by an opponent’s ship wins.

If you are not familiar with the game, you should start out by reading the Wikipedia article, and spending some time playing a fancy version of the game at Pogo.com. See the links below

Wikipedia’s Batleship Article

Pogo.com’s Gabbleship Game

The One Player Game

In this assignment you will be writing a one player version of the Battleship game in which the computer randomly places five ships, and the user tries to sink the ships.

In the sample run of the program below, the grid is first displayed as empty. All of the ships are hidden. The player enters coordinates by entering two integer values separated by a space. Hits are shown on the map with an ‘X’. Misses are shown with a ‘.’. The ‘.’ character represents a small splash. Feel free to replace this, it is the best that I could think of.

Welcome to Battleship.

9 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

8 ~ ~ ~ ~ ~ ~ ~ ~ ~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with length 2!” Where the 2 is replaced by the length of the ship that was sunk. When all five ships are sunk, the game should end.

Object Oriented Design

Your game does not need a two dimensional grid. Instead if can use ArrayList objects full of Point objects. The Point class can be a simple class that keeps track of x and y coordinates.

You can use two classes to keep track of the game data. a Ship class that stores the data for each ship. Your program will have five of these. And a Board class that stores the data the game in general. It will have an array of Ship objects, and an ArrayList of points that represent the players guesses.

Ship Class: Your game should store ships in objects of type Ship. This ship class should keep two ArrayLists of points: one to store the points that the ship covers, and one to store the points that have been “hit” by the player.

The Ship class has the following constructors and methods.

Ship(Point origin, boolean isVertical, int length) - this constructor accepts the origin or the ship (its lowest, or leftmost point), its length, and its orientation (vertical, or horizontal).

boolean containsPoint(Point p) const - Returns true if a Ship covers a point on the board, false if it does not.

boolean collidesWith(Ship s) const - Returns true if the receiving ship shares a point with the argument ship. Collides with it, so to speak.

void shotFiredAtPoint(Point p) - This is a verb in the game. When the user enters a coordinate, this method can be called on each ship. If the ship contains the point, it should remember that it has been hit at that point. It could do this with a second PointCollection, or some other data strategy.

bool isHitAtPoint(Point p) - returns true if shotFiredAtPoint has been called for this point in the ship. False if it has not, or if the point is not in the ship.

int hitCount() - returns the number of points in the ship that have been hit. When the hitCount is equal to the length of the ship the ship is considered to be sunk.

Board Class: The board class has not been designed for you. Designing this class is one of the key challenges in the assignment. When you design this class think about the code that you will need for the basic game loop. It will read in a coordinate from the player, say if it is a hit or a miss, then display the board.

The Board class should not contain this game loop. It is a data object. It is similar to the ConwayWorld object in this sense. But if the Board class is well designed, then it should be extremely easy to write the rest of the game. We can discuss possible approaches in the forum.

What to submit

Submit all of the code for your game. It should include Point.java, Ship.java, Board.java, and at least one other file that stores the game code.

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

Battleship.java

import java.util.Scanner;

public class Battleship {
   public static void main(String[] args)
   {
       boolean gameRunning = true;
      
       Ship submarine = new Ship(new Point(1,1), false, 3);
       Ship destroyer = new Ship(new Point(5,5), false, 4);
       Ship carrier = new Ship(new Point(10,1), true, 5);
       Ship patrol = new Ship(new Point(2,6),true,2);
       Ship battleship = new Ship(new Point(3,7),false,4);
          
       Board newBoard = new Board();      
      
       newBoard.display();
      
       newBoard.addShip(submarine);
       newBoard.addShip(destroyer);
       newBoard.addShip(carrier);
       newBoard.addShip(patrol);
       newBoard.addShip(battleship);
      
       while (gameRunning)
       {
           Scanner keyboard = new Scanner(System.in);
          
           System.out.println("\nEnter two coordinates separated by a space: ");
           String inputX = keyboard.next();
           String inputY = keyboard.next();
          
           int xValue = Integer.parseInt(inputX);
           int yValue = Integer.parseInt(inputY);
      
           Point shot = new Point (xValue, yValue);
          
           if (submarine.shotFiredAtPoint(shot) ||
               destroyer.shotFiredAtPoint(shot) ||
               carrier.shotFiredAtPoint(shot) ||
               patrol.shotFiredAtPoint(shot) ||
               battleship.shotFiredAtPoint(shot)) // YOU HIT
           {
               System.out.println("Hit!");
               if (submarine.sunk)
                   System.out.println("You sunk the submarine!");
               else if (destroyer.sunk)
                   System.out.println("You sunk the destroyer!");
               else if (carrier.sunk)
                   System.out.println("You sunk the carrier!");
               else if (patrol.sunk)
                   System.out.println("You sunk the patrol!");
               else if (battleship.sunk)
                   System.out.println("You sunk the battleship!");
              
               newBoard.hitBoard.add(shot);
               newBoard.shipBoard.add(shot);
               newBoard.display();
              
               System.out.print("HITS = ");
               for (int i = 0; i < newBoard.hitBoard.size(); i++)
               {
                   System.out.print(" [" + newBoard.hitBoard.get(i).getX() + " " + newBoard.hitBoard.get(i).getY() + "] ");
               }
                  
           }
           else // YOU MISSED
           {
               System.out.println("Miss! Try again...");
               newBoard.missBoard.add(shot);
               newBoard.display();
               System.out.print("MISSES = ");

               for (int i = 0; i < newBoard.missBoard.size(); i++)
               {
                   System.out.print(" [" + newBoard.missBoard.get(i).getX() + " " + newBoard.missBoard.get(i).getY() + "] ");
               }
           }
       }
   }

}

Ship.java

import java.util.ArrayList;

public class Ship {
   boolean isVertical;
   int size;
   Point origin;
   int hits;
   boolean sunk = false;
  
   ArrayList<Point> ship = new ArrayList<Point>();

//   this constructor accepts the origin or the ship (its lowest, or leftmost point),
//   its length, and its orientation (vertical, or horizontal).
   Ship(Point myOrigin, boolean vertical, int length)
   {
       origin = new Point(myOrigin.getX(), myOrigin.getY());
       isVertical = vertical;
       size = length;
      
       if (isVertical)
       {
           for (int index = 0; index < size; index++)
           {
               ship.add(new Point(origin.getX(), origin.getY() + index));      
           }
       }
       else
       {
           for (int index = 0; index < size; index++)
           {
               ship.add(new Point(origin.getX() + index, origin.getY()));      
           }
       }
   }

   //   Returns true if a Ship covers a point on the board, false if it does not.
   boolean containsPoint(Point p)
   {
//       for (int index = 0; index)
//       return this.origin.getX() == p.getX() && this.origin.getY() == p.getX();
       return true;
   }
  
//   Returns true if the receiving ship shares a point with the argument ship. Collides with it, so to speak.
   public boolean collidesWith(Ship s)
   {
       return true;
   }
  
//   This is a verb in the game. When the user enters a coordinate, this method can be called on each ship.
//   If the ship contains the point, it should remember that it has been hit at that point. It could
//   do this with a second PointCollection, or some other data strategy
   public boolean shotFiredAtPoint(Point p)
   {
       boolean wasHit = false;
      
       for(int i = 0; i < size; i++)
       {
           if (ship.get(i).equals(p))
           {
               hits++;
               wasHit = true;
           }
       }
       if (hits == size)
           sunk = true;
      
       return wasHit;
   }
  
//   Returns true if shotFiredAtPoint has been called for this point in the ship.
//   False if it has not, or if the point is not in the ship.
   public boolean isHitAtPoint(Point p)
   {
       return false;
   }
  
//   Returns the number of points in the ship that have been hit.
//   When the hitCount is equal to the length of the ship the ship is considered to be sunk.
   public int hitCount()
   {
       return hits;
   }
}


Point.java


public class Point {
   private int x;
   private int y;
  
   public Point(int xValue, int yValue)
   {
       x = xValue;
       y = yValue;
   }
  
   public void setX(int value) { x = value; }
   public int getX() { return x; }
  
   public void setY(int value) { y = value; }
   public int getY() { return y; }

   public boolean equals(Point p)
   {
       return x == p.getX() && y == p.getY();
   }
}

Board.java

import java.util.ArrayList;

public class Board {
   static final int ROWS = 10;
   static final int COLS = 10;
   ArrayList<Point> boardSpaces = new ArrayList<Point>(); // contains all the points on the board
   ArrayList<Point> shipBoard = new ArrayList<Point>(); // contains the points of all the ships
   ArrayList<Point> hitBoard = new ArrayList<Point>(); // contains all the point called that were hits
   ArrayList<Point> missBoard = new ArrayList<Point>(); // contains all the points called that were misses
  
   public Board() // Constructor
   {
       for(int r = 0; r < 10; r++)
       {
           for(int c = 0; c < 10; c++)
               {boardSpaces.add(new Point(r, c));}
       }
   }
  
   public void addShip(Ship o)
   {
       if (o.isVertical)
       {
           for (int index = 0; index < o.size; index++)
           {
               shipBoard.add(new Point(o.origin.getX(), o.origin.getY() + index));      
           }
       }
       else
       {
           for (int index = 0; index < o.size; index++)
           {
               shipBoard.add(new Point(o.origin.getX() + index, o.origin.getY()));      
           }
       }
          
   }

   public void display()
   {  
       int i = 0;
       for (int r = 9; r >= 0; r--)  
       {
          
           System.out.print(r);
          
           for (int c = 0; c < 10; c++)
           {
               System.out.print("[" + boardSpaces.get(i).getX() + "]" + "[" + boardSpaces.get(i).getY() + "],");
               i++;
           }
           System.out.println();
          
       }
       for (int r = 0; r <= 9; r++)
           System.out.print(" " + r + " ");
       System.out.println("");
  
   }
}


Problems Javadoc e, Declaration Console 3 Battleship [Java Application] C:Program Files Javaljre7bin javaw.exe (Dec 22, 2016,

Add a comment
Know the answer?
Add Answer to:
Assignment - Battleship In 1967, Hasbro toys introduced a childrens game named “Battleship”. In the next...
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
  • 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...

  • Imagine we are using a two-dimensional array as the basis for creating the game battleship. In...

    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...

  • In C++ program use the new style od C++ not the old one. Simple Battleship You...

    In C++ program use the new style od C++ not the old one. Simple Battleship You will make a game similar to the classic board game Battleship. You will set up a 5 x 5, 2 dimensional array. In that array, you will use a random number generator to select 5 elements that will act as the placeholders for your "battleships". Your user will get 10 guesses to "seek and destroy" the battleships. After their 10 guesses, you will tell...

  • 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...

  • Program in C computer language In this program you will be mimicking a game of Battleship....

    Program in C computer language In this program you will be mimicking a game of Battleship. Your game board is a line of 10 slots. You have to implement 3 methods. The following methods must be implemented: void setBoard(int *) This method sets up the human’s game board. The method prompts the user for 2 slots to place the “ship”. The program should ensure that the slots are consecutive. In other words, your ship cannot be placed at slot 2...

  • The game Battleship is played on a grid board. Each opponent has multiple ships that are...

    The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six...

  • The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the o...

    The game Battleship is played on a grid board. Each opponent has multiple ships that are placed on the grid where the other opponent cannot see them. In order to attack, each player takes turns calling out coordinates on a grid. If the attacker calls out a coordinate that hits their opponent's ship, they must call out, "Hit." You are going to be developing a computer program to mimic this game. Use the Gridlayout that is six columns by six...

  • Assignment overview In this assignment, you will implement a simple game of Battleship. If you are...

    Assignment overview In this assignment, you will implement a simple game of Battleship. If you are unfamiliar with the game Battleship, there are tutorials online describing the game. In short, there are two players that each have a 10 by 10 grid where ships are placed. The players take turns taking shots at each other’s ships. A player wins when they have shot at all spaces on their opponent’s grid that are occupied by ship. To sink a ship, you...

  • 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...

  • Programming Language : JAVA Write a class named Ship. Its purpose is to model a ship...

    Programming Language : JAVA Write a class named Ship. Its purpose is to model a ship in the BattleShip game and its placement on the Battleship board. Ships exist on a 10 x 10 battleship board with ten rows labeled A through J and columns labeled 1 through 9 and the final column labeled 0 to indicate the tenth column. We will refer to the Ship placed on the board at the origin which the pair (r,c) where in the...

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