aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/fr/umlv/java/wallj/board/BoardConverter.java
blob: 53f11c0f04a31767725826c797b5283b611a742c (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
package fr.umlv.java.wallj.board;

import fr.umlv.java.wallj.block.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Operations of conversion on Board and List of blocks
 * @author Adam NAILI
 */
public final class BoardConverter {
  private BoardConverter() {
  }

  /**
   * Converts a list of Blocks to a Board
   * @param blocks the list of blocks to convert in a board
   * @return the converted board
   */
  public static Board worldToBoard(List<Block> blocks) {
    int width = blocks.stream().map(Block::getTile).mapToInt(TileVec2::getCol).max().orElse(-1) + 1;
    int height = blocks.stream().map(Block::getTile).mapToInt(TileVec2::getRow).max().orElse(-1) + 1;

    Board.Builder builder = new Board.Builder(width, height);
    for (Block block : blocks) {
      builder.setBlockTypeAt(block.getTile(), block.getType());
    }
    return builder.build();
  }

  /**
   * Converts a Board to a list of Blocks
   * @param board the board to convert into a list of blocks
   * @return the list of blocks converted
   */
  public static List<Block> boardToWorld(Board board) {
    int nbRow = board.getDim().getRow();
    int nbCol = board.getDim().getCol();
    ArrayList<Block> blocks = new ArrayList<>(nbCol * nbRow);
    for (int i = 0; i < nbRow; i++) {
      for (int j = 0; j < nbCol; j++) {
        Block block;
        TileVec2 location = TileVec2.of(j, i);
        block = BlockFactory.build(board.getBlockTypeAt(location), location);
        if (block != null) {
          blocks.add(block);
        }
      }
    }
    return blocks;
  }
}