/
WinCondition.java
55 lines (43 loc) · 1.75 KB
/
WinCondition.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
package io.karniushin.tictactoe.core.service.handler.rule.condition;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import io.karniushin.tictactoe.core.domain.WinResult;
public abstract class WinCondition {
protected WinResult.WinResultType type;
public Optional<WinResult> check(final CheckParams params) {
final short search = params.getSearch();
final int threshold = params.getThreshold();
List<WinResult.Coords> winningLine = new ArrayList<>();
winningLine.add(new WinResult.Coords(params.getX(), params.getY()));
NeighbourDetector before = before(params);
while (before.hasNext()) {
winningLine.add(0, before.next());
if (winningLine.size() == threshold) {
return Optional.of(new WinResult(type, search, winningLine));
}
}
NeighbourDetector after = after(params);
while (after.hasNext()) {
winningLine.add(after.next());
if (winningLine.size() == threshold) {
return Optional.of(new WinResult(type, search, winningLine));
}
}
return Optional.empty();
}
protected abstract NeighbourDetector before(CheckParams params);
protected abstract NeighbourDetector after(CheckParams params);
protected abstract static class NeighbourDetector implements Iterator<WinResult.Coords> {
private final short[][] board;
private final short search;
public NeighbourDetector(short[][] board, short search) {
this.board = board;
this.search = search;
}
protected boolean matches(int i, int j) {
return board[i][j] == search;
}
}
}