Spiral.java
1 package hlt; 2 3 import java.util.ArrayList; 4 import java.util.Iterator; 5 6 public class Spiral implements Iterator<Position> { 7 8 private Iterator<Position> iterator; 9 10 /** 11 * Creates a counter-clockwise spiral iterator of positions in a grid of dimension: 12 * dimension x dimension centered at origin 13 */ 14 public Spiral(GameMap gameMap, Position origin, int dimension){ 15 ArrayList<Position> positions = new ArrayList<>(); 16 Position currentPosition = origin; 17 positions.add(currentPosition); 18 int sign = 1; 19 for (int i = 1; i <= dimension; i++){ 20 for (int xStep = 1; xStep <= i; xStep++){ 21 currentPosition = currentPosition.offset(sign, 0); 22 currentPosition = gameMap.normalize(currentPosition); 23 positions.add(currentPosition); 24 } 25 for (int yStep = 1; yStep <= i; yStep++){ 26 currentPosition = currentPosition.offset(0, sign); 27 currentPosition = gameMap.normalize(currentPosition); 28 positions.add(currentPosition); 29 } 30 sign *= -1; 31 } 32 iterator = positions.subList(0, dimension * dimension).iterator(); 33 } 34 35 @Override 36 public boolean hasNext() { 37 return iterator.hasNext(); 38 } 39 40 //TODO: compute next position each call to next() rather than pre-computing the entire iterator 41 @Override 42 public Position next() { 43 return iterator.next(); 44 } 45 }