-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShip.java
More file actions
97 lines (86 loc) · 1.86 KB
/
Ship.java
File metadata and controls
97 lines (86 loc) · 1.86 KB
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
//Ship class
public class Ship
{
private int length;
private char direction;
private boolean sunk;
private int row;
private int column;
private int life;
private int [][] shipLocations;
public Ship(int len, char dir, int row_in, int column_in)
{
length = len;
life = len;
direction = dir;
row = row_in;
column = column_in;
sunk = false;
//will keep track of all locations on the board that the ship occupies
shipLocations = new int [len][2];
if(dir == 'H')
{
for(int i = 0; i < len; i++)
{
for(int j = 0; j < 2; j++)
{
if(j == 0)
shipLocations[i][j] = row;
else
shipLocations[i][j] = column + i;
}
}
}
else if(dir == 'V')
{
for(int i = 0; i < len; i++)
{
for(int j = 0; j < 2; j++)
{
if(j == 0)
shipLocations[i][j] = row + i;
else
shipLocations[i][j] = column;
}
}
}
}
public int [][] getLocations()
{
return shipLocations;
}
public int getRow()
{
return row;
}
public int getCol()
{
return column;
}
public boolean isHit(int col, int row)
{
for(int i = 0; i < length; i++)
{
if(shipLocations[i][0] == row && shipLocations[i][1] == col)
{
System.out.println("Hit!");
hit();
return true;
}
}
return false;
}
public void hit()
{
life--;
if(life == 0)
{
sunk = true;
System.out.println("Sunk opponent's ship of length "+length);
}
}
public boolean isSunk()
{
return sunk;
}
}