-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShip.java
110 lines (95 loc) · 3.4 KB
/
Ship.java
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
public class Ship {
private int length;
private Point[] shipPoints;
private int hitCount;
private boolean announcedSinking = false;
public Ship(Point origin, boolean isVertical, int length, GameBoard b) {
this.length = length;
// store points that belong to the ship in an array
shipPoints = new Point[length];
// set point of origin
// set additional points based on length and orientation
// vertical ship
if (isVertical) {
if (origin.getRow() + length <= 10) {
for (int i = 0; i < length; i ++) {
b.getGrid()[origin.getRow() + i][origin.getColumn()].setIsShip(true);
this.shipPoints[i] = b.getPoint(origin.getRow() + i, origin.getColumn());
//int index = ((origin.getRow() + i - 1) * 10) + origin.getColumn() - 1;
}
} else {
for (int i = 0; i < length; i ++) {
b.getGrid()[origin.getRow() - i][origin.getColumn()].setIsShip(true);
this.shipPoints[i] = b.getPoint(origin.getRow() - i, origin.getColumn());
}
}
}
// horizontal ship
else {
if (origin.getColumn() + length <= 10) {
for (int i = 0; i < length; i ++) {
b.getGrid()[origin.getRow()][origin.getColumn() + i].setIsShip(true);
this.shipPoints[i] = b.getPoint(origin.getRow(), origin.getColumn() + i);
//int index = ((origin.getRow() + i - 1) * 10) + origin.getColumn() - 1;
}
} else {
for (int i = 0; i < length; i ++) {
b.getGrid()[origin.getRow()][origin.getColumn() - i].setIsShip(true);
this.shipPoints[i] = b.getPoint(origin.getRow(), origin.getColumn() - i);
}
}
}
// perform bounds checking
//add ship to game board
b.addShip(this);
}
public boolean containsPoint(Point p) {
for (Point sp: shipPoints) {
if (p.getRow() == sp.getRow() && p.getColumn() == sp.getColumn()) {
return true;
}
}
return false;
}
public boolean collidesWith(Ship s) {
for (Point sp: s.getPoints()) {
if (this.containsPoint(sp)) {
return true;
}
}
return false;
}
public int getHitCount() {
return hitCount;
}
// when a ship is hit (GameBoard.shotFired()), we will increment the hit count.
public void hit() {
hitCount++;
}
public boolean isSunk() {
if (this.getHitCount() >= length) {
return true;
} else {
return false;
}
}
public Point[] getPoints() {
return shipPoints;
}
public String printPoints() {
String pointList = "Ship of length " + length + ":";
for (Point p: shipPoints) {
int row = p.getRow() - 1;
int col = p.getColumn() - 1;
pointList += " (" + row + ", " + col + ")";
}
pointList += ".";
return pointList;
}
public void announce() {
if (announcedSinking == false && isSunk()) {
System.out.println("You sank a ship of length: " + length);
announcedSinking = true;
}
}
}