-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGRID.java
More file actions
289 lines (261 loc) · 9.9 KB
/
GRID.java
File metadata and controls
289 lines (261 loc) · 9.9 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
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class GRID {
private final String username;
private final int size;
private final List<SHIP> ships;
private final int[][] shipIndexAtCell;
private final boolean[][] shotsTaken;
private int placedShipCells;
private int hitShipCells;
public GRID(String username, int size) {
if (username == null || username.trim().isEmpty()) {
throw new IllegalArgumentException("Username must not be empty.");
}
if (size < 2 || size > 26) {
throw new IllegalArgumentException("Grid size must be between 2 and 26.");
}
this.username = username.trim();
this.size = size;
this.ships = new ArrayList<SHIP>();
this.shipIndexAtCell = new int[size][size];
this.shotsTaken = new boolean[size][size];
this.placedShipCells = 0;
this.hitShipCells = 0;
}
public String getUsername() {
return username;
}
public int getSize() {
return size;
}
public List<SHIP> getShips() {
return Collections.unmodifiableList(ships);
}
public SHIP getShipAt(Coordinate c) {
Coordinate checked = Coordinate.validateBounds(c, size);
int shipIndex = shipIndexAtCell[checked.getRow()][checked.getColumn()];
if (shipIndex == 0) {
return null;
}
return ships.get(shipIndex - 1);
}
public boolean canPlaceShip(Coordinate start, Orientation orientation, int length) {
List<Coordinate> cells;
try {
cells = getShipCells(start, orientation, length);
} catch (IllegalArgumentException ex) {
return false;
}
for (Coordinate c : cells) {
if (shipIndexAtCell[c.getRow()][c.getColumn()] > 0) {
return false;
}
if (hasAdjacentShip(c)) {
return false;
}
}
return true;
}
public SHIP placeShip(String shipName, Coordinate start, Orientation orientation, int length) {
if (length < 2) {
throw new IllegalArgumentException("Ship length must be at least 2.");
}
List<Coordinate> cells = getShipCells(start, orientation, length);
if (!canPlaceShip(start, orientation, length)) {
throw new IllegalArgumentException("Ship placement collides or touches another ship.");
}
SHIP ship = new SHIP(shipName, cells);
ships.add(ship);
int shipIndex = ships.size();
for (Coordinate c : cells) {
shipIndexAtCell[c.getRow()][c.getColumn()] = shipIndex;
}
placedShipCells += cells.size();
return ship;
}
public void placeShipsRandomly(List<ShipType> fleetDefinition, long seed) {
if (fleetDefinition == null || fleetDefinition.isEmpty()) {
throw new IllegalArgumentException("Fleet definition must not be empty.");
}
clearShips();
Random random = new Random(seed);
for (ShipType type : fleetDefinition) {
for (int i = 1; i <= type.getCount(); i++) {
boolean placed = false;
int tries = 0;
while (!placed && tries < 10_000) {
tries++;
Orientation orientation = random.nextBoolean() ? Orientation.HORIZONTAL : Orientation.VERTICAL;
int row = random.nextInt(size);
int col = random.nextInt(size);
Coordinate start = new Coordinate(row, col);
if (canPlaceShip(start, orientation, type.getLength())) {
placeShip(type.getName() + " #" + i, start, orientation, type.getLength());
placed = true;
}
}
if (!placed) {
throw new IllegalStateException("Unable to place all ships for " + type.getName() + ".");
}
}
}
}
public boolean placeShipRandomly(String shipName, int length, Random random, int maxTries) {
if (shipName == null || shipName.trim().isEmpty()) {
throw new IllegalArgumentException("Ship name must not be empty.");
}
if (length < 2) {
throw new IllegalArgumentException("Ship length must be at least 2.");
}
if (random == null) {
throw new IllegalArgumentException("Random must not be null.");
}
if (maxTries < 1) {
throw new IllegalArgumentException("maxTries must be at least 1.");
}
for (int tries = 0; tries < maxTries; tries++) {
Orientation orientation = random.nextBoolean() ? Orientation.HORIZONTAL : Orientation.VERTICAL;
int row = random.nextInt(size);
int col = random.nextInt(size);
Coordinate start = new Coordinate(row, col);
if (canPlaceShip(start, orientation, length)) {
placeShip(shipName, start, orientation, length);
return true;
}
}
return false;
}
public boolean removeShip(String shipName) {
if (shipName == null || shipName.trim().isEmpty()) {
return false;
}
for (int i = 0; i < ships.size(); i++) {
SHIP ship = ships.get(i);
if (ship.getName().equals(shipName.trim())) {
placedShipCells -= ship.getCoordinates().size();
ships.remove(i);
rebuildShipIndexMap();
return true;
}
}
return false;
}
public ShotReport fireAt(Coordinate target) {
Coordinate c = Coordinate.validateBounds(target, size);
if (shotsTaken[c.getRow()][c.getColumn()]) {
return new ShotReport(ShotResult.ALREADY_TARGETED, c, null, false);
}
shotsTaken[c.getRow()][c.getColumn()] = true;
int shipIndex = shipIndexAtCell[c.getRow()][c.getColumn()];
if (shipIndex == 0) {
return new ShotReport(ShotResult.MISS, c, null, false);
}
SHIP ship = ships.get(shipIndex - 1);
ship.registerHit(c);
hitShipCells++;
if (ship.isSunk()) {
boolean won = isAllShipsSunk();
return new ShotReport(ShotResult.SUNK, c, ship.getName(), won);
}
return new ShotReport(ShotResult.HIT, c, null, false);
}
public boolean isAllShipsSunk() {
return placedShipCells > 0 && hitShipCells >= placedShipCells;
}
public boolean hasShotAt(Coordinate c) {
Coordinate checked = Coordinate.validateBounds(c, size);
return shotsTaken[checked.getRow()][checked.getColumn()];
}
public boolean hasShipAt(Coordinate c) {
Coordinate checked = Coordinate.validateBounds(c, size);
return shipIndexAtCell[checked.getRow()][checked.getColumn()] > 0;
}
public String renderOwnBoard() {
return renderBoard(true);
}
public String renderOpponentView() {
return renderBoard(false);
}
private String renderBoard(boolean ownBoard) {
StringBuilder sb = new StringBuilder();
sb.append(" ");
for (int col = 1; col <= size; col++) {
if (col < 10) {
sb.append(" ");
}
sb.append(col).append(" ");
}
sb.append('\n');
for (int row = 0; row < size; row++) {
sb.append((char) ('A' + row)).append(" ");
for (int col = 0; col < size; col++) {
boolean shot = shotsTaken[row][col];
boolean ship = shipIndexAtCell[row][col] > 0;
char symbol;
if (shot && ship) {
symbol = 'X';
} else if (shot) {
symbol = 'o';
} else if (ownBoard && ship) {
symbol = 'S';
} else {
symbol = '.';
}
sb.append(" ").append(symbol).append(" ");
}
sb.append('\n');
}
return sb.toString();
}
private List<Coordinate> getShipCells(Coordinate start, Orientation orientation, int length) {
List<Coordinate> cells = new ArrayList<Coordinate>();
for (int i = 0; i < length; i++) {
int row = start.getRow() + (orientation == Orientation.VERTICAL ? i : 0);
int column = start.getColumn() + (orientation == Orientation.HORIZONTAL ? i : 0);
Coordinate c = new Coordinate(row, column);
cells.add(Coordinate.validateBounds(c, size));
}
return cells;
}
private boolean hasAdjacentShip(Coordinate coordinate) {
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int rr = coordinate.getRow() + dr;
int cc = coordinate.getColumn() + dc;
if (rr < 0 || cc < 0 || rr >= size || cc >= size) {
continue;
}
if (shipIndexAtCell[rr][cc] > 0) {
return true;
}
}
}
return false;
}
private void rebuildShipIndexMap() {
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
shipIndexAtCell[row][col] = 0;
}
}
for (int shipIndex = 0; shipIndex < ships.size(); shipIndex++) {
for (Coordinate c : ships.get(shipIndex).getCoordinates()) {
shipIndexAtCell[c.getRow()][c.getColumn()] = shipIndex + 1;
}
}
}
private void clearShips() {
ships.clear();
placedShipCells = 0;
hitShipCells = 0;
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
shipIndexAtCell[row][col] = 0;
shotsTaken[row][col] = false;
}
}
}
}