From ac744b9f965ac3e28f9d48e51f3b8cedbfe903bc Mon Sep 17 00:00:00 2001 From: Oksana Miazina Date: Fri, 16 Feb 2024 14:28:59 +0200 Subject: [PATCH] feat: implement RobotRoute --- src/main/java/core/basesyntax/RobotRoute.java | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/main/java/core/basesyntax/RobotRoute.java b/src/main/java/core/basesyntax/RobotRoute.java index 351ca4b9..5a4225b7 100644 --- a/src/main/java/core/basesyntax/RobotRoute.java +++ b/src/main/java/core/basesyntax/RobotRoute.java @@ -2,6 +2,35 @@ public class RobotRoute { public void moveRobot(Robot robot, int toX, int toY) { - //write your solution here + moveRobotHorizontal(robot, toX); + moveRobotVertical(robot, toY); + } + + private void moveRobotVertical(Robot robot, int toY) { + int fromY = robot.getY(); + Direction verticalDirection = fromY - toY > 0 ? Direction.DOWN : Direction.UP; + + turnRobotTo(robot, verticalDirection); + makeRobotNSteps(robot, Math.abs(fromY - toY)); + } + + private void moveRobotHorizontal(Robot robot, int toX) { + int fromX = robot.getX(); + Direction horizontalDirection = fromX - toX > 0 ? Direction.LEFT : Direction.RIGHT; + + turnRobotTo(robot, horizontalDirection); + makeRobotNSteps(robot, Math.abs(fromX - toX)); + } + + private void turnRobotTo(Robot robot, Direction direction) { + while (robot.getDirection() != direction) { + robot.turnLeft(); + } + } + + private void makeRobotNSteps(Robot robot, int steps) { + for (int i = 0; i < steps; i++) { + robot.stepForward(); + } } }