+1 (315) 557-6473 

Battleship Game in C++ using 2D Array Homework Solution


Simplified version of Battleship Game

In this lab, we will create a very simplified version of “Battleship”

Your program will set up a 2D array (5 rows by 5 columns) and initialize each element as space (press the spacebar key) to represent a “black” element.

It will then generate two random numbers (a row and column) to represent the location of a hidden bomb within the 2D array.

To complete the c++ assignment ask the user for two numbers as their guess for the bomb’s location.

If the user guessed wrong, place an ‘O’ to represent their miss. If they guessed correctly, place an ‘X’ to represent their hit. After each turn, display the array in a table format so they can visually see the game board.

You are NOT required to validate input except for index out of bounds. So, assume the user will be cooperative and only provide numbers.

Example program execution (red font is user input):Battleship

Solution:

#include < iostream> using namespace std; void setupGameBoard(); void displayGameBoard(); int getRandomNum(); int bombRow, bombCol; const int DIM = 5; char gameBoard[DIM][DIM]; int main() { int pos_x, pos_y; bool win = false; setupGameBoard(); do { cout << "Try to find the randomly placed bomb." << endl; do { cout << "Enter two numbers as coordinates (1 - 5): "; cin >> pos_x; cin >> pos_y; if ( pos_x < 1 || pos_x > DIM || pos_y < 1 || pos_y > DIM ) { cout << "Please only enter values between 1 and 5 inclusive." << endl; cout << endl; } else { break; } } while ( true ); pos_x--; pos_y--; if ( ( pos_x == bombRow ) && ( pos_y == bombCol ) ) { cout << "Direct hit!" << endl; gameBoard[pos_x][pos_y] = 'X'; win = true; } else { cout << "You missed! Try again." << endl; gameBoard[pos_x][pos_y] = 'O'; } cout << endl; displayGameBoard(); if ( win ) { cout << "Game over!" << endl; break; } } while ( true ); return 0; } // Display the 2D Array as a table void displayGameBoard() { cout << " "; for ( int i = 0; i < DIM; i++ ) { cout << i + 1 << " "; } cout << endl; for ( int i = 0; i < DIM; i++ ) { cout << i + 1 << ' '; for ( int j = 0; j < DIM; j++ ) { cout << '[' << gameBoard[i][j] << ']'; } cout << endl; } cout << endl; } void setupGameBoard() { // Initialize each element of the character array as a space for ( int i = 0; i < DIM; i++ ) { for ( int j = 0; j < DIM; j++ ) { gameBoard[i][j] = ' '; } } // initialize random seed srand (time(NULL)); // randomly assign coordinates of the bomb bombRow = getRandomNum(); bombCol = getRandomNum(); // cout << bombRow << " " << bombCol << endl; // used for testing } int getRandomNum() { //generate number between 0 and 4 return rand() % DIM; }