My tutor has given me these steps for one of our end of my year projects I am struggling with c and any help would be appreciated
1) Declare the 2d array (5x5)
2) Initialise the 2d array (put a space in each cell)
3) Randomly generate & store 5 ships in 2d array
4) Ask user to enter their guess (x,y co-ords)
5) Check if it was a hit, miss or a cell already fired upon.
6) Draw the grid to show all events (misses & hits)
7) Have they used their 8 shots yet, if no goto step 4
#include <iostream>
#include <cstdlib>
// Declare constants and map
constunsignedint X = 5;
constunsignedint Y = 5;
constchar SHIP = '#';
constchar HIT = 'X';
constchar MISS = 'O';
typedefchar MAP[Y][X];
int main()
{
// Seed random number generator
srand(time(0));
// Declare a map
MAP MyMap;
// Init map with spaces
for(unsignedint i = 0; i < Y; i++)
for(unsignedint j = 0; j < X; j++)
MyMap[i][j] = ' ';
// Count how many ships have been placed
unsignedint ships_placed = 0;
// Attempt to randomly place the ships
while(ships_placed < 5)
{
unsignedint tempx, tempy;
tempx = tempy = 0;
tempx = rand() % 5;
tempy = rand() % 5;
if(MyMap[tempy][tempx] == ' ')
{
MyMap[tempy][tempx] = SHIP;
ships_placed++;
}
}
// Declare the amount of shots the player has
unsignedint shots_left = 8;
// Declare amount of ships left on the board
unsignedint ships_left = 5;
// Game runs while shots can still be fired
while(shots_left > 0 && ships_left > 0)
{
std::cout << "Please enter x and y coordinates: ";
unsignedint tempx,tempy;
std::cin >> tempx >> tempy;
// Test input for correctess
if(tempx > X-1 || tempy > Y-1)
{
std::cout << "Invalid coordinates, please choose between 0 and 4\n\n";
}
elseif(MyMap[tempy][tempx] == HIT || MyMap[tempy][tempx] == MISS)
{
std::cout << "You have already tried that!\n\n";
}
else
{
// Coordinates are valid, proceed
// Take a shot away
shots_left--;
// Test if coordinates contain a ship
if(MyMap[tempy][tempx] == SHIP)
{
// Update map to show hit
MyMap[tempy][tempx] = HIT;
// Let it be known
std::cout << "You hit!\n\n";
// Take a ship away
ships_left--;
}
else
{
// Update map to show miss
MyMap[tempy][tempx] = MISS;
// Let it be known
std::cout << "You missed!\n\n";
}
// Draw map
for(unsignedint i = 0; i < Y; i++)
{
for(unsignedint j = 0; j < X; j++)
{
// "Hide" the ships
if(MyMap[i][j] == SHIP) std::cout << ' ';
else std::cout << MyMap[i][j];
}
std::cout << "\n";
}
}
}
// The game is over, display results
if(shots_left == 0)
{
std::cout << "You ran out of shots, you lost!\n\n";
}
elseif(ships_left == 0)
{
std::cout << "You destroyed all the ships, congratulations you won!\n\n";
}
// End of program
return 0;
}