Order Now  +1 678 648 4277 

Design and Develop your own Programming


You are to design and develop a program of your own design and choosing.

Solution:

Project Name and Description

The name of the project is called Battleships.

It is a two-player game adapted from the original Battleships game where each player will have to destroy each other’s ship. The game ends when one of the players has all their ships destroyed.

At the beginning of each game, both players will have to set up their ships on their respective boards. For this project, one of the players is controlled by the user and the other is by a computer. The board has a size dimension of 5 x 5 and only 5 ships are allowed to be displayed. Each ship has to be deployed in only one of the slots on the board. Whilst the user will manually place their ships on the board, the computer will randomly place its ships on the board. The user of course will not be able to know at which coordinates did the computer placed its ships on the board. Additional features include allowing the user to save a game to a file that can be loaded later on.

The game uses the following technical programming features:

  1. Use of meaningful variables and comments to document the program.
  2. Use math operations and the math library to calculate the shooting rate of a user.
  3. Use of conditional statements including nested if-else. Primarily used for validation and coordinating appropriate action based on an event.
  4. Use of loops and nested loops. (for-loop and while-loop). Primarily used for handle board management.
  5. Validation of user input.
  6. Savings and loading game to and from a file.
  7. Use of more than 3 functions including an overloaded function.
  8. The use of 2-dimensional arrays to represent the game board.
  9. Output is formatted and neatly organized.
  10. Runs without errors.

List of Inputs/Outputs

Inputs:

  1.  Selection whether to start a new game, load a saved game, or quit the program.
  2. Row and column coordinate when setting up the ships on the board and during hitting ships on an opponent’s board.

Outputs:

  1. The boards of each player to the console while setting them up or when players are shooting at each other’s boards.
  2. The boards of each player to the file when the user initiates to save the game.
  3. Error messages when entered options and/or coordinates are invalid.
  4. Shooting rate of the user upon ending the game

Flow Chart

Main

The entry point of the program to handle the overall flow of the program.

Flowchart 1

Play Game

A function where both players will shoot at each other’s board until one of them wins.

Flowchart 2

Clear Board

A function to clear the board of each player where all slots are marked as “water”.

Flowchart 3

Print Board

Display a board to the console.

Flowchart 4

Save Game

Writes the board of players to the file.

Flowchart 5

Initialize Boards from File

Loads the saved game from the file. The state of the player boards is restored.

Flowchart 6

Initialize Boards

Allows players to put ships on their boards.

Flowchart 7

Count Elements

A utility function to count how many of a given element exists on the board. The element can be ships, hits, or misses.

Flowchart 8

Instructions on how to use Program

The program starts with the main menu where we select whether to start a new game, load a game, or quit. Choosing quit will terminate the program.

When starting a new game, we enter the coordinates of each of the 5 ships to be placed on the board. We can only put ships on a slot that is not previously occupied.

When loading a game, the program will look for a previously saved file and restore the boards and the game will continue to be played.

While playing, we guess the ships of the opponent by entering a coordinate. A coordinate is only valid if it has not been previously hit. If the coordinate contains a ship, the current player will continue its next move otherwise the next turn is given to the opponent.

The game ends when one of the players have all their ships destroyed.

#include #include #include #include #include #include #include using namespace std; // Constants const int BOARD_SIZE = 5; const char HIT = 'X'; const char MISS = ' '; const char WATER = '~'; const char SHIP = '*'; // Clear the board by putting water on all the slots void clearBoard(char board[BOARD_SIZE][BOARD_SIZE]) { for (int r = 0; r < BOARD_SIZE; r++) for (int c = 0; c < BOARD_SIZE; c++) board[r][c] = WATER; } // Display the board on the console void printBoard(char board[BOARD_SIZE][BOARD_SIZE], bool showShips) { // Display the column coordinates cout << " "; for (int c = 0; c < BOARD_SIZE; c++) cout << c; cout << endl; // Display each row for (int r = 0; r < BOARD_SIZE; r++) { cout << r << " "; for (int c = 0; c < BOARD_SIZE; c++) { if (!showShips && board[r][c] == SHIP) cout << WATER; else cout << board[r][c]; } cout << endl; } } // Forces the user to enter an integer value int readInt(const string &prompt) { while (true) { cout << prompt; string line; getline(cin, line); stringstream ss(line); int value; if (ss >> value) return value; cout << "Error: Please enter an integer value." << endl; } } // Save the game to file void saveGame(char playerBoard[BOARD_SIZE][BOARD_SIZE], char computerBoard[BOARD_SIZE][BOARD_SIZE]) { ofstream outFile("save.dat"); // Write the player's board for (int r = 0; r < BOARD_SIZE; r++) for (int c = 0; c < BOARD_SIZE; c++) outFile << playerBoard[r][c]; // Write the computer's board for (int r = 0; r < BOARD_SIZE; r++) for (int c = 0; c < BOARD_SIZE; c++) outFile << computerBoard[r][c]; outFile << endl; outFile.close(); } // Initialize the board of player and the computer void initializeBoards(char playerBoard[BOARD_SIZE][BOARD_SIZE], char computerBoard[BOARD_SIZE][BOARD_SIZE]) { clearBoard(playerBoard); clearBoard(computerBoard); // Set up the player's board cout << "Okay player, choose the coordinates where you want to place " << BOARD_SIZE << " of your ships..." << endl; for (int i = 0; i < BOARD_SIZE;) { cout << "Player Board" << endl; printBoard(playerBoard, true); cout << "Initializing ship #" << (i + 1) << " coordinates..." << endl; int row = readInt("Enter row (0 - 4): "); int col = readInt("Enter column (0 - 4): "); if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && playerBoard[row][col] == WATER) { playerBoard[row][col] = SHIP; cout << "Ship placed!" << endl; i++; } else { cout << "Invalid coordinates. Please try again." << endl; } } cout << "Player Board" << endl; printBoard(playerBoard, true); cout << endl << endl; cout << "Initializing computer's ships..." << endl; // Initialize the computer's board for (int i = 0; i < BOARD_SIZE;) { int row = rand() % BOARD_SIZE; int col = rand() % BOARD_SIZE; if (computerBoard[row][col] == WATER) { computerBoard[row][col] = SHIP; i++; } } cout << endl; } // Load game from file bool initializeBoards(char playerBoard[BOARD_SIZE][BOARD_SIZE], char computerBoard[BOARD_SIZE][BOARD_SIZE], const string &filename) { cout << "Loading last saved game..." << endl; ifstream inFile(filename.c_str()); if (!inFile.is_open()) return false; // Load player's board for (int r = 0; r < BOARD_SIZE; r++) for (int c = 0; c < BOARD_SIZE; c++) inFile >> noskipws >> playerBoard[r][c]; // Load computer's board for (int r = 0; r < BOARD_SIZE; r++) for (int c = 0; c < BOARD_SIZE; c++) inFile >> noskipws >> computerBoard[r][c]; inFile.close(); return true; } // Count the existence of an element in the board int countElement(char board[BOARD_SIZE][BOARD_SIZE], char element) { int count = 0; for (int r = 0; r < BOARD_SIZE; r++) for (int c = 0; c < BOARD_SIZE; c++) if (board[r][c] == element) count++; return count; } // Play the game until game is over void playGame(char playerBoard[BOARD_SIZE][BOARD_SIZE], char computerBoard[BOARD_SIZE][BOARD_SIZE]) { bool playerMoves = true; cout << "Game has started!" << endl; while (countElement(playerBoard, SHIP) > 0 && countElement(computerBoard, SHIP) > 0) { if (playerMoves) { // Make the player have its turn cout << "Computer Board" << endl; printBoard(computerBoard, false); int row = readInt("Enter a row to shoot (0 - 4 or 9 to save game): "); int col = readInt("Enter a column to shoot (0 - 4 or 9 again to confirm save game): "); if (row == 9 && col == 9) { // Save the game saveGame(playerBoard, computerBoard); cout << "Game saved!" << endl; } else if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && (computerBoard[row][col] == WATER || computerBoard[row][col] == SHIP)) { if (computerBoard[row][col] == SHIP) { // Player remains next move computerBoard[row][col] = HIT; cout << "It's a hit!" << endl; } else { // Give next turn to computer computerBoard[row][col] = MISS; cout << "You missed!" << endl; printBoard(computerBoard, false); playerMoves = false; } } else { cout << "Error: Invalid coordinate." << endl; } } else { // Computer makes its turn int row = rand() % BOARD_SIZE; int col = rand() % BOARD_SIZE; if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && (playerBoard[row][col] == WATER || playerBoard[row][col] == SHIP)) { cout << "Player Board" << endl; printBoard(playerBoard, true); if (playerBoard[row][col] == SHIP) { // Computer remains next move playerBoard[row][col] = HIT; cout << "Computer made a hit at coordinate " << row << ", " << col << "!" << endl; } else { // Computer missed, give turn to player playerBoard[row][col] = MISS; cout << "Computer missed at coordinate " << row << ", " << col << "!" << endl; playerMoves = true; } } } } cout << endl; // Display the final boards cout << "Player Board" << endl; printBoard(playerBoard, true); cout << endl; cout << "Computer Board" << endl; printBoard(computerBoard, true); cout << endl; // Display the winner if (countElement(playerBoard, SHIP) > 0) cout << "You win!" << endl; else cout << "You lose!" << endl; cout << endl; int playerShootingRate = (int)round(100 - ((countElement(computerBoard, HIT) + countElement(computerBoard, MISS)) / (double)(BOARD_SIZE * BOARD_SIZE) * 100)); cout << "Player shooting rate : " << playerShootingRate << "%" << endl; cout << endl; } // Entry point of the program int main() { char playerBoard[BOARD_SIZE][BOARD_SIZE]; char computerBoard[BOARD_SIZE][BOARD_SIZE]; while (true) { // Show some options cout << "Battleships Menu" << endl; cout << "1. New Game" << endl; cout << "2. Load Game" << endl; cout << "0. Exit" << endl; // Ask user what to do int option = readInt("Option: "); // Execute user's option if (option == 1) { initializeBoards(playerBoard, computerBoard); playGame(playerBoard, computerBoard); } else if (option == 2) { if (initializeBoards(playerBoard, computerBoard, "save.dat")) playGame(playerBoard, computerBoard); else cout << "There are no previously saved game." << endl; } else if (option == 0) { break; } else { cout << "Error: Invalid option." << endl; } cout << endl; } return 0; } ScreenShots

Playing a New Game

Screenshot 1

Screenshot 2

Screenshot 3

Screenshot 4

Screenshot 5

The game is getting long… we’re skipping screenshots to the end.

Screenshot 6

Saving and Loading the Game from and/or To File

After a few rounds, we will save the game.

Screenshot 7

We’re going to end the game and load the saved game.

screenshot 8

Placed Validations

Error when coordinates are not within the board’s range.

Screenshot 9

Error when the coordinate is already previously shot.

Screenshot 10

Error when deploying a ship on a slot that is already occupied.

Screenshot 11

Error when not entering an integer value for an input that requires an integer value.