diff --git a/src/main/java/core/basesyntax/Main.java b/src/main/java/core/basesyntax/Main.java new file mode 100644 index 00000000..152779f5 --- /dev/null +++ b/src/main/java/core/basesyntax/Main.java @@ -0,0 +1,20 @@ +package core.basesyntax; + +import java.util.Random; + +public class Main { + public static void main(String[] args) { + Random random = new Random(); + Robot robot = new Robot(Direction.UP, 0, 0); + RobotRoute route = new RobotRoute(); + + int toX = random.nextInt(21) - 10; + int toY = random.nextInt(21) - 10; + + route.moveRobot(robot, toX, toY); + + System.out.println("Starting position: " + robot); + System.out.println("Target coordinates: (" + toX + ", " + toY + ")"); + System.out.println("After moving: " + robot); + } +} diff --git a/src/main/java/core/basesyntax/RobotRoute.java b/src/main/java/core/basesyntax/RobotRoute.java index 351ca4b9..0ad75c58 100644 --- a/src/main/java/core/basesyntax/RobotRoute.java +++ b/src/main/java/core/basesyntax/RobotRoute.java @@ -2,6 +2,38 @@ public class RobotRoute { public void moveRobot(Robot robot, int toX, int toY) { - //write your solution here + //write your solution here + int currentX = robot.getX(); + int currentY = robot.getY(); + + if (toX > currentX) { + turnToDirection(robot, Direction.RIGHT); + while (robot.getX() < toX) { + robot.stepForward(); + } + } else if (toX < currentX) { + turnToDirection(robot, Direction.LEFT); + while (robot.getX() > toX) { + robot.stepForward(); + } + } + if (toY > currentY) { + turnToDirection(robot, Direction.UP); + while (robot.getY() < toY) { + robot.stepForward(); + } + } else if (toY < currentY) { + turnToDirection(robot, Direction.DOWN); + while (robot.getY() > toY) { + robot.stepForward(); + } + } + } + + private void turnToDirection(Robot robot, Direction targetDirection) { + while (robot.getDirection() != targetDirection) { + robot.turnLeft(); + robot.turnRight(); + } } }