Question

I need help finishing my C++ coding assignment! My teacher has provided a template but I...

I need help finishing my C++ coding assignment! My teacher has provided a template but I need help finishing it! Details are provided below and instructions are provided in the //YOU: comments of the template...

My teacher has assigned a game that is similar to battleship but it is single player with an optional multiplayer AI... In the single player game you place down a destroyer, sub, battleship, and aircraft carrier onto the grid.... Then you attack the ships you placed down. There is a torpedo count when the count runs out, you lose. The optional AI multiplayer is extra credit.... The multiplayer version is exactly like the normal Battleship game... This version of the game is not necessary the game only has to be single player, but i would like extra credit if possible.

He has given us a template that needs to be completed... The areas that need to be completed say YOU... The areas that say you include instructions on what to add into the code! I have made all the //YOU statements bold for better understanding

*Note the AI is extra credit so the template is not provided, the AI must be thought of and implemented in this code. If the AI is not implemented then just complete the code below where it says //YOU

----------------------------------------------------------------------

Template

#include
#include
using namespace std;

const size_t SIZE = 12;
int board[SIZE][SIZE] = {};

//Makes a bunch of constants for the letters to be printed on the board
enum tiles { CLEAR=0, DESTROYER, SUBMARINE, BATTLESHIP, AIRCRAFT_CARRIER, HIT, MISS };
int message = 0; //If a ship has been destroyed, it will be set to BATTLESHIP or whatever

//Holds how big each ship is
enum sizes { DESTROYER_SIZE=2, SUBMARINE_SIZE=3, BATTLESHIP_SIZE=4, AIRCRAFT_CARRIER_SIZE=5 };

void die() {
cout << "Bad input!\n";
exit(1);
}

void win(); //Function prototype, ends the game successfully
void lose(); //Ends the game with failure

void print_board() {
system("clear");
cout << "BATTLESLOOP 2000(tm)\n";
//Print column headers
cout << "\t";
for (size_t i = 0; i < SIZE; i++)
cout << i << "\t";
cout << endl;
//Print board
for (size_t i = 0; i < SIZE; i++) {
//Print row headers
cout << i << "\t";
for (size_t j = 0; j < SIZE; j++) {
if (board[j][i] == CLEAR) cout << "." << "\t";
else if (board[j][i] == DESTROYER) cout << "D" << "\t";
else if (board[j][i] == SUBMARINE) cout << "S" << "\t";
else if (board[j][i] == BATTLESHIP) cout << "B" << "\t";
else if (board[j][i] == AIRCRAFT_CARRIER) cout << "A" << "\t";
else if (board[j][i] == HIT) cout << "*" << "\t";
else if (board[j][i] == MISS) cout << "X" << "\t";
else die();
}
cout << endl;
}
if (message == MISS) cout << "MISS!\n";
else if (message == HIT) cout << "HIT!\n";
else if (message == DESTROYER) cout << "You sank my destroyer!\n";
//YOU: Do the rest

message = 0; //Clear the message so it doesn't display again.
}

int main() {
cout << "Welcome to Battlesloop 2000(tm)\n";
cout << "Press any key and hit enter to continue.\n";
getchar();

//PHASE 1 - Set up the ships on the board
print_board();
cout << "Please insert the (x,y) starting location for the destroyer:\n";
int x=0,y=0;
cin >> x >> y;
if (!cin) die();
//YOU: Error check the coordinates
cout << "Is the destroyer vertical (v) or horizontal (h)?\n";
char c = 0;
cin >> c;
if (!cin) die();
if (c == 'v') { //If vertical, we start at the top and go down
for (int i = 0; i < DESTROYER_SIZE; i++) {
//YOU: Error check the coordinates
board[x][y] = DESTROYER;
y++;
}
}
else if (c == 'h') {
//YOU: Do the same for a horizontal ship

}
else die();
print_board();
//YOU: Do the same for the other three ships

//PHASE 2 - Shoot torpedoes at the ships until they're all destroyed
int torpedoes = 40; //If these run out, we lose
while (true) { //Main loop
print_board(); //Display the world state

//Input next move
cout << "Please enter where you want to shoot a torpedo:\n";
cin >> x >> y;
if (!cin) die(); //YOU: Add in bounds checks for x and y

if (board[x][y] == CLEAR || board[x][y] == HIT || board[x][y] == MISS) {
message = MISS; //This will do a cout << "MISS!\n"; when the board is next printed

//YOU: When should it not register a miss? Add an if statement for that
board[x][y] = MISS;
}
else { //Hit!
message = HIT;
//YOU: Mark the board with a hit

//YOU: If that was the last one of a certain ship, set message.
// In other words, if that was the last of the battleship,
// set message = BATTLESHIP. This will cause "You sank my battleship!" to be
// printed the next time the board is displayed instead of just "HIT!"

//YOU: If no ships are remaining, call win();
}
//YOU: Reduce torpedoes by 1
//YOU: If torpedoes is < 0, call lose();

}
}

void beep() {
cout << "^G";
}
void win() {
beep();
cout << "You are a Winner \n";
beep();
exit(0);
}

void lose() {
beep();
cout << "You Lose
beep();

exit(0);
}

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

Working code implemented in C++ and comments for better understanding:

Code for main.cpp:

#include <iostream>

#include <cstdlib>

using namespace std;

const size_t SIZE = 12;

int board[SIZE][SIZE] = {};

//Makes a bunch of constants for the letters to be printed on the board

enum tiles { CLEAR = 0, DESTROYER, SUBMARINE, BATTLESHIP, AIRCRAFT_CARRIER, HIT, MISS };

int message = 0; //If a ship has been destroyed, it will be set to BATTLESHIP or whatever

//Holds how big each ship is

enum sizes { DESTROYER_SIZE = 2, SUBMARINE_SIZE = 3, BATTLESHIP_SIZE = 4, AIRCRAFT_CARRIER_SIZE = 5 };

void die() {

  cout << "Bad input!\n";

  exit(1);

}

bool isDestroyer = true, isSubmarine = true, isBattleship = true, isAircraftCarrier = true;

void win(); //Function prototype, ends the game successfully

void lose(); //Ends the game with failure

void print_board() {

  system("clear");

  cout << "BATTLESLOOP 2000(tm)\n";

  //Print column headers

  cout << "\t";

  for (size_t i = 0; i < SIZE; i++)

    cout << i << "\t";

  cout << endl;

  //Print board

  for (size_t i = 0; i < SIZE; i++) {

    //Print row headers

    cout << i << "\t";

    for (size_t j = 0; j < SIZE; j++) {

      if (board[j][i] == CLEAR) cout << "." << "\t";

      else if (board[j][i] == DESTROYER) cout << "D" << "\t";

      else if (board[j][i] == SUBMARINE) cout << "S" << "\t";

      else if (board[j][i] == BATTLESHIP) cout << "B" << "\t";

      else if (board[j][i] == AIRCRAFT_CARRIER) cout << "A" << "\t";

      else if (board[j][i] == HIT) cout << "*" << "\t";

      else if (board[j][i] == MISS) cout << "X" << "\t";

      else die();

    }

    cout << endl;

  }

  if (message == MISS)    cout << "MISS!\n";

  else if (message == HIT)    cout << "HIT!\n";

  else if (message == DESTROYER) cout << "You sank my destroyer!\n";

  else if (message == SUBMARINE) cout << "You sank my submarine!\n";

  else if (message == BATTLESHIP) cout << "You sank my battleship!\n";

  else if (message == AIRCRAFT_CARRIER) cout << "You sank my aircraft carrier!\n";

  //YOU: Do the rest

  message = 0; //Clear the message so it doesn't display again.

}

int main() {

  cout << "Welcome to Battlesloop 2000(tm)\n";

  cout << "Press any key and hit enter to continue.\n";

  getchar();

  //PHASE 1 - Set up the ships on the board

  //DESTROYER PLACEMENT

  print_board();

  cout << "Please insert the (x,y) starting location for the destroyer:\n";

  int x = 0, y = 0;

  cin >> x >> y;

  if (!cin) die();

  //YOU: Error check the coordinates

  if (x < 0 || x > SIZE - 1 || y < 0 || y > SIZE - 1) die();

  cout << "Is the destroyer vertical (v) or horizontal (h)?\n";

  char c = 0;

  cin >> c;

  if (!cin) die();

  if (c == 'v') { //If vertical, we start at the top and go down

    for (int i = 0; i < DESTROYER_SIZE; i++) {

      //YOU: Error check the coordinates

      if (y < SIZE) {

        board[x][y] = DESTROYER;

        y++;

      } else {

        die();

      }

    }

  } else if (c == 'h') {

    //YOU: Do the same for a horizontal ship

    for (int i = 0; i < DESTROYER_SIZE; i++) {

      if (board[x][y] == CLEAR) {

        if (x < SIZE) {

          board[x][y] = DESTROYER;

          x++;

        } else {

          die();

        }

      } else die();

    }

  } else die();

  print_board();

  //YOU: Do the same for the other three ships

  //SUBMARINE PLACEMENT

  cout << "Please insert the (x,y) starting location for the submarine:\n";

  cin >> x >> y;

  if (!cin || x > SIZE - 1 || x < 0 || y > SIZE - 1 || y < 0) die();

  cout << "Is the submarine vertical (v) or horizontal (h)?\n";

  cin >> c;

  if (c == 'v') {

    for (int i = 0; i < SUBMARINE_SIZE; i++) {

      if (board[x][y] == CLEAR) {

        if (y < SIZE) {

          board[x][y] = SUBMARINE;

          y++;

        } else die();

      } else die();

    }

  } else if (c == 'h') {

    for (int i = 0; i < SUBMARINE_SIZE; i++) {

      if (board[x][y] == CLEAR) {

        if (x < SIZE) {

          board[x][y] = SUBMARINE;

          x++;

        } else {

          die();

        }

      } else die();

    }

  } else die();

  print_board();

  //BATTLESHIP PLACEMENT

  cout << "Please insert the (x,y) starting location for the battleship: \n";

  cin >> x >> y;

  if (!cin || x > SIZE - 1 || x < 0 || y > SIZE - 1 || y < 0) die();

  cout << "Is the battleship vertical (v) or horizontal (h)?\n";

  cin >> c;

  if (c == 'v') {

    for (int i = 0; i < BATTLESHIP_SIZE; i++) {

      if (board[x][y] == CLEAR) {

        if (y < SIZE) {

          board[x][y] = BATTLESHIP;

          y++;

        } else die();

      } else die();

    }

  } else if (c == 'h') {

    for (int i = 0; i < BATTLESHIP_SIZE; i++) {

      if (board[x][y] == CLEAR) {

        if (x < SIZE) {

          board[x][y] = BATTLESHIP;

          x++;

        } else die();

      } else die();

    }

  } else die();

  print_board();

  cout << "Please insert the (x,y) starting location for the aircraft carrier: \n";

  cin >> x >> y;

  if (!cin || x > SIZE - 1 || x < 0 || y > SIZE - 1 || y < 0) die();

  cout << "Is the aircraft carrier vertical (v) or horizontal (h)? \n";

  cin >> c;

  if (c == 'v') {

    for (int i = 0; i < AIRCRAFT_CARRIER_SIZE; i++) {

      if (board[x][y] == CLEAR) {

        if (y < SIZE) {

          board[x][y] = AIRCRAFT_CARRIER;

          y++;

        } else die();

      } else die();

    }

  } else if (c == 'h') {

    for (int i = 0; i < AIRCRAFT_CARRIER_SIZE; i++) {

      if (board[x][y] == CLEAR) {

        if (x < SIZE) {

          board[x][y] = AIRCRAFT_CARRIER;

          x++;

        } else die();

      } else die();

    }

  } else die();

  //PHASE 2 - Shoot torpedoes at the ships until they're all destroyed

  int torpedoes = 40; //If these run out, we lose

  //Main loop

  while (true) {

    print_board(); //Display the world state

    //Input next move

    cout << "Please enter where you want to shoot a torpedo:\n";

    cin >> x >> y;

    if (!cin || x < 0 || x > 11 || y < 0 || y > 11) die(); //YOU: Add in bounds checks for x and y

    if (board[x][y] == CLEAR || board[x][y] == HIT || board[x][y] == MISS) {

      message = MISS; //This will do a cout << "MISS!\n"; when the board is next printed

      //YOU: When should it not register a miss? Add an if statement for that

      if (board[x][y] == HIT || board[x][y] == MISS) {

      } else {

        board[x][y] = MISS;

      }

    } else {

      //Hit!

      message = HIT;

      //YOU: Mark the board with a hit

      board[x][y] = HIT;

      //YOU: If that was the last one of a certain ship, set message.

      // In other words, if that was the last of the battleship,

      // set message = BATTLESHIP. This will cause "You sank my battleship!" to be

      // printed the next time the board is displayed instead of just "HIT!"

      int dShipCtn = 0, sShipCtn = 0, bShipCtn = 0, aShipCtn = 0;

      for (int i = 0; i < SIZE; i++) {

        for (int j = 0; j < SIZE; j++) {

          switch (board[i][j]) {

          case 1:

            dShipCtn++;

          case 2:

            sShipCtn++;

          case 3:

            bShipCtn++;

          case 4:

            aShipCtn++;

          default:

            break;

          }

        }

      }

      if (dShipCtn == 0 && isDestroyer == true) {

        message = DESTROYER;

        isDestroyer = false;

      } else if (sShipCtn == 0 && isSubmarine == true) {

        message = SUBMARINE;

        isSubmarine = false;

      } else if (bShipCtn == 0 && isBattleship == true) {

        message = BATTLESHIP;

        isBattleship = false;

      } else if (aShipCtn == 0 && isAircraftCarrier == true) {

        message = AIRCRAFT_CARRIER;

        isAircraftCarrier = false;

      }

      if (dShipCtn == 0 && sShipCtn == 0 && bShipCtn == 0 && aShipCtn == 0) win();

    }

    //YOU: Reduce torpedoes by 1

    torpedoes -= 1;

    //YOU: If torpedoes is < 0, call lose();

    if (torpedoes < 0) lose();

  }

}

void beep() {

  cout << "";

}

void win() {

  beep();

  cout << " _ __ _____ _ _ _ _ _____ ____ ___ ____\n";

  cout << " / \\ \\ \\ / /_ _| \\ | | \\ | | ____| _ \\ |_ _/ ___|\n";

  cout << " / _ \\ \\ \\ /\\ / / | || \\| | \\| | _| | |_) | | |\\___ \\\n";

  cout << " / ___ \\ \\ V V / | || |\\ | |\\ | |___| _ < | | ___) |\n";

  cout << "/_/ \\_\\ \\_/\\_/ |___|_| \\_|_| \\_|_____|_| \\_\\ |___|____/\n";

  cout << "\n";

  cout << "__ _____ _ _\n";

  cout << "\\ \\ / / _ \\| | | |\n";

  cout << " \\ V / | | | | | |\n";

  cout << " | || |_| | |_| |\n";

  cout << " |_| \\___/ \\___/\n";

  beep();

  exit(0);

}

void lose() {

  beep();

  cout << "__ _____ _ _ _ ___ ____ _____\n";

  cout << "\\ \\ / / _ \\| | | | | | / _ \\/ ___|| ____|\n";

  cout << " \\ V / | | | | | | | | | | | \\___ \\| _|\n";

  cout << " | || |_| | |_| | | |__| |_| |___) | |___\n";

  cout << " |_| \\___/ \\___/ |_____\\___/|____/|_____|\n";

  beep();

  exit(0);

}

Code Screenshots:

Output Screenshots:

Hope it helps, if you like the answer give it thumbs up. Thank you.

Add a comment
Know the answer?
Add Answer to:
I need help finishing my C++ coding assignment! My teacher has provided a template but I...
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
  • Can somebody help me with this coding the program allow 2 players play tic Tac Toe....

    Can somebody help me with this coding the program allow 2 players play tic Tac Toe. however, mine does not take a turn. after player 1 input the tow and column the program eliminated. I want this program run until find a winner. also can somebody add function 1 player vs computer mode as well? Thanks! >>>>>>>>>>>>>Main program >>>>>>>>>>>>>>>>>>>>>>> #include "myheader.h" int main() { const int NUM_ROWS = 3; const int NUM_COLS = 3; // Variables bool again; bool won;...

  • Can anyone help me with my C++ assignment on structs, arrays and bubblesort? I can't seem...

    Can anyone help me with my C++ assignment on structs, arrays and bubblesort? I can't seem to get my code to work. The output should have the AVEPPG from highest to lowest (sorted by bubbesort). The output of my code is messed up. Please help me, thanks. Here's the input.txt: Mary 15 10.5 Joseph 32 6.2 Jack 72 8.1 Vince 83 4.2 Elizabeth 41 7.5 The output should be: NAME             UNIFORM#    AVEPPG Mary                   15     10.50 Jack                   72      8.10 Elizabeth              41      7.50 Joseph                 32      6.20 Vince                  83      4.20 ​ My Code: #include <iostream>...

  • i need this in C# please can any one help me out and write the full...

    i need this in C# please can any one help me out and write the full code start from using system till end i am confused and C# is getting me hard.I saw codes from old posts in Chegg but i need the ful complete code please thanks. Module 4 Programming Assignment – OO Design and implementation (50 points) Our Battleship game needs to store a set of ships. Create a new class called Ships. Ships should have the following...

  • C++ i have started the program i just need help finishing it. This chapter is on...

    C++ i have started the program i just need help finishing it. This chapter is on functions. If you write this assignment without creating functions (main itself does not count) then the maximum score you can receive is 10% of the grade even if the output is perfectly correct. Write a modular program with the following Functions: Main, PrintHeading, PrintTuitionTable The Main Function should ask the user for a Tuition like assignment 6. Then it should call the PrintHeading function,...

  • In C++ please.. I only need the game.cpp. thanks. Game. Create a project titled Lab8_Game. Use...

    In C++ please.. I only need the game.cpp. thanks. Game. Create a project titled Lab8_Game. Use battleship.h, battleship.cpp that mentioned below; add game.cpp that contains main() , invokes the game functions declared in battleship.h and implements the Battleship game as described in the introduction. ——————————————- //battleship.h #pragma once // structure definitions and function prototypes // for the battleship assignment // 3/20/2019 #include #include #ifndef BATTLESHIP_H_ #define BATTLESHIP_H_ // // data structures definitions // const int fleetSize = 6; // number...

  • I haven't code in awhile and would like some help getting back on my feet. Need to code this in C++. Thank you! In...

    I haven't code in awhile and would like some help getting back on my feet. Need to code this in C++. Thank you! In this homework, you will implement a simple version of the game Battleship, in which the player tries to destroy ships hidden on a map using a system of coordinates. In this program, the map will be represented by a 4x4 matrix of integers. A 1 in the matrix represents the presence of a ship. There are...

  • This is an advanced version of the game tic tac toe, where the player has to...

    This is an advanced version of the game tic tac toe, where the player has to get five in a row to win. The board is a 30 x 20. Add three more functions that will check for a win vertically, diagonally, and backwards diagonally. Add an AI that will play against the player, with random moves. Bound check each move to make sure it is in the array. Use this starter code to complete the assignment in C++. Write...

  • Hello, I am working on my final and I am stuck right near the end of...

    Hello, I am working on my final and I am stuck right near the end of the the program. I am making a Tic-Tac-Toe game and I can't seem to figure out how to make the program ask if you would like to play again, and keep the same names for the players that just played, keep track of the player that wins, and display the number of wins said player has, after accepting to keep playing. I am wanting...

  • I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<i...

    I just need a help in replacing player 2 and to make it unbeatable here is my code: #include<iostream> using namespace std; const int ROWS=3; const int COLS=3; void fillBoard(char [][3]); void showBoard(char [][3]); void getChoice(char [][3],bool); bool gameOver(char [][3]); int main() { char board[ROWS][COLS]; bool playerToggle=false; fillBoard(board); showBoard(board); while(!gameOver(board)) { getChoice(board,playerToggle); showBoard(board); playerToggle=!playerToggle; } return 1; } void fillBoard(char board[][3]) { for(int i=0;i<ROWS;i++) for(int j=0;j<COLS;j++) board[i][j]='*'; } void showBoard(char board[][3]) { cout<<" 1 2 3"<<endl; for(int i=0;i<ROWS;i++) { cout<<(i+1)<<"...

  • Coding in c++

    I keep getting errors and i am so confused can someone please help and show the input and output ive tried so many times cant seem to get it. main.cpp #include <iostream> #include <vector> #include <string> #include "functions.h" int main() {    char option;    vector<movie> movies;     while (true)     {         printMenu();         cin >> option;         cin.ignore();         switch (option)         {            case 'A':            {                string nm;                int year;                string genre;                cout << "Movie Name: ";                getline(cin, nm);                cout << "Year: ";                cin >> year;                cout << "Genre: ";                cin >> genre;                               //call you addMovie() here                addMovie(nm, year, genre, &movies);                cout << "Added " << nm << " to the catalog" << endl;                break;            }            case 'R':            {                   string mn;                cout << "Movie Name:";                getline(cin, mn);                bool found;                //call you removeMovie() here                found = removeMovie(mn, &movies);                if (found == false)                    cout << "Cannot find " << mn << endl;                else                    cout << "Removed " << mn << " from catalog" << endl;                break;            }            case 'O':            {                string mn;                cout << "Movie Name: ";                getline(cin, mn);                cout << endl;                //call you movieInfo function here                movieInfo(mn, movies);                break;            }            case 'C':            {                cout << "There are " << movies.size() << " movies in the catalog" << endl;                 // Call the printCatalog function here                 printCatalog(movies);                break;            }            case 'F':            {                string inputFile;                bool isOpen;                cin >> inputFile;                cout << "Reading catalog info from " << inputFile << endl;                //call you readFromFile() in here                isOpen = readFile(inputFile, &movies);                if (isOpen == false)                    cout << "File not found" << endl;...

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
ADVERTISEMENT