58 lines
1.8 KiB
Java
58 lines
1.8 KiB
Java
package labyrinth;
|
|
|
|
import io.vavr.collection.Stream;
|
|
import io.vavr.control.Option;
|
|
import lombok.NonNull;
|
|
|
|
import java.util.EnumSet;
|
|
import java.util.Random;
|
|
import java.util.function.UnaryOperator;
|
|
|
|
public enum Direction {
|
|
TOP(position -> position.withY(position.getY() - 1)),
|
|
BOTTOM(position -> position.withY(position.getY() + 1)),
|
|
LEFT(position -> position.withX(position.getX() - 1)),
|
|
RIGHT(position -> position.withX(position.getX() + 1));
|
|
private static final Random random = new Random();
|
|
@NonNull
|
|
private final UnaryOperator<Position> translation;
|
|
|
|
Direction(@NonNull final UnaryOperator<Position> translation) {
|
|
this.translation = translation;
|
|
}
|
|
|
|
public static Direction getRandom() {
|
|
return values()[random.nextInt(4)];
|
|
}
|
|
|
|
public static Option<Direction> getRandomExcluding(@NonNull final EnumSet<Direction> directions) {
|
|
final EnumSet<Direction> allowedDirections = EnumSet.complementOf(directions);
|
|
return Stream.ofAll(allowedDirections).shuffle().headOption();
|
|
}
|
|
|
|
public static Option<Direction> getRandomExcluding(@NonNull final Direction... directions) {
|
|
return Stream.of(values())
|
|
.removeAll(Stream.of(directions))
|
|
.shuffle()
|
|
.headOption();
|
|
}
|
|
|
|
public Direction getOpposite() {
|
|
switch (this) {
|
|
case TOP:
|
|
return BOTTOM;
|
|
case LEFT:
|
|
return RIGHT;
|
|
case RIGHT:
|
|
return LEFT;
|
|
case BOTTOM:
|
|
return TOP;
|
|
}
|
|
throw new IllegalStateException("Programming error: Not all enum values covered in enum Direction#getOpposite()!");
|
|
}
|
|
|
|
public Position translate(@NonNull final Position position) {
|
|
return this.translation.apply(position);
|
|
}
|
|
}
|