-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.java
More file actions
56 lines (49 loc) · 1.71 KB
/
Board.java
File metadata and controls
56 lines (49 loc) · 1.71 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
import java.util.*;
public final class Board {
private static volatile Board instance;
private final int size;
private final Map<Integer, Entity> entityMap;
private Board(int size, List<Entity> entities) {
this.size = size;
this.entityMap = new HashMap<>();
int last = getLastCell();
for (Entity e : entities) {
// checks if the entity position is valid
validate(e, last);
if (entityMap.containsKey(e.getStart())) {
throw new IllegalArgumentException("Duplicate entity at cell " + e.getStart());
}
entityMap.put(e.getStart(), e);
}
}
private void validate(Entity e, int last) {
if (e.getStart() <= 0 || e.getStart() > last || e.getEnd() <= 0 || e.getEnd() > last) {
throw new IllegalArgumentException("Entity out of bounds");
}
if (e instanceof Snake && e.getEnd() >= e.getStart()) {
throw new IllegalArgumentException("Snake must descend");
}
if (e instanceof Ladder && e.getEnd() <= e.getStart()) {
throw new IllegalArgumentException("Ladder must ascend");
}
}
public static Board getInstance(int size, List<Entity> entities) {
if (instance == null) {
synchronized (Board.class) {
if (instance == null) {
instance = new Board(size, entities);
}
}
}
return instance;
}
public Optional<Entity> getEntityAt(int cell) {
return Optional.ofNullable(entityMap.get(cell));
}
public int getLastCell() {
return size * size;
}
public int getSize() {
return size;
}
}