-
Notifications
You must be signed in to change notification settings - Fork 0
/
grid.cpp
96 lines (78 loc) · 1.54 KB
/
grid.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
#include <iostream>
#include "grid.h"
#include "ship.h"
using namespace std;
// Constructor
battlefield::battlefield()
{
// There are no ships in the battlefield initially.
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
grid[i][j] = '_';
for(int i=0;i<5;i++)
{
ship_rows[i] = -1;
ship_cols[i] = -1;
}
count = 0;
}
// Method to display the battlefield
void battlefield::display()
{
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
cout<<grid[i][j]<<" ";
cout<<"\n";
}
}
void battlefield::set(char c, int row, int col)
{
grid[row][col] = c;
}
// Get content
char battlefield::content(int row, int col)
{
if((row<0)||(col<0)||(row>9)||(col>9))
return '*';
return grid[row][col];
}
int battlefield::get_count()
{
return count;
}
void battlefield::decrCount()
{
--count;
}
// Place ship
bool battlefield::place_ship(char symbol, int row, int col, int size, char hv)
{
if(hv=='V') // place vertically
{
if(size+row>10)
return false;
for(int i=0;i<size;i++)
if(content(row+i,col)!='_')
return false;
// Space available. Place the ship in the battlefield
for(int i=0;i<size;i++)
grid[row+i][col] = symbol;
count++;
return true;
}
else
{
// Place horizontally
if(size+col>10)
return false;
for(int i=0;i<size;i++)
if(content(row,col+i)!='_')
return false;
// Space available. Place the ship in the battlefield
for(int i=0;i<size;i++)
grid[row][col+i] = symbol;
count++;
return true;
}
}