package jrummikub.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Random; /** * StoneHeap creates all {@link Stone}s for a game, manages them and allows * players to draw one or more random Stones. */ public class StoneHeap implements Serializable { private static final long serialVersionUID = -5247740086907775125L; ArrayList heap; private Random generator = new Random(); /** * Creates 106 Stones according to standard rules * * @param gameSettings * (for number of sets/jokers, colors etc.) * */ public StoneHeap(GameSettings gameSettings) { heap = new ArrayList(); for (int i = 1; i <= gameSettings.getHighestValue(); i++) { for (int j = 0; j < gameSettings.getStoneSetNumber(); j++) { for (StoneColor c : gameSettings.getStoneColors()) { heap.add(new Stone(i, c)); } } } // Joker ArrayList jokerColors = new ArrayList( Arrays.asList(StoneColor.values())); jokerColors.retainAll(gameSettings.getStoneColors()); if (jokerColors.size() >= 4) { StoneColor temp = jokerColors.get(1); jokerColors.set(1, jokerColors.get(3)); jokerColors.set(3, temp); } int jokersLeft = gameSettings.getJokerNumber(); done: while (true) { for (StoneColor c : jokerColors) { if (jokersLeft == 0) break done; heap.add(new Stone(c)); jokersLeft--; } } } /** * Removes random {@link Stone} from the heap and returns it * * @return the drawn stone */ public Stone drawStone() { if (heap.isEmpty()) { return null; } return heap.remove(generator.nextInt(heap.size())); } /** * Removes several {@link Stone}s from the heap and returns them * * @param number * number of requested Stones * @return list of drawn stones */ public List drawStones(int number) { List drawnStones = new ArrayList(); number = Math.min(number, heap.size()); for (int i = 0; i < number; i++) { drawnStones.add(drawStone()); } return drawnStones; } /** * Get the number of stones left * * @return number of stones on the heap */ public int getSize() { return heap.size(); } /** * Put stones back on the heap * * @param stones * collection of stones to put back */ public void putBack(Collection stones) { heap.addAll(stones); } }