1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
cout << "This is your game board. A ship taking up one spot will be placed randomly on the board. You have three guesses to find the ship. Good luck!\n";
//Creates the game board
string board[7][7] = { { "0 ", "1 ", "2 ", "3 ", "4 ", "5 ", "6 " },
{ "1 ", "O ", "O ", "O ", "O ", "O ", "O " },
{ "2 ", "O ", "O ", "O ", "O ", "O ", "O " },
{ "3 ", "O ", "O ", "O ", "O ", "O ", "O " },
{ "4 ", "O ", "O ", "O ", "O ", "O ", "O " },
{ "5 ", "O ", "O ", "O ", "O ", "O ", "O " },
{ "6 ", "O ", "O ", "O ", "O ", "O ", "O " } };
//Declares the variables for the coordinates of the ship and the coordinates fired at
int row_of_ship, column_of_ship, row, column;
//Randomly initializes the coordinates of the ship
row_of_ship = rand() % 7 + 1;
column_of_ship = rand() % 7 + 1;
//Prints the game board
for (int i = 0; i <= 7; i++)
{
for (int j = 0; j <= 6; j++)
{
cout << board[i][j];
}
cout << endl;
}
//Used to count the number of turns
int l = 1;
//Used to begin each turn
A:
//Limits the number of turns
while (l <= 3)
{
//Inputs the row number
cout << "\nEnter the row number you want to attack: ";
cin >> row;
//Checks if the input is valid
if (row >= 7 || row <= 0)
{
cout << "\nThat's not even in the ocean, try again.";
//Uses a turn
l = l + 1;
//Begins a new turn
goto A;
}
else
{
//Inputs the column the player wants to attack.
cout << "\nEnter the column number you want to attack: ";
cin >> column;
//Checks if input is valid
if (column >= 7 || column <= 0)
{
cout << "\nThat's not even in the ocean, try again.";
l = l + 1;
goto A;
}
//Checks if the attack hits the ship.
else if (row_of_ship == row && column_of_ship == column)
{
cout << "Congratulations you defeated the enemy. That was some good shooting.";
}
else
{
if (l != 3)
{
cout << "You missed the ship, but you still have " << 3 - l << " shots left. Try again.";
//Sets the location to attacked
board[row][column] = "X ";
//Prints out the board
for (int i = 0; i <= 7; i++)
{
for (int j = 0; j <= 6; j++)
{
cout << board[i][j];
}
cout << endl;
}
goto A;
}
else
{
cout << "That was your last shot. The enemy has bested you.";
}
}
}
}
return 0;
}
|