package de.hsfulda.pmuw.oop; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class CellCreator { /** one alive to X dead */ private static final int ALIVE_CELLS_RATIO = 30; private static final int BOARD_SIZE = 500; public static List aliveList = new Random().ints(0, ALIVE_CELLS_RATIO).limit(BOARD_SIZE * BOARD_SIZE) .mapToObj(Integer::valueOf).map(i -> Boolean.valueOf(i == 0)).collect(Collectors.toList()); int calculateNeighbourIndex(List allCells, CgolCell cgolCell, NeighborPosition neighborPosition) { int row = cgolCell.row; int column = cgolCell.column; int size = allCells.size(); int index = neighborPosition.getIndex(row, column, BOARD_SIZE); int finalIndex = (index + size) % size; return finalIndex; } protected void createCells(Collection activeCells, boolean isOptimized) { StateChangeListener changeListener = getChangeListener(activeCells, isOptimized); List allCells = createCells(changeListener); constructGameField(activeCells, isOptimized, allCells); System.out.println(String.format("active cells: %7s", activeCells.size())); System.out.println(String.format("alive cells : %7s", allCells.stream().filter(CgolCell::isAlive).count())); } private StateChangeListener getChangeListener(Collection activeCells, boolean isOptimized) { StateChangeListener changeListener = isOptimized ? nc -> activeCells.add(nc) : nc -> { ; }; return changeListener; } private List createCells(StateChangeListener changeListener) { Iterator iterator = aliveList.iterator(); List allCells = new ArrayList<>(); for (int row = 0; row < BOARD_SIZE; row++) for (int col = 0; col < BOARD_SIZE; col++) allCells.add(new CgolCell(row, col, iterator.next(), changeListener)); System.out.println(String.format("cells created: %7s", allCells.size())); return allCells; } private void constructGameField(Collection activeCells, boolean isOptimized, List allCells) { for (CgolCell cgolCell : allCells) { Set neighbors = Stream.of(NeighborPosition.values()) .map(np -> calculateNeighbourIndex(allCells, cgolCell, np)).map(allCells::get).collect(Collectors.toSet()); cgolCell.setNeighbors(neighbors); if (cgolCell.isAlive()) { if (isOptimized) { activeCells.add(cgolCell); activeCells.addAll(neighbors); } } } if (!isOptimized) { activeCells.addAll(allCells); } } }