blob: 71bdc51647f9548d71569911d21d44d4fb7275b7 (
plain)
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
|
package fr.umlv.java.wallj.board;
import fr.umlv.java.wallj.block.BlockType;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.ListIterator;
import java.util.stream.Collectors;
/**
* Board deserializer.
*
* @author Pacien TRAN-GIRARD
*/
public final class BoardParser {
private BoardParser() {
// static class
}
private static Board buildBoard(List<List<BlockType>> map) {
if (!Matrix.isShapeValid(map)) throw new IllegalArgumentException("Board must be rectangular.");
Board.Builder b = new Board.Builder(Matrix.getWidth(map), Matrix.getHeight(map));
for (ListIterator<List<BlockType>> line = map.listIterator(); line.hasNext(); )
for (ListIterator<BlockType> block = line.next().listIterator(); block.hasNext(); )
b.setBlockTypeAt(TileVec2.of(block.nextIndex(), line.previousIndex()), block.next());
return b.build();
}
private static BlockType parseChar(int c) {
switch (c) {
case ' ':
return BlockType.FREE;
case 'W':
return BlockType.WALL;
case 'T':
return BlockType.TRASH;
case 'G':
return BlockType.GARBAGE;
default:
return null;
}
}
private static List<BlockType> parseLine(String line) {
return line.chars()
.mapToObj(BoardParser::parseChar)
.collect(Collectors.toList());
}
/**
* Parses a block from a file.
*
* @param filePath path to the map file
* @return the parsed Board
* @throws IOException any IO exception that happened while reading the file
*/
public static Board parse(Path filePath) throws IOException {
return buildBoard(Files.lines(filePath)
.filter(s -> !s.isEmpty())
.map(BoardParser::parseLine)
.collect(Collectors.toList()));
}
}
|