Position.java
1 package hlt; 2 3 import java.util.ArrayList; 4 import java.util.Collection; 5 6 public class Position { 7 public final int x; 8 public final int y; 9 10 public Position(final int x, final int y) { 11 this.x = x; 12 this.y = y; 13 } 14 15 public Position directionalOffset(final Direction d) { 16 final int dx; 17 final int dy; 18 19 switch (d) { 20 case NORTH: 21 dx = 0; 22 dy = -1; 23 break; 24 case SOUTH: 25 dx = 0; 26 dy = 1; 27 break; 28 case EAST: 29 dx = 1; 30 dy = 0; 31 break; 32 case WEST: 33 dx = -1; 34 dy = 0; 35 break; 36 case STILL: 37 dx = 0; 38 dy = 0; 39 break; 40 default: 41 throw new IllegalStateException("Unknown direction " + d); 42 } 43 44 return new Position(x + dx, y + dy); 45 } 46 47 /** 48 * Does not normalize the position 49 * @return The position at offset (dx, dy) from this position 50 */ 51 public Position offset(final int dx, final int dy) { 52 return new Position(x + dx, y + dy); 53 } 54 55 /** 56 * Does not normalize the position 57 * @return A collection of the 4 positions adjacent to this position 58 */ 59 public Collection<Position> adjacentPositions(){ 60 ArrayList<Position> surrounding = new ArrayList<>(); 61 for (Direction d : Direction.ALL_CARDINALS){ 62 surrounding.add(directionalOffset(d)); 63 } 64 return surrounding; 65 } 66 67 @Override 68 public boolean equals(Object o) { 69 if (this == o) return true; 70 if (o == null || getClass() != o.getClass()) return false; 71 72 Position position = (Position) o; 73 74 if (x != position.x) return false; 75 return y == position.y; 76 } 77 78 @Override 79 public int hashCode() { 80 int result = x; 81 result = 31 * result + y; 82 return result; 83 } 84 85 @Override 86 public String toString() { 87 return "(" + x + ", " + y + ")"; 88 } 89 }