Question

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 must attack every cell that the ship occupies. In this assignment, we will create Battleship that any number of players (>= 2) can play, with any sized two dimensional grids. Do to this, you will implement the following the classes:

  • • Gameboard:
  • • Tile
  • • Game

Keep all of your methods short and simple. In a properly-written object-oriented program, the work is distributed among many small methods, which call each other. Most of the methods you write in this program should be less than 10 lines of code.

Unless specified otherwise, all instance variables must be private, and all methods listed should be public. You may write any private helper methods you deem appropriate to solve the problems. You should not need any more accessor or mutator methods than are listed.

Testing Your Coding

We have provided sample test files for each phase to help you see if code is working according to the assignment specifications. These files are starting points for testing your code. Part of developing your skills as a programmer is to think through additional important test cases and to write your own code to test these cases.

Phase 1: Gameboard and Tiles

First, implement two simple classes: a Tile class and a Gameboard class.

The Tile class is a representation of a single space on the board. The Tile class should have:

  • • Three instance variables: wasAttacked, hasShip, and displayLetter. Instance variable wasAttacked stores whether or not an attack was made on this Tile. Instance variable hasShip stores true if there is a ship placed on this Tile. Finally, displayLetter is the char potentially shown by the Tile. The way the tiles are displayed is described below.
  • • Constructor Tile() that sets displayLetter to the character ~, which represents a wave. Note that the constructor takes no parameters.
  • • Method setDisplayLetter(char letter). This is a mutator/setter method for displayLetter.

ASSIGNMENT 2: Multi-dimensional arrays COMP 1020 Winter 2019

Page 2 of 7

  • • A getDisplay(boolean isOpponent) instance method. The method returns the character, as a String, to display when showing this tile to the user. o If this gameboard is the player’s (that is, isOpponent == false) ▪ Show the character saved in displayLetter if it has not been attacked, and has a ship.
  • ▪ Show a wave (~) if this tile has not been attacked, and does not have a ship.
  • ▪ Show a splash (^) if this tile does not have a ship, and has been attacked.
  • ▪ Show an explosion (*) if this tile has been attacked, and does have a ship.
  • o If this gameboard belongs to the opponent. We do not show the ship locations for opponent boards. ▪ Show a wave (~) if this tile has not been attacked.
  • ▪ Show a splash (^) if this tile does not have a ship, and has been attacked.
  • ▪ Show an explosion (*) if this tile has been attacked, and does have a ship.
  • • Method attack() which sets wasAttacked to true.
  • • Method canPlaceShip(), that returns a boolean. The method returns true if a ship could be placed on this Tile. A ship can be placed if this tile has not been attacked, and does not have a ship placed on it already.
  • • Method activeShip(), that returns true if there is a ship on this tile, and it has not been attacked.

The Gameboard class is a two-dimensional array of Tile objects, creating a game board for a single player. Complete the following:

  • • Gameboard has two instance variables. A two-dimensional array of Tile objects for the gameboard, and a boolean ‘isOpponent’ that stores whether or not this is a player board, or an opponent board.
  • • A Constructor that accepts three values: int row – the number of rows, int column – the number of columns, and boolean isOpponent – true if this board is owned by your opponent.
  • • A toString() method which returns a string representation of the entire gameboard. If this is an opponent’s board, then the ship locations should not be shown.
  • • Method getRow(int rowNum), which fetches row rowNum from the board, returning it as a String. The returned String should not have a newline character in it. Use class Tile’s getDisplay method to fetch the values from the Tiles, not showing the opponent ship locations to the user. This method is used to extract a single row from the gameboard for displaying to the user.
  • • Method doAttack(int row, int column). This method sets the isAttacked flag on the tile at index row, column.

Sample output from A2TestPhase1.java:

Should be a wave ~: ~

Should be a splash ^: ^

Should be a splash ^: ^

Should be a C: C

Should be a ~: ~

Should be an explosion *: *

Print a 2x2 board of waves ~:

~~

~~

Should have a splash ^ on second row, second column

~~

~^

Should be ^~ : ^~

Should be ~^ : ~^

Print splashes down the x=y axis of a 3x3 board:

^~~

~^~

~~^


public class A2TestPhase1 {

   public static void main(String[] args) {
      
       Tile emptyTile = new Tile();
      
       System.out.println("Should be a wave ~: " + emptyTile.getDisplay(false));
       emptyTile.attack();
       System.out.println("Should be a splash ^: " + emptyTile.getDisplay(false));
       System.out.println("Should be a splash ^: " + emptyTile.getDisplay(true));
      
       Tile tileWithShip = new Tile();
       tileWithShip.setDisplayLetter('C');
       System.out.println("Should be a C: " + tileWithShip.getDisplay(false));
       tileWithShip.setDisplayLetter('~');
       System.out.println("Should be a ~: " + tileWithShip.getDisplay(true));
       tileWithShip.attack();
       System.out.println("Should be an explosion *: " + tileWithShip.getDisplay(false));
      
       Gameboard myBoard = new Gameboard(2, 2, false);
      
       System.out.println("Print a 2x2 board of waves ~:");
       System.out.println(myBoard);
      
       myBoard.doAttack(1, 1);
      
       System.out.println("Should have a splash ^ on second row, second column");
       System.out.println(myBoard);
      
       myBoard.doAttack(0, 0);
      
       System.out.println("Should be ^~ : " + myBoard.getRow(0) );
       System.out.println("Should be ~^ : " + myBoard.getRow(1) );
      
       Gameboard theirBoard = new Gameboard(3, 3, true);
       theirBoard.doAttack(0, 0);
       theirBoard.doAttack(1, 1);
       theirBoard.doAttack(2, 2);
       System.out.println("Print splashes down the x=y axis of a 3x3 board:");
       System.out.println(theirBoard);
   }

}

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

A2TestPhase1.java


public class A2TestPhase1 {

   public static void main(String[] args) {
      
       Tile emptyTile = new Tile();
      
       System.out.println("Should be a wave ~: " + emptyTile.getDisplay(false));
       emptyTile.attack();
       System.out.println("Should be a splash ^: " + emptyTile.getDisplay(false));
       System.out.println("Should be a splash ^: " + emptyTile.getDisplay(true));
      
       Tile tileWithShip = new Tile();
       tileWithShip.setDisplayLetter('C');
       System.out.println("Should be a C: " + tileWithShip.getDisplay(false));
       tileWithShip.setDisplayLetter('~');
       System.out.println("Should be a ~: " + tileWithShip.getDisplay(true));
       tileWithShip.attack();
       System.out.println("Should be an explosion *: " + tileWithShip.getDisplay(false));
      
       Gameboard myBoard = new Gameboard(2, 2, false);
      
       System.out.println("Print a 2x2 board of waves ~:");
       System.out.println(myBoard);
      
       myBoard.doAttack(1, 1);
      
       System.out.println("Should have a splash ^ on second row, second column");
       System.out.println(myBoard);
      
       myBoard.doAttack(0, 0);
      
       System.out.println("Should be ^~ : " + myBoard.getRow(0) );
       System.out.println("Should be ~^ : " + myBoard.getRow(1) );
      
       Gameboard theirBoard = new Gameboard(3, 3, true);
       theirBoard.doAttack(0, 0);
       theirBoard.doAttack(1, 1);
       theirBoard.doAttack(2, 2);
       System.out.println("Print splashes down the x=y axis of a 3x3 board:");
       System.out.println(theirBoard);
   }

}

Gameboard.java

// Gameboard class. contain a two-dimensional array of Tile objects, creating a game board for a single player
public class Gameboard
{
   // instance variables
   Tile[][] gameboard;
   boolean isOpponent;

   public static final int UP = 1;
   public static final int DOWN = -1;
   public static final int LEFT = 2;
   public static final int RIGHT = -2;

   // Constructor
   public Gameboard(int row, int column, boolean isOpponent)
   {
       gameboard = new Tile[row][column];

       for (int i = 0; i < row; i++)
       {
           for (int j = 0; j < column; j++)
           {
               gameboard[i][j] = new Tile();
           }
       }

       this.isOpponent = isOpponent;
   }

   // returns a string representation of the entire gameboard
   public String toString()
   {
       String gameBoardString = "";

       for (int i = 0; i < gameboard.length; i++)
       {
           for (int j = 0; j < gameboard[i].length; j++)
           {
               gameBoardString += gameboard[i][j].getDisplay(isOpponent);
           }
           gameBoardString += "\n";
       }

       return gameBoardString;
   }

   // fetches row rowNum from the board, returning it as a String
   public String getRow(int rowNum)
   {
       String rowString = "";

       for (int j = 0; j < gameboard[rowNum].length; j++)
       {
           rowString += gameboard[rowNum][j].getDisplay(isOpponent);
       }

       return rowString;
   }

   // sets the isAttacked flag on the tile at index row, column
   public void doAttack(int row, int column)
   {
       if(row >= 0 && row < gameboard.length &&
               column >= 0 && column < gameboard[row].length)
       {
           gameboard[row][column].attack();
       }
   }

   // returns a Tile array containing the contents of the specified row
   public Tile[] extractRow(int row)
   {
       Tile[] tileArray = new Tile[gameboard[row].length];

       for (int j = 0; j < gameboard[row].length; j++)
       {
           tileArray[j] = gameboard[row][j];
       }

       return tileArray;
   }

   // returns a Tile array containing the contents of the specified column
   public Tile[] extractColumn(int column)
   {
       Tile[] tileArray = new Tile[gameboard.length];

       for (int j = 0; j < gameboard.length; j++)
       {
           tileArray[j] = gameboard[j][column];
       }

       return tileArray;
   }

   // reverse the provided array
   public static void reverse(Tile[] data)
   {
       Tile temp = null;

       for (int i = 0; i < data.length / 2; i++)
       {
           temp = data[i];
           data[i] = data[data.length - i - 1];
           data[data.length - i - 1] = temp;
       }
   }

   // adding ships to the board
   public boolean addShip(int row, int col, int length, int direction, char display)
   {
       boolean canAddShip = true;
       int start = 0;
       Tile[] tiles = null;

       // check the direction
       if (direction == UP)
       {
           start = gameboard.length - 1 - row;
           tiles = extractColumn(col);
           reverse(tiles);
       }
       else if (direction == DOWN)
       {
           start = row;
           tiles = extractColumn(col);
       }
       else if (direction == RIGHT)
       {
           start = col;
           tiles = extractRow(row);
       }
       else if (direction == LEFT)
       {
           start = gameboard.length - 1 - col;
           tiles = extractRow(row);
           reverse(tiles);
       }

       // check if it can place a ship
       canAddShip = canPlaceShipInArray(tiles, start, length);

       // place the ship
       if(canAddShip)
       {
           placeShipInArray(tiles, start, length, display);
       }
      
       return canAddShip;
   }
  
   // adds a ship into this array
   private static void placeShipInArray(Tile [] tiles, int start, int length, char letter)
   {
       for (int i = start; i < (start + length); i++)
       {
           tiles[i].setDisplayLetter(letter);
       }
   }
  
   // checks to see if a ship could be placed in this array
   private static boolean canPlaceShipInArray(Tile[] tiles, int start, int length)
   {
       boolean canAddShip = true;      
      
       if ((start + length) > tiles.length)
       {
           canAddShip = false;
       }      
       else
       {
           for (int i = start; i < length; i++)
           {
               if (!tiles[i].canPlaceShip())
               {
                   canAddShip = false;
               }
           }
       }
       return canAddShip;
   }
  
   // returns true if the player has lost
   public boolean hasLost()
   {
       boolean lost = true;
      
       for (int i = 0; i < gameboard.length; i++)
       {
           for (int j = 0; j < gameboard[i].length; j++)
           {
               if(gameboard[i][j].activeShip())
               {
                   lost = false;
               }
           }
       }
      
       return lost;
   }
}


Tile.java

// Tile class, single space on the board
public class Tile
{
   // instance variables
   boolean wasAttacked;
   boolean hasShip;
   char displayLetter;

   // Constructor
   public Tile()
   {
       wasAttacked = false;
       hasShip = false;
       displayLetter = '~';
   }

   // setter method for displayLetter
   public void setDisplayLetter(char letter)
   {
       displayLetter = letter;
       hasShip = true;
   }

   // returns the character, as a String, to display when showing this tile to the user
   public String getDisplay(boolean isOpponent)
   {
       String displayChar = "";

       if (!isOpponent)
       {
           if (!wasAttacked && hasShip)            // Show the character saved in displayLetter if it has not been attacked, and has a ship
           {
               displayChar = displayLetter + "";
           }
           else if (!wasAttacked && !hasShip)       // Show a wave (~) if this tile has not been attacked, and does not have a ship
           {
               displayChar = "~";
           }
           else if (wasAttacked && !hasShip)       // Show a splash (^) if this tile does not have a ship, and has been attacked
           {
               displayChar = "^";
           }
           else if (wasAttacked && hasShip)       // Show an explosion (*) if this tile has been attacked, and does have a ship
           {
               displayChar = "*";
           }
       }
       else
       {
           if (!wasAttacked)                       // Show a wave (~) if this tile has not been attacked
           {
               displayChar = "~";
           }
           else if (wasAttacked && !hasShip)       // Show a splash (^) if this tile does not have a ship, and has been attacked
           {
               displayChar = "^";
           }
           else if (wasAttacked && hasShip)       // Show an explosion (*) if this tile has been attacked, and does have a ship
           {
               displayChar = "*";
           }
       }

       return displayChar;
   }

   // sets wasAttacked to true
   public void attack()
   {
       wasAttacked = true;
   }

   // returns true if a ship could be placed on this Tile
   public boolean canPlaceShip()
   {
       boolean canPlaceShip = false;

       if (!wasAttacked && !hasShip)
       {
           canPlaceShip = true;
       }

       return canPlaceShip;
   }

   // returns true if there is a ship on this tile, and it has not been attacked
   public boolean activeShip()
   {
       boolean activeShip = false;

       if (hasShip && !wasAttacked)
       {
           activeShip = true;
       }

       return activeShip;
   }  
}


Add a comment
Know the answer?
Add Answer to:
Assignment overview In this assignment, you will implement a simple game of Battleship. If you are...
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
  • 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...

  • Code in JAVA You are asked to implement “Connect 4” which is a two player game....

    Code in JAVA You are asked to implement “Connect 4” which is a two player game. The game will be demonstrated in class. The game is played on a 6x7 grid, and is similar to tic-tac-toe, except that instead of getting three in a row, you must get four in a row. To take your turn, you choose a column, and slide a checker of your color into the column that you choose. The checker drops into the slot, falling...

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

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

  • 1 Overview For this assignment you are required to write a Java program that plays (n,...

    1 Overview For this assignment you are required to write a Java program that plays (n, k)-tic-tac-toe; (n, k)-tic- tac-toe is played on a board of size n x n and to win the game a player needs to put k symbols on adjacent positions of the same row, column, or diagonal. The program will play against a human opponent. You will be given code for displaying the gameboard on the screen. 2 The Algorithm for Playing (n, k)-Tic-Tac-Toe The...

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

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

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

  • Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game....

    Tic Tac Toe Game: Help, please. Design and implement a console based Tic Tac Toe game. The objective of this project is to demonstrate your understanding of various programming concepts including Object Oriented Programming (OOP) and design. Tic Tac Toe is a two player game. In your implementation one opponent will be a human player and the other a computer player. ? The game is played on a 3 x 3 game board. ? The first player is known as...

  • 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