Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

#include <iostream>

#include <time.h>
#include <windows.h>

using namespace std;

const int row = 8;


const int col = 8;

int ships = 10;


char table[row][col];

void createships()
{
int x, y;
for (int i = 0; i < 10; i++)
{
x = rand() % 7;
y = rand() % 7;
if (table[x][y] == 'o')
table[x][y] = 'x';
else
i = i - 1;
}
}
void clear()
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
table[i][j] = 'o';
}
}
}
void print()
{
cout << " ";
for (int i = 0; i < col; i++)
{
cout << i << " ";
}
cout << endl;
for (int i = 0; i < row; i++)
{
cout << " ";
cout << i << " ";
for (int j = 0; j < col; j++)
{
if (table[i][j] == 'x')
cout << "o";
else
cout << table[i][j];
cout << " ";
}
cout << endl;
}
}

void fire()
{
int a, b;
int range = 1;

cout << "Ships remain: " << ships << endl;


do
{
cout << "Choose a position to shoot." << endl;
cout << "x axis: ";
cin >> b;
cout << "y axis: ";
cin >> a;

if (a < 0 || a > 7 || b < 0 || b > 7)


{
cout << "Out of range" << endl;
range = 0;
}
else
range = 1;
} while ( table[a][b] == '*' || (range == 0));

if (table[a][b] == 'x')
{
ships = ships - 1;
cout << "One ship has sunk. Congrat!" << endl;
Sleep(2000);
}
table[a][b] = '*';
}
int main()
{
srand(time(NULL));
clear();
createships();
while (ships != 0)
{
cout << "Battle ship" << endl;
cout << "Ships set, let's play!" << endl;
print();
fire();
system("CLS");
}
cout << "You win!" << endl;
}

You might also like