-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbattleship.cpp
125 lines (103 loc) · 2.31 KB
/
battleship.cpp
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <iostream>
#include <ctime>
#include <stdlib.h>
using namespace std;
const int rows = 5;
const int cols = 5;
int MaxShips = 3;
int matrix[rows][cols];
void Clear()
{
for(int i=0; i < rows; i++)
{
for(int j=0; j < cols; j++)
{
matrix[i][j] = 0;
}
}
}
void Show()
{
for(int i=0; i < rows; i++)
{
for(int j=0; j < cols; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
void SetShips()
{
int s = 0;
while(s < MaxShips)
{
int x = rand() % rows;
int y = rand() % cols;
if(matrix[x][y] != 1)
{
s++;
matrix[x][y] = 1;
}
}
}
int NumberOfShips()
{
int c=0;
for(int i=0; i < rows; i++)
{
for(int j=0; j < cols; j++)
{
if(matrix[i][j] == 1)
{
c++;
}
}
}
return c;
}
bool Attack(int x, int y)
{
if(matrix[x][y] == 1)
{
matrix[x][y] = 2;
return true;
}
}
int main()
{
srand(time(NULL));
Clear();
cout << "Welcome to this simple game of battleships. " << endl;
cout << "The computer has hidden 3 ships on a 5 x 5 board \n";
Show();
cout << "The board shows 0's where no ship is, the computer will hide the ships and they will show as 1's and when sunk 2's. " << endl;
cout << "-------------------------------- Randomly hiding ships --------------------------------" << endl;
SetShips();
int pos1,pos2;
char prompt;
while(1)
{
cout << "Please enter the location of your guess (row then column, numbers 0-4 e.g 0 0 is the first square): ";
cin >> pos1 >> pos2;
if(Attack(pos1,pos2))
{
cout << "You sunk my Battleship!" << endl;
}else{
cout << "Sorry there is no ship at this location, please try again" << endl;
}
cout << "Number of ships remaining: " << NumberOfShips() << endl;
if (NumberOfShips() == 0){
break;
}
cout << "Do you want to surrender (y/n)? ";
cin >> prompt;
if(prompt == 'y')
{
break;
}
}
cout << "Game over!" << endl;
Show();
return 0;
}