Advertisement
Guest User

Untitled

a guest
Jan 29th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.05 KB | None | 0 0
  1. /**
  2.  * Cardinal and intercardinal directions.
  3.  * @param x the X-value. Grows positively towards the "right".
  4.  * @param y the Y-value. Grows positively upwards.
  5.  */
  6. enum class Direction2D(val x: Int, val y: Int) {
  7.     NONE(0, 0),
  8.     NORTH(0, 1),
  9.     SOUTH(0, -1),
  10.     EAST(1, 0),
  11.     WEST(-1, 0),
  12.     NORTHEAST(1, 1),
  13.     SOUTHEAST(1, -1),
  14.     SOUTHWEST(-1, -1),
  15.     NORTHWEST(-1, 1);
  16.  
  17.     private fun flip(xFlip: Boolean, yFlip: Boolean): Direction2D =
  18.         Direction2D.values().find {
  19.             it.x == (if (xFlip) -x else x) && it.y == (if (yFlip) -y else y)
  20.         } ?: Direction2D.NONE
  21.  
  22.     /**
  23.      * Flips the direction horizontally and vertically
  24.      */
  25.     val flipped: Direction2D
  26.         get() = flip(true, true)
  27.  
  28.     /**
  29.      * Flips the direction's X-values
  30.      */
  31.     val flippedX: Direction2D
  32.         get() = flip(true, false)
  33.  
  34.     /**
  35.      * Flips the direction's Y-values
  36.      */
  37.     val flippedY: Direction2D
  38.         get() = flip(false, true)
  39.  
  40.     private fun Int.limited(): Int = min(1, max(this, -1))
  41.  
  42.     /**
  43.      * Sums with a direction.
  44.      */
  45.     operator fun plus(other: Direction2D): Direction2D =
  46.         values().find {
  47.             it.x == (x + other.x).limited() && it.y == (y + other.y).limited()
  48.         } ?: NONE
  49.  
  50.     /**
  51.      * Subtracts with a direction.
  52.      */
  53.     operator fun minus(other: Direction2D): Direction2D =
  54.         values().find {
  55.             it.x == (x - other.x).limited() && it.y == (y - other.y).limited()
  56.         } ?: NONE
  57.  
  58.     /**
  59.      * Multiplies by a scalar.
  60.      */
  61.     operator fun times(scalar: Int): Point = makePoint(x * scalar, y * scalar)
  62.  
  63.     /**
  64.      * Returns whether this direction contains [other].
  65.      * Specifically, a direction "D" contains another if D [Direction2D.plus] [other] equals D.
  66.      * For example, [NORTHEAST] contains [NORTH] and [EAST], but not [WEST].
  67.      * All directions contain [NONE]. [NONE] contains only [NONE].
  68.      */
  69.     operator fun contains(other: Direction2D): Boolean {
  70.         return this + other == this
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement