From af3de4f4f612f542fefd3813ef7a8f6c2923819b Mon Sep 17 00:00:00 2001 From: Volodymyr Kulesha Date: Sun, 7 Apr 2024 20:40:40 +0300 Subject: [PATCH] added task solution to RobotRoute --- src/main/java/core/basesyntax/RobotRoute.java | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/src/main/java/core/basesyntax/RobotRoute.java b/src/main/java/core/basesyntax/RobotRoute.java index 351ca4b9..8bccc851 100644 --- a/src/main/java/core/basesyntax/RobotRoute.java +++ b/src/main/java/core/basesyntax/RobotRoute.java @@ -2,6 +2,52 @@ public class RobotRoute { public void moveRobot(Robot robot, int toX, int toY) { - //write your solution here + moveRobotToTheVerticalPoint(robot, toY); + moveRobotToTheHorizontalPoint(robot, toX); + } + + private void moveRobotToTheVerticalPoint(Robot robot, int toY) { + if (robot.getY() == toY) { + return; + } + + int verticalDistanceToTheTarget = robot.getY() - toY; + if (verticalDistanceToTheTarget < 0) { + turnRobotToTheDirection(robot, Direction.UP); + verticalDistanceToTheTarget *= -1; + } else { + turnRobotToTheDirection(robot, Direction.DOWN); + } + + stepForwardToTheTarget(robot, verticalDistanceToTheTarget); + } + + private void moveRobotToTheHorizontalPoint(Robot robot, int toX) { + if (robot.getX() == toX) { + return; + } + + int horizontalDistanceToTheTarget = robot.getX() - toX; + if (horizontalDistanceToTheTarget < 0) { + turnRobotToTheDirection(robot, Direction.RIGHT); + horizontalDistanceToTheTarget *= -1; + } else { + turnRobotToTheDirection(robot, Direction.LEFT); + } + + stepForwardToTheTarget(robot, horizontalDistanceToTheTarget); + } + + private void turnRobotToTheDirection(Robot robot, Direction neededDirection) { + while (robot.getDirection() != neededDirection) { + robot.turnRight(); + } + } + + private void stepForwardToTheTarget(Robot robot, int stepsQuantity) { + while (stepsQuantity > 0) { + robot.stepForward(); + stepsQuantity--; + } } }