Question

In: Computer Science

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 (i.e., not a ship), a '#' character represents a place in 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 been sunk. Declare a two-dimensional array that is 25 × 25 that represents the entire ocean and an If statement that prints "HIT" if a torpedo hits a ship given the coordinates X and Y. Write a C++ program that will read in a file representing a game board with 25 lines where each line has 25 characters corresponding to the description above. An example file might look like:

~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ # # # # # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ # ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ # ~ ~ ~ ~ ~ ~ ~ ~ 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 ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~

You should write a function called Fire that will take an X and Y coordinate and print "HIT" if a ship is hit and "MISS" if a ship is missed. If a ship is HIT you should update the array with an 'H' character to indicate the ship was hit. If a ship is hit that has already been hit at that location you should print "HIT AGAIN". You should write a second function called FleetSunk that will determine if all the ships have been sunk. Your C++ program must then call these functions until all the ships have been sunk, at which point the program should display "The fleet was destroyed!". B. Write a program to play a game in which you try to sink a fleet of five navy vessels by guessing their locations on a grid. The program uses random numbers to position its ships on a 15 × 15 grid. The ships are of different lengths as follows: Frigate: 2 locations Tender: 2 locations Destroyer: 3 locations Cruiser: 3 locations Carrier: 4 locations The program must pick one square as the starting location, then pick the direction of the ship on the board, and mark off the number of squares in that direction to represent the size of the ship. It must not allow a ship to overlap with another ship or to run off the board. The user enters coordinates in the range of 1 through 15 for the rows and A through O for the columns. The program checks this location, and reports whether it is a hit or a miss. If it is a hit, the program also checks whether the ship has been hit in every location that it occupies. If so, the ship is reported as sunk, and the program identifies which ship it is. The user gets 60 shots to attempt to sink the fleet. If the user sinks all of the ships before using all 60 shots, then he or she wins the game. At the end of the game, the program should output the grid, so that the user can see where the ships are located.

Solutions

Expert Solution

A)

Code:-

#include<cstdlib>
#include<iostream>
#include<cmath>
#include<string>
#include<iomanip>
#include<fstream>
using namespace std;
ifstream myinfile;
const int gameBoardWidth = 25;
const int gameBoardHeight = 25;
void Fire(const int gameBoardWidth, const int gameBoardHeight, int X, int Y, char gameBoard[][25]);
void FleetSunk(const int gameBoardWidth, const int gameBoardHeight, int X, int Y, char gameBoard[][25], bool &GameOver);
int main()
{
cout << "Titus Dyck -- Lab 9 (BattleShip)" << endl << endl;
myinfile.open("Board.txt"); // Enter your own game board file name here
// variables
char gameBoard[gameBoardWidth][gameBoardHeight];
int X;
int Y;
bool GameOver;
for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 25; j++)
myinfile >> gameBoard[i][j];
}
for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 25; j++)
myinfile >> gameBoard[i][j];
}
GameOver = false;
while (!GameOver)
{
cout << endl << "Please enter a X cordinate from 0 to 24 for your Attack" << endl << endl;
cin >> X;
cout << endl;
cout << "Please enter a Y cordinate from 0 to 24 for your Attack" << endl << endl;
cin >> Y;
cout << endl;
Fire(gameBoardHeight, gameBoardWidth, X, Y,gameBoard);
FleetSunk(gameBoardHeight, gameBoardWidth, X, Y,gameBoard, GameOver);
}
//closing program statements
myinfile.close();
system("pause");
return 0;
}
// function declarations
void Fire(const int gameBoardWidth, const int gameBoardHeight, int X, int Y, char gameBoard[][25])
{
if (gameBoard[X][Y] == '#')
{
cout << "HIT" << endl;
gameBoard[X][Y] = 'H';
}
else if (gameBoard[X][Y] == 'H')
{
cout << "HIT AGAIN" << endl;
}
else
{
cout << "MISS" << endl;
}
}
void FleetSunk(const int gameBoardWidth, const int gameBoardHeight, int X, int Y, char gameBoard[][25], bool &GameOver)
{
bool NoPound;
NoPound = false;

for (int i = 0; i < 25; i++)
{
for (int j = 0; j < 25; j++)
if (gameBoard[i][j] == '~' || gameBoard[i][j] == 'H')
NoPound = true;
else
{
NoPound = false;
break;
}
if (NoPound == false)
    break;
}
if (NoPound == true)
{
GameOver = true;
cout << "The Entire Enemey Fleet has been destroyed, well done Admiral!" << endl << endl;
cout << " Game Over" << endl << endl;
}
}

Input File:-

// Board.txt

~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~#####~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~#~~~~~~~~~~
~~~~~~~~~~~~~~#~~~~~~~~~~
~~~~~~~~~~~~~~#~~~~~~~~~~
~~~~~~~~~~~~~~#~~~~~~~~~~
~~~~~~~~~~~~~~#~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~#####~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~######~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~#####~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~#~~~~~
~~~~~~~~~~~~~~~~~~~#~~~~~
~~~~~~~~~~~~~~~~~~~#~~~~~
~~~~~~~~~~~~~~~~~~~#~~~~~
~~~######~~~~~~~~~~#~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~

Output:-

B)

Code:-

#include <cstdlib>
#include<iostream>
using namespace std;
char grid[15][15]; // 15x15 playing grid
int row, col; // rows and columns of the grid
// Put a ship on the map
int putship(char ship, int spots)
{
   int dir; // direction
   int i;
   // Keep trying to find an open spot for the ship
   while (1)
   {
       // get a random row, column, direction
       row = rand() %15;
       col = rand() %15;
       dir = rand() %4;
       if (grid[row][col] != '.')
       continue;
       if (dir == 0)
       {
           // left direction
           // check if putting the ship to the left will go out of bounds
           // if it doesn't work, continue so we can do the while loop
           // again and choose a new position randomly
           if ((col - spots + 1) < 0)
               continue;
           // check if the spots are already taken by another ship
           for (i = 1; i < spots; i++)
           {
               if (grid[row][col - i] != '.')
                   continue;
           }
           // mark the ship into the grid
           for (i = 0; i < spots; i++)
           {
               grid[row][col - i] = ship;
           }
       }
       else if (dir == 1)
       {
           // up
           if ((row - spots + 1) < 0)
           {
               continue;
           }
           for (i = 1; i < spots; i++)
           {
               if (grid[row - i][col] != '.')
               {
                   continue;
               }
           }
           for (i = 0; i < spots; i++)
           {
               grid[row - i][col] = ship;
           }
       }
       else if (dir == 2)
       {
           // right
           if ((col + spots) > 15)
           {
               continue;
           }
           for (i = 1; i < spots; i++)
           {
               if (grid[row][col + i] != '.')
               {
                   continue;
               }
           }
           for (i = 0; i < spots; i++)
           {
               grid[row][col + i] = ship;
           }
       }
       else if (dir == 3)
       {
           // down
           if ((row + spots) > 15)
           {
               continue;
           }
           for (i = 1; i < spots; i++)
           {
               if (grid[row + i][col] != '.')
               {
                   continue;
               }
           }
           for (i = 0; i < spots; i++)
           {
               grid[row + i][col] = ship;
           }
       }
       break;
   }
}
void printGrid()
{
   // print the grid
   cout << " ABCDEFGHIJKLMNO"<<endl;
   for (row = 0; row < 15; row++)
   {
       printf("%2d ", row+1);
       for (col = 0; col < 15; col++)
       {
           cout << grid[row][col];
       }
       cout << endl;
   }
}
int main()
{
   int shots = 60;
   int sunk = 0;
   char map[15][15];
   // Initialize everything to zero
   for (row = 0; row < 15; row++)
   {
       for (col = 0; col < 15; col++)
       {
           grid[row][col] = '.';
       }
   }
   // Add the ships into the grid
   putship('F', 2); // F for Frigate
   putship('T', 2); // T for Tender
   putship('D', 3); // D for Destroyer
   putship('C', 3); // C for Cruiser
   putship('A', 4); // A for Carrier
   // Save a copy of the grid for display
   for (row = 0; row < 15; row++)
   {
       for (col = 0; col < 15; col++)
       {
           map[row][col] = grid[row][col];
       }
   }
   // Have user fire a shot and see if it hit anything
   while (shots-- > 0)
   {
       int r;
       char c;
       int ro, co;
       char type;
       printGrid(); // DEBUG
       cout<<"enter position (for example B3): ";
       cin >> c >> r;
       ro = r-1;
       co = c-'A';
       type = grid[ro][co];
       // check if it hit a ship spot
       if ((type != '.') && (type != 'X'))
       {
           int pos;
           int remains = 0;
           cout << "HIT!\n";
           grid[ro][co] = 'X';
           // Check row and column to see if any part of the ship remains
           for (pos = 0; pos < 15; pos++)
           {
               if ((grid[ro][pos] == type) || (grid[pos][co] == type))
               {
                   remains = 1;
                   break;
               }
           }
           // check if a ship has been completely sunk
           if (remains == 0)
           {
               cout << "You sunk my ";
               if (type == 'F') {
                   cout << "frigate!\n";
               }
               else if (type == 'T')
               {
                   cout << "tender!\n";
               }
               else if (type == 'D')
               {
                   cout << "destroyer!\n";
               }
               else if (type == 'C')
               {
                   cout << "cruiser!\n";
               }
               else if (type == 'A')
               {
                   cout << "carrier!\n";
               }
               sunk++;
               if (sunk == 5) {
                   break;
               }
           }
       }
       else
       {
           cout << "MISSED!\n";
           grid[ro][co] = 'X';
       }
       cout << shots << " Shots left\n";
   }
   // check if all ships are sunk
   if (sunk == 5)
   {
       cout << "You sunk all my battleships!\n";
   }
   else
   {
       cout << "You ran out of shots\n";
   }
   // restore the original grid for display
   for (row = 0; row < 15; row++)
   {
       for (col = 0; col < 15; col++)
       {
           grid[row][col] = map[row][col];
       }
   }
   printGrid();
   return 0;
}
  

Output:-

Please UPVOTE thank you...!!!


Related Solutions

Create a game of Connect Four using a two dimensional array (that has 6 rows and...
Create a game of Connect Four using a two dimensional array (that has 6 rows and 7 columns) as a class variable. It should be user friendly and be a two person game. It should have clear directions and be visually appealing. The code MUST have a minimum of 3 methods (other than the main method). The player should be able to choose to play again. **Code must be written in Java**
Create a two-dimensional array A using random integers from 1 to 10. Create a two-dimensional array B using random integers from -10 to 0.
This program is for C.Create a two-dimensional array A using random integers from 1 to 10. Create a two-dimensional array B using random integers from -10 to 0. Combine the elements of A + B to create two- dimensional array C = A + B. Display array A, B and C to the screen for comparison. (Note a[0] + b[0] = c[0], a[1] + b[1] = c[1], etc.)
C++ ASSIGNMENT: Two-dimensional array Problem Write a program that create a two-dimensional array initialized with test...
C++ ASSIGNMENT: Two-dimensional array Problem Write a program that create a two-dimensional array initialized with test data. The program should have the following functions: getTotal - This function should accept two-dimensional array as its argument and return the total of all the values in the array. getAverage - This function should accept a two-dimensional array as its argument and return the average of values in the array. getRowTotal - This function should accept a two-dimensional array as its first argument...
you will create a dynamic two dimensional array of mult_div_values structs (defined below). The two dimensional...
you will create a dynamic two dimensional array of mult_div_values structs (defined below). The two dimensional array will be used to store the rows and columns of a multiplication and division table. Note that the table will start at 1 instead of zero, to prevent causing a divide-by-zero error in the division table! struct mult_div_values { int mult; float div; }; The program needs to read the number of rows and columns from the user as command line arguments. You...
How to create a two-dimensional array, initializing elements in the array and access an element in...
How to create a two-dimensional array, initializing elements in the array and access an element in the array using PHP, C# and Python? Provide code examples for each of these programming languages. [10pt] PHP C# Python Create a two-dimensional array Initializing elements in the array Access an element in the array
Build a two dimensional array out of the following three lists. The array will represent a...
Build a two dimensional array out of the following three lists. The array will represent a deck of cards. The values in dCardValues correspond to the card names in dCardNames. Note that when you make an array all data types must be the same. Apply dSuits to dCardValues and dCardNames by assigning a suit to each set of 13 elements. dCardNames = ['2','3','4','5','6','7','8','9','10','J','Q','K','A'] dCardValues = ['2','3','4','5','6','7','8','9','10','11','12','13','14'] dSuits = ["Clubs","Spades","Diamonds","Hearts"] Once assigned your two dimensional array should resemble this : 2...
1.Declare a two-dimensional array of Strings namedchessboard.
1. Declare a two-dimensional array of Strings named chessboard.2. Declare a two-dimensional array of integers named tictactoe.3. Declare and create a two-dimensional array of chars,tictactoe, with 3 rows, each with 3 elements.4. Create a two-dimensional array of ints, plan, with 2 rows, and and 3 columns and initialize the first row to 8, 20, 50 and the second row to 12, 30, 75. Use member initializer syntax.
Create a “Main” method that contains two 2-Dimensional arrays of characters. The first array, which we...
Create a “Main” method that contains two 2-Dimensional arrays of characters. The first array, which we will call our visible field, needs to be 5 by 5 and should initially hold the underscore character “_”.  This will be used in our game of minesweeper to represent the possible locations the player can check. The second array, which we will call our hidden field, should also be 5 by 5 but filled with the capital letter "S” which means safety. However, we...
In C++ using a single dimensional array Create a program that uses a for loop to...
In C++ using a single dimensional array Create a program that uses a for loop to input the day, the high temperature, and low temperature for each day of the week. The day, high, and low will be placed into three elements of the array. For each loop the day, high, and low will be placed into the next set of elements of the array. After the days and temps for all seven days have been entered into the array,...
You will put a possible magic square into a two dimensional array and determine if it...
You will put a possible magic square into a two dimensional array and determine if it is a magic square or not. Some of the code is completed. You can assume that it is a square array and that all of the integers are unique (no repeats) CODE: package TwoDimensionalArrays; public class MagicSquare {    public static boolean checkMagicSquare(int[][]array)    {   //Pre: Assume that the array is a square two dimensional array        //Pre: Assume that there are no...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT