-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathLine.java
More file actions
74 lines (64 loc) · 2.27 KB
/
Line.java
File metadata and controls
74 lines (64 loc) · 2.27 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
package domain;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Line {
private final List<Bridge> bridges;
public Line(LadderWidth ladderWidth, Line previousLine) {
this.bridges = createBridges(ladderWidth, previousLine);
}
private List<Bridge> createBridges(LadderWidth ladderWidth, Line previousLine) {
List<Bridge> list = new ArrayList<>();
Random random = new Random();
boolean previousConnected = false;
List<Bridge> previousBridges = null;
if (previousLine != null) {
previousBridges = previousLine.getBridges();
}
for (int i = 0; i < ladderWidth.getValue() - 1; i++) {
boolean connected = determineConnection(previousConnected, random, previousBridges, i);
list.add(Bridge.fromBoolean(connected));
previousConnected = connected;
}
return list;
}
private boolean determineConnection(boolean previousConnected, Random random,
List<Bridge> previousBridges, int index) {
if (previousConnected) {
return false;
}
if (previousBridges != null && previousBridges.get(index) == Bridge.CONNECTED) {
return false;
}
return random.nextBoolean();
}
public List<Bridge> getBridges() {
return bridges;
}
public String draw() {
StringBuilder builder = new StringBuilder();
builder.append("|");
for (Bridge bridge : bridges) {
builder.append(bridge.display());
builder.append("|");
}
return builder.toString();
}
public Position move(Position position) {
int current = position.getValue();
if (canMoveLeft(current)) {
return new Position(current - 1);
}
if (canMoveRight(current)) {
return new Position(current + 1);
}
return position;
}
private boolean canMoveLeft(int current) {
return current > 0 && bridges.get(current - 1) == Bridge.CONNECTED;
}
private boolean canMoveRight(int current) {
int columnCount = bridges.size() + 1;
return current < columnCount - 1 && bridges.get(current) == Bridge.CONNECTED;
}
}