4 Replies - 8637 Views - Last Post: 13 March 2010 - 12:11 PM Rate Topic: -----

#1 dfournie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 22-September 09

Battleship Game Help in C++

Posted 07 December 2009 - 12:49 PM

I had already posted a previous question about this program a week ago. No one replied...that sucks...So here is what i came up with for anyone interested in the code so far.
Note: This is not the final code for the project..i am having a few prblems if anyone can help me with it. Help would be greatly appreciated.

Basically how do i
1.) show the status of the ships in the PlaySingleMode() function?..when if you run the program..the menu deal at the top...the one with ENEMY: and STATUS:? I was going to use AT LARGE! and SUNK! for the status.
but how do i do it?
2.) When a ship is hit it is supposed to put an "*" on the screen/Grid..it only puts the " " letter of the boat hit, which isnt supposed to be displayed until it is sunk, only the asterick is.?

/*

#include <iostream>
#include <ctime>
#include <string>
#include <iomanip>
#include <windows.h>

using namespace std;
const int GRIDSIZE = 10;
enum direction {EXPAND_ROW, EXPAND_COL};

// Function Prototypes
int GetPlayers();
void SetComputerBoats(char [GRIDSIZE][GRIDSIZE]);
void PrintBoard(char [GRIDSIZE][GRIDSIZE]);
string GetRank(int);
int PlaySingleMode(char [GRIDSIZE][GRIDSIZE]);
void SetParticularBoat(char [GRIDSIZE][GRIDSIZE], int, char);


void main()
{
	//Just For Fun!>
	system("color 02");
	int numOfPlayers, moves=99;
	//char player1Boats[GRIDSIZE][GRIDSIZE];
	char player2Boats[GRIDSIZE][GRIDSIZE];

	// Print Title, seed RNG and get # of players
	cout << "						 B A T T L E S H I P\n";
	srand( (unsigned int) time(NULL) );
	numOfPlayers = GetPlayers();

	// Set boats - multiplayer not yet implemented
	if(numOfPlayers == 2)
	{
		cout << "Player 1... get ready to place your ships...\n";
		system("pause");

		//SetPlayerBoats(player1Boats);

		cout << "Player 2... get ready to place your ships...\n";
		system("pause");
		//SetPlayerBoats(player2Boats);
	}
	else // Single-player mode - set computer boats
	{
		SetComputerBoats(player2Boats);
	}

	if(numOfPlayers == 1)
	{
		moves = PlaySingleMode(player2Boats);
		system("cls");
		cout << "						 B A T T L E S H I P\n\n\n";
		PrintBoard(player2Boats);
		cout << "\n\nDestroying boats within " << moves 
			 << " moves earns you the rank of "<< GetRank(moves) << ".\n";
	}
	//else
	//	winner = Play2PlayerMode(player1Boats, player2Boats);
}

// Function: GetPlayers() *****************************************************
//
//   Input		: None
//   Output		: None
//   Returns	: The number of players (1 or 2)
//
//   Description: This functions attempts to retreive the number of players
//   from the user - either 1 or 2. Error correcting code forces the user
//   to type 1 or 2. Multiplayer mode (2 players) not yet implemented.
int GetPlayers()
{
	int n;
	cout << endl << "For 1 or 2 players? ";
	cin >> n;
	
	while(!cin || (n != 1 && n != 2))
	{
		if(!cin)
		{
			cin.clear();
			cin.ignore(INT_MAX,'\n');
		}
		cout << "For 1 or 2 players? ";
		cin >> n;
	}

	if(n == 2)
		cout << "Sorry, multiplayer mode not yet implemented."
			 << " Starting single-player mode.\n";
	return(1);
} // end of GetPlayers()*******************************************************



// Function: SetComputerBoats()************************************************
//
//   Input		: 2D character array of the computer boat locations
//   Output		: None
//   Returns	: Nothing.
//
//   Description: Randomly select where to place the boats corresponding to:
void SetComputerBoats(char p[GRIDSIZE][GRIDSIZE])
{

	// Initialize the empty grid
	for(int i=0; i<GRIDSIZE; i++)
		for(int j=0; j<GRIDSIZE; j++)
			p[i][j] = '-';

	// Set all 5 boats.
	SetParticularBoat(p, 5, 'A'); // Aircraft Carrier
	SetParticularBoat(p, 4, 'B'); // Battleship
	SetParticularBoat(p, 3, 'C'); // Cruiser
	SetParticularBoat(p, 3, 'S'); // Submarine
	SetParticularBoat(p, 2, 'D'); // Destroyer.

	//	PrintBoard(p);
} // end of SetComputerBoats()*************************************************



 /*Function: PrintBoard()******************************************************

   Input		: 2D character array of the battleship board
   Output		: The 2D array of the battleship board
   Returns		: Nothing.

   Description: This will print the grid showing where the boats are for
   the passed grid. Different characters will represent various meanings:

			'-'		Nothing is at this location.
			'A'		Part of the Aircraft Carrier
			'B'		Part of the Battleship
			'C'		Part of the Cruiser
			'S'		Part of the Submarine
			'D'		Part of the Destroyer
			'*'		A current "hit" is known.
			'M'		A current "miss" is known.						 */ 
void PrintBoard(char p[GRIDSIZE][GRIDSIZE])
{
	cout << "						1  2  3  4  5  6  7  8  9 10\n";
	cout << "					  ------------------------------\n";
	for(int i=0; i<GRIDSIZE; i++)
	{
		cout << "					" << char('A' + i) << " |";
		for(int j=0; j<GRIDSIZE; j++)
			cout << ' ' << p[i][j] << ' ';
		cout << endl;
	}
} // end of PrintBoard()*******************************************************


 /*Function: GetRank()*********************************************************

   Input		: An integer, representing the number of moves.
   Output		: None
   Returns		: The specific 'rank' of the player.

   Description: This will return a string corresponding to the rank earned
   while playing the game, depending on the number of moves took to win. The
   rank earned will follow:

		00 - 25 : Admiral
		26 - 35	: Captain
		36 - 45 : Commander
		46 - 60 : Lieutenant
		61 +	: Ensign												 */
string GetRank(int m)
{
	if(m <= 25)
		return("Admiral");
	else if(m <= 35)
		return("Captain");
	else if(m <= 45)
		return("Commander");
	else if(m <= 60)
		return("Lieutenant");
	else
		return("Ensign");
} // end of GetRank()**********************************************************


 /*Function: PlaySingleMode()**************************************************

   Input		: A 2D character array of the location of the computer boats.
   Output		: The current status of the boats & corresponding grid.
   Returns		: The number of moves it takes to sink all 5 boats.

   Description: This is the basic game in single player mode. The 5 boats 
	 are displayed with their status:
		
		"At Large!"		The boat has not been sunk.
		"  SUNK   "		The boat has been sunk.

	 Also, the grid of the current status of the player is shown - to include
	 all hits, misses & known ships destroyed.*/
int PlaySingleMode(char p[GRIDSIZE][GRIDSIZE])
{
	int col=0, moves=0;
	char row = 'A';
	char grid[GRIDSIZE][GRIDSIZE];
	int carrierHits=0, battleshipHits=0, cruiserHits=0, submarineHits=0, 
		destroyerHits=0;
	bool carrierSunk = false, battleshipSunk = false, cruiserSunk = false,
		submarineSunk = false, destroyerSunk = false;
	 
	// Initialize guessing grid
	for(int i=0; i<GRIDSIZE; i++)
		for(int j=0; j<GRIDSIZE; j++)
			grid[i][j] = '-';
	
	//PrintBoard(p);/////////////need to delete when submitted.....//////
	PrintBoard(grid);
	
	// Play the game.
	while(!carrierSunk||!battleshipSunk||!cruiserSunk||!submarineSunk||
		!destroyerSunk)
	{
		//Asks User for Coordinates of their choice.
		//Also retrieves next coordinate from the user after each move.
		cout << "\n\nPlease enter your coordinates: ";
		cin >> row;
		row = toupper(row);
		cin >> col;
		
	// Make sure the coordinate is valid.
	/*if((col < 0)||(col > 10))
	{
		 cout << "Sorry, but " << (col,row) << " is out of target range.";
	}
	*/
	//Clears Previos System Screen For Visual Appearance.
	system("cls");
	
	
	//Prints out the title again and the current status of the targets/boats.
	//This is represented either by "At Large" or "Sunk".
	cout << "						 B A T T L E S H I P\n\n";
	cout << "ENEMY  :  Aircraft Carrier   Battleship   Cruiser";  
	cout << "   Submarine   Destroyer" << endl;
	cout << setw(7) << "	   ----------------------------------------------";		
	cout << "-----------------------" << endl;
	cout << "STATUS :\n\n";

	// Update Grid display as "HIT" or "MISS"
	if (p[int(row-'A')][col-1] == 'A')//Marks a "A" on Grid when--
	{								  //--Aircraft carrier gets hit.
		grid[int(row-'A')][col-1] = 'A'; 
		carrierHits++;				  
	}

	if(p[int(row-'A')][col-1] == 'B') //Marks a "B" on Grid when-- 
	{								 //--Battleship gets hit.
		grid[int(row-'A')][col-1] = 'B';							  
		battleshipHits++;	  
	}

	if(p[int(row-'A')][col-1] == 'S') //Marks a "S" on Grid when submarine is hit.
	{
		grid[int(row-'A')][col-1] = 'S';
		submarineHits++;
	}
	if(p[int(row-'A')][col-1] == 'C') //Marks a "C" on Grid when cruiser is hit.
	{
		grid[int(row-'A')][col-1] = 'C';
		cruiserHits++;
	}

	if(p[int(row-'A')][col-1] == 'D') //Marks a "D" on Grid when destroyer is hit.
	{
		grid[int(row-'A')][col-1] = 'D';
		destroyerHits++;  
	}
	
	if(p[int(row-'A')][col-1] == '-')
	{
		grid[int(row-'A')][col-1] = 'M'; //Marks a "M" on Grid as a Miss.
		cout << "\n Target missed...Try Another Location!\n\n";
	}
	else if(p[int(row-'A')][col-1] == '-')
	{
		grid[int(row-'A')][col-1] = '*'; //Marks a "*" on Grid as a Hit.
		cout << "\n Target Hit!...Great Shot!\n\n";
	}

	// Check to see if any boats are sunk.
	if(carrierHits == 5)
	{
		carrierSunk = true;
		cout << "...You Sank My Aircraft Carrier!";
	}
	if(battleshipHits == 4)
	{
		battleshipSunk = true;
		cout << "...You Sank My Battleship!";
	}
	if(cruiserHits == 3)
	{
		cruiserSunk = true;
		cout << "...You Sank My Cruiser!";
	}
	if(submarineHits == 3)
	{
		submarineSunk = true;
		cout << "...You Sank My Submarine!";
	}
	if(destroyerHits == 2)
	{
		destroyerSunk = true;
		cout << "...You Sank My Destroyer!";
	}
	
	//Prints current Grid status.
	PrintBoard(grid);
	
	//Updates moves as each is made.
	moves++;
	cout << "\nCurrent Move: " << moves;
	


	}//end of while loop
	// Return the number of moves taken to win the game.
	
	return (moves);
	

} // end of PlaySingleMode()***************************************************



// Function: SetParticularBoat()***********************************************
//
//   Input		: A 2D char array of the grid to set the boat
//				  An integer, ship_size, representing the size
//				  A character representing the type of boat.
// 
//			Each correspond to the MB game:
//
//					Boat					Size	char
//				   -----------------------------------------
//					Aircraft Carrier		  5		 'A'
//					Battleship				  4		 'B'
//					Submarine				  3		 'S'
//					Cruiser					  3		 'C'
//					Destroyer				  2		 'D'
//
//   Output		: None
//   Returns	: Nothing
//
//   Description: This function checks the passed grid for the existence
//				  of other boats, and if there is no collision, places
//				  the boats in a random spot, extending randomly between
//				  horizontal and vertical placement.
void SetParticularBoat(char g[GRIDSIZE][GRIDSIZE], int ship_size, char boat)
{
	bool placementFailure = true;
	char startingRow = 'A';
	int startingCol = 0;
	direction d;

	while(placementFailure)
	{
		startingRow = rand()%GRIDSIZE;
		if(startingRow > GRIDSIZE-ship_size)
		{
			d = EXPAND_ROW;
			startingCol = rand()%(GRIDSIZE-ship_size);
		}
		else
		{
			startingCol= rand()%GRIDSIZE;
			if(startingCol > GRIDSIZE-ship_size)
				d = EXPAND_COL;
			else
				d = (rand()%2)==0?EXPAND_ROW:EXPAND_COL;
		}
		// Assume placement will be OK.
		placementFailure = false;

		// Now check to see if boat can be placed.
		for(int i=0; i<ship_size; i++)
		{
			if(d==EXPAND_ROW && g[startingRow][startingCol+i] != '-')
				placementFailure = true;
			else if(d==EXPAND_COL && g[startingRow+i][startingCol] != '-')
				placementFailure = true;
		}
		// If there was not a placement failure, set the boat
		if(!placementFailure)
		{
			for(int i=0; i<ship_size; i++)
			{
				if(d==EXPAND_ROW)
					g[startingRow][startingCol+i] = boat;
				else
					g[startingRow+i][startingCol] = boat;
			}
		}
	} // end of while to set boat
} // end of SetParticularBoat()************************************************


//cout << "Would you like to continue on to play the game Battleship? <Y/N>: ";
//		cin >> answer;
//		answer = toupper(answer);
//		while(answer != 'N')
//		{
//			return true;
//		}


*** MOD EDIT: Why are code tags so #@^&$%@#^&$ difficult to grasp??? ***
*** :code: ***

This post has been edited by JackOfAllTrades: 07 December 2009 - 01:14 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Battleship Game Help in C++

#2 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: Battleship Game Help in C++

Posted 07 December 2009 - 01:53 PM

One reason why you don't get replies is because the code is long. People don't want to take the time to read all of it. If you could point out specific problem sections and what is supposed to happen that would help.
Was This Post Helpful? 0
  • +
  • -

#3 dfournie  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 21
  • Joined: 22-September 09

Re: Battleship Game Help in C++

Posted 07 December 2009 - 08:50 PM

View Posteker676, on 7 Dec, 2009 - 12:53 PM, said:

One reason why you don't get replies is because the code is long. People don't want to take the time to read all of it. If you could point out specific problem sections and what is supposed to happen that would help.



Well i sort of did, but i just kind of figured that if someone wanted to helpme then they would need the code to see where i wen wrong..sorry for such the long code everyone!

here is where im having trouble..In the PlaySingleMode Function()

Basically how do i
1.) show the status of the ships in the PlaySingleMode() function?..when if you run the program..the menu deal at the top...the one with ENEMY: and STATUS:? I was going to use AT LARGE! and SUNK! for the status.
but how do i do it?
2.) When a ship is hit it is supposed to put an "*" on the screen/Grid..it only puts the " " letter of the boat hit, which isnt supposed to be displayed until it is sunk, only the asterick is.?

here is the code..but the whole function i need help in as well..sorry if it long but i figure u need it to help..Thanks for any replies

int PlaySingleMode(char p[GRIDSIZE][GRIDSIZE])
{
	int col=0, moves=0;
	char row = 'A';
	char grid[GRIDSIZE][GRIDSIZE];
	int carrierHits=0, battleshipHits=0, cruiserHits=0, submarineHits=0, 
		destroyerHits=0;
	bool carrierSunk = false, battleshipSunk = false, cruiserSunk = false,
		submarineSunk = false, destroyerSunk = false;
	 
	// Initialize guessing grid
	for(int i=0; i<GRIDSIZE; i++)
		for(int j=0; j<GRIDSIZE; j++)
			grid[i][j] = '-';
	
	//PrintBoard(p);/////////////need to delete when submitted.....//////
	PrintBoard(grid);
	
	// Play the game.
	while(!carrierSunk||!battleshipSunk||!cruiserSunk||!submarineSunk||
		!destroyerSunk)
	{
		//Asks User for Coordinates of their choice.
		//Also retrieves next coordinate from the user after each move.
		cout << "\n\nPlease enter your coordinates: ";
		cin >> row;
		row = toupper(row);
		cin >> col;
		
	// Make sure the coordinate is valid.
	/*if((col < 0)||(col > 10))
	{
		 cout << "Sorry, but " << (col,row) << " is out of target range.";
	}
	//rguess >= int('A') && rguess <= int('J')
	*/
	//Clears Previos System Screen For Visual Appearance.
	system("cls");
	
	
	//Prints out the title again and the current status of the targets/boats.
	//This is represented either by "At Large" or "Sunk".
	cout << "						 B A T T L E S H I P\n\n";
	cout << "ENEMY  :  Aircraft Carrier   Battleship   Cruiser";  
	cout << "   Submarine   Destroyer" << endl;
	cout << setw(7) << "	   ----------------------------------------------";		
	cout << "-----------------------" << endl;
	cout << "STATUS :\n\n";

	// Update Grid display as "HIT" or "MISS"
	if (p[int(row-'A')][col-1] == 'A')//Marks a "A" on Grid when--
	{								  //--Aircraft carrier gets hit.
		grid[int(row-'A')][col-1] = 'A'; 
		carrierHits++;				  
	}

	if(p[int(row-'A')][col-1] == 'B') //Marks a "B" on Grid when-- 
	{								 //--Battleship gets hit.
		grid[int(row-'A')][col-1] = 'B';							  
		battleshipHits++;	  
	}

	if(p[int(row-'A')][col-1] == 'S') //Marks a "S" on Grid when submarine is hit.
	{
		grid[int(row-'A')][col-1] = 'S';
		submarineHits++;
	}
	if(p[int(row-'A')][col-1] == 'C') //Marks a "C" on Grid when cruiser is hit.
	{
		grid[int(row-'A')][col-1] = 'C';
		cruiserHits++;
	}

	if(p[int(row-'A')][col-1] == 'D') //Marks a "D" on Grid when destroyer is hit.
	{
		grid[int(row-'A')][col-1] = 'D';
		destroyerHits++;  
	}
	
	if(p[int(row-'A')][col-1] == '-')
	{
		grid[int(row-'A')][col-1] = 'M'; //Marks a "M" on Grid as a Miss.
		cout << "\n Target missed...Try Another Location!\n\n";
	}
	else if(p[int(row-'A')][col-1] == '-')
	{
		grid[int(row-'A')][col-1] = '*'; //Marks a "*" on Grid as a Hit.
		cout << "\n Target Hit!...Great Shot!\n\n";
	}

	// Check to see if any boats are sunk.
	if(carrierHits == 5)
	{
		carrierSunk = true;
		cout << "...You Sank My Aircraft Carrier!";
	}
	if(battleshipHits == 4)
	{
		battleshipSunk = true;
		cout << "...You Sank My Battleship!";
	}
	if(cruiserHits == 3)
	{
		cruiserSunk = true;
		cout << "...You Sank My Cruiser!";
	}
	if(submarineHits == 3)
	{
		submarineSunk = true;
		cout << "...You Sank My Submarine!";
	}
	if(destroyerHits == 2)
	{
		destroyerSunk = true;
		cout << "...You Sank My Destroyer!";
	}
	
	//Prints current Grid status.
	PrintBoard(grid);
	
	//Updates moves as each move is made.
	moves++;
	cout << "\nCurrent Move: " << moves;
	


	}//end of while loop
	// Return the number of moves taken to win the game.
	
	return (moves);
	

} // end of PlaySingleMode()***************************************************


This post has been edited by dfournie: 07 December 2009 - 08:58 PM

Was This Post Helpful? 0
  • +
  • -

#4 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: Battleship Game Help in C++

Posted 08 December 2009 - 12:39 AM

View Postdfournie, on 7 Dec, 2009 - 09:50 PM, said:

Basically how do i
1.) show the status of the ships in the PlaySingleMode() function?..when if you run the program..the menu deal at the top...the one with ENEMY: and STATUS:? I was going to use AT LARGE! and SUNK! for the status.
but how do i do it?

2.) When a ship is hit it is supposed to put an "*" on the screen/Grid..it only puts the " " letter of the boat hit, which isnt supposed to be displayed until it is sunk, only the asterick is.?


You're right. I need the code in order to see where the problem might be. It's not too long.

Here's what I would try, to solve your first issue:
	//Prints out the title again and the current status of the targets/boats.
	//This is represented either by "At Large" or "Sunk".
	cout << "						 B A T T L E S H I P\n\n";
	cout << "ENEMY  :  Aircraft Carrier   Battleship   Cruiser";  
	cout << "   Submarine   Destroyer" << endl;
	cout << setw(7) << "	   ----------------------------------------------";		
	cout << "-----------------------" << endl;
	cout << "STATUS :\n\n";
//I'd do something like this. Use "\t" for tabs, for easier formatting.
//then you can use if statements here. Like if your battleship is full (maybe 
//do a search of the entire board to see how many B's it contains? Or whenever
//a new B is printed, increment BattleshipCounter. When it gets to 10, the number
//of letters in battleship, then set bool battleshipSunk to true. Use functions
//for this. Then when you get to THIS part of the code, do this for each ship:
	  if(battleshipSunk){
	  cout <<"\t\tSUNK!";
	  }
	  else {
	  cout <<"\t\tAT LARGE!";
	  }
	   //I didn't test it. I'm pretty sure it will work though. Good luck! :)


//see how this (tested) code lines up so neatly when the program is run? 
	cout << "						 B A T T L E S H I P\n\n";
	cout << "ENEMY:\t\tAircraft Carrier   Battleship   Cruiser";  
	cout << "   Submarine   Destroyer" << endl;
	cout << setw(7) << "	   ----------------------------------------------";		
	cout << "-----------------------" << endl;
	cout << "STATUS:";

	  cout <<"\t\tSUNK!";//lines up with aircraft carrier


Your second issue seems to be here (notice the if statement and the else if statement in particular).

	if(p[int(row-'A')][col-1] == '-')
	{
		grid[int(row-'A')][col-1] = 'M'; //Marks a "M" on Grid as a Miss.
		cout << "\n Target missed...Try Another Location!\n\n";
	}
	else if(p[int(row-'A')][col-1] == '-') //um, didn't you just say that?
	{
		grid[int(row-'A')][col-1] = '*'; //Marks a "*" on Grid as a Hit.
		cout << "\n Target Hit!...Great Shot!\n\n";
	}

Was This Post Helpful? 0
  • +
  • -

#5 Guest_prof*


Reputation:

Re: Battleship Game Help in C++

Posted 13 March 2010 - 12:11 PM

Did you get the base code as part of the assignment, and now you are trying to add 2 player mode? Do you have the original code? Thanks
Was This Post Helpful? 0

Page 1 of 1