/** I wrote this code recently for a Word Puzzle game I created and this particular class is responsible for processing the touch events that occur when the user swipes on different words within the grid. It's suppose to detect the direction that the swipe took place in so that it can utilize the direction with determine the coordinates between the start and end event of the touch interaction so that it can highlight those letters. **/ class CoordinatesDirectionInteractor @Inject constructor() { private var swipeDirection: SwipeDirection? = null private var swipeType: SwipeType? = null fun detectSwipeDirection(startCoordinate: WordCoordinate, endCoordinate: WordCoordinate): Pair { return when { areCoordinatesInSameRow(startCoordinate, endCoordinate) -> Pair(swipeDirection, swipeType) areCoordinatesInSameColumn(startCoordinate, endCoordinate) -> Pair(swipeDirection, swipeType) else -> { calculateDiagonalCoordinates(startCoordinate, endCoordinate) Pair(swipeDirection, swipeType) } } } private fun areCoordinatesInSameRow(startCoordinate: WordCoordinate, endCoordinate: WordCoordinate): Boolean { if (startCoordinate.y != endCoordinate.y) return false swipeType = Horizontal if (startCoordinate.x < endCoordinate.x) { swipeDirection = W.to(E) } else if (startCoordinate.x > endCoordinate.x) { swipeDirection = E.to(W) } return true } private fun areCoordinatesInSameColumn(startCoordinate: WordCoordinate, endCoordinate: WordCoordinate): Boolean { if (startCoordinate.x != endCoordinate.x) return false swipeType = Vertical if (startCoordinate.y < endCoordinate.y) { swipeDirection = N.to(S) } else if (startCoordinate.y > endCoordinate.y) { swipeDirection = S.to(N) } return true } private fun calculateDiagonalCoordinates(startCoordinate: WordCoordinate, endCoordinate: WordCoordinate): Boolean { val diffX = Math.abs(startCoordinate.x - endCoordinate.x) val diffY = Math.abs(startCoordinate.y - endCoordinate.y) if (diffX == diffY && diffX != 0) { swipeType = Diagonal if (startCoordinate.x > endCoordinate.x && startCoordinate.y < endCoordinate.y) { swipeDirection = NE.to(SW) } if (startCoordinate.x < endCoordinate.x && startCoordinate.y > endCoordinate.y) { swipeDirection = SW.to(NE) } if (startCoordinate.x < endCoordinate.x && startCoordinate.y < endCoordinate.y) { swipeDirection = NW.to(SE) } if (startCoordinate.x > endCoordinate.x && startCoordinate.y > endCoordinate.y) { swipeDirection = SE.to(NW) } } return true } fun Direction.to(value: Direction): SwipeDirection = SwipeDirection(this, value) }