To create a C++ program to practice two-dimensional arrays and implement a game
ID: 3930049 • Letter: T
Question
To create a C++ program to practice two-dimensional arrays and implement a game in which a player attempts to sink a fleet of five navy vessels by guessing their locations on a grid. You need to create a C++ class for the game with a two-dimensional array as the grid for ship locations. At the beginning, your game will initialize the five navy vessels locations randomly. A player will enter the locations of his/her missiles and your program will determine if it is a hit. The player wins if he/she hits all of five navy vessels before he/she runs out of his missiles, or the player loses. You need to create a game class to complete the lab. Define the class functions and variables yourself. Follow the C++ object-oriented programming style.Explanation / Answer
Solution for the above given Game Problem in C++.
#include<iostream>
#include<random>
#include<cstdlib>
using namespace std;
class Game
{
int ROW_SIZE,COLUMN_SIZE;
void fillRandomLocations(int,int); // Function to fill out random vessels
void HitLocation(int[][],int,int);//Function to check whether your missiles hit or not
}
int main()
{
Game game = new Game(); / /Creating the object of that class
int R1,C1;
R1=game.ROW_SIZE;
C1=game.COLUMN_SIZE;
cout << "Please enter the Row Size : " << endl;
cin >> R1; // Enter the number of rows of the Array;
cout << "Please enter the Column Size: " << endl;
cin >> C1; // Enter the number of columns for the array
int array[R1[C1]; // Initializing array with entered values
RAND_MAX1 = R1;
RAND_MAX2 = C1;
for(int i=0;i<R1;i++) // Initializing whole locations to zero first
{
for(int j=0;j<C1;j++)
{
array[i][j]=0;
}
}
game.fillRandomLocation(RAND_MAX1,RAND_MAX2); // Calling function to fill out vessels randomly
void HitLocation(array,R1,C1);
return 0;
}
void fillRandomLocations(int RAND_MAX1,int RAND_MAX2)
{
for(int i=0;i<5;i++)
{
array[rand() % RAND_MAX1][rand() % RAND_MAX2] = rand() % 100; //Fills out locations for 5 times
}
cout << "Locations have been filled with vessels randomly " << endl;
}
void HitLocation(int[][] array,int R1,int C1)
{
int count=0,ROW,COLUMN;
for(int i=0;i<R1+C1<i++)
{
cout << "Enter the hits as row number and column number"<<endl;
cin >> ROW >> COLUMN;
if(array[ROW][COLUMN]!=0)
count++;
else
continue;
}
if(count == 5) // if 5 hits are correct
cout << "Your Missiles Hit Successfully " << endl;
else
cout << "Better Luck...Try Once again " << endl;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.